xref: /aosp_15_r20/external/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // Hacks and fun related to the code rewriter.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Rewrite/Frontend/ASTConsumers.h"
15*67e74705SXin Li #include "clang/AST/AST.h"
16*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
17*67e74705SXin Li #include "clang/AST/Attr.h"
18*67e74705SXin Li #include "clang/AST/ParentMap.h"
19*67e74705SXin Li #include "clang/Basic/CharInfo.h"
20*67e74705SXin Li #include "clang/Basic/Diagnostic.h"
21*67e74705SXin Li #include "clang/Basic/IdentifierTable.h"
22*67e74705SXin Li #include "clang/Basic/SourceManager.h"
23*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
24*67e74705SXin Li #include "clang/Lex/Lexer.h"
25*67e74705SXin Li #include "clang/Rewrite/Core/Rewriter.h"
26*67e74705SXin Li #include "llvm/ADT/DenseSet.h"
27*67e74705SXin Li #include "llvm/ADT/SmallPtrSet.h"
28*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
29*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
30*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
31*67e74705SXin Li #include <memory>
32*67e74705SXin Li 
33*67e74705SXin Li #ifdef CLANG_ENABLE_OBJC_REWRITER
34*67e74705SXin Li 
35*67e74705SXin Li using namespace clang;
36*67e74705SXin Li using llvm::utostr;
37*67e74705SXin Li 
38*67e74705SXin Li namespace {
39*67e74705SXin Li   class RewriteModernObjC : public ASTConsumer {
40*67e74705SXin Li   protected:
41*67e74705SXin Li 
42*67e74705SXin Li     enum {
43*67e74705SXin Li       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
44*67e74705SXin Li                                         block, ... */
45*67e74705SXin Li       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
46*67e74705SXin Li       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
47*67e74705SXin Li                                         __block variable */
48*67e74705SXin Li       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
49*67e74705SXin Li                                         helpers */
50*67e74705SXin Li       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
51*67e74705SXin Li                                         support routines */
52*67e74705SXin Li       BLOCK_BYREF_CURRENT_MAX = 256
53*67e74705SXin Li     };
54*67e74705SXin Li 
55*67e74705SXin Li     enum {
56*67e74705SXin Li       BLOCK_NEEDS_FREE =        (1 << 24),
57*67e74705SXin Li       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
58*67e74705SXin Li       BLOCK_HAS_CXX_OBJ =       (1 << 26),
59*67e74705SXin Li       BLOCK_IS_GC =             (1 << 27),
60*67e74705SXin Li       BLOCK_IS_GLOBAL =         (1 << 28),
61*67e74705SXin Li       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
62*67e74705SXin Li     };
63*67e74705SXin Li 
64*67e74705SXin Li     Rewriter Rewrite;
65*67e74705SXin Li     DiagnosticsEngine &Diags;
66*67e74705SXin Li     const LangOptions &LangOpts;
67*67e74705SXin Li     ASTContext *Context;
68*67e74705SXin Li     SourceManager *SM;
69*67e74705SXin Li     TranslationUnitDecl *TUDecl;
70*67e74705SXin Li     FileID MainFileID;
71*67e74705SXin Li     const char *MainFileStart, *MainFileEnd;
72*67e74705SXin Li     Stmt *CurrentBody;
73*67e74705SXin Li     ParentMap *PropParentMap; // created lazily.
74*67e74705SXin Li     std::string InFileName;
75*67e74705SXin Li     raw_ostream* OutFile;
76*67e74705SXin Li     std::string Preamble;
77*67e74705SXin Li 
78*67e74705SXin Li     TypeDecl *ProtocolTypeDecl;
79*67e74705SXin Li     VarDecl *GlobalVarDecl;
80*67e74705SXin Li     Expr *GlobalConstructionExp;
81*67e74705SXin Li     unsigned RewriteFailedDiag;
82*67e74705SXin Li     unsigned GlobalBlockRewriteFailedDiag;
83*67e74705SXin Li     // ObjC string constant support.
84*67e74705SXin Li     unsigned NumObjCStringLiterals;
85*67e74705SXin Li     VarDecl *ConstantStringClassReference;
86*67e74705SXin Li     RecordDecl *NSStringRecord;
87*67e74705SXin Li 
88*67e74705SXin Li     // ObjC foreach break/continue generation support.
89*67e74705SXin Li     int BcLabelCount;
90*67e74705SXin Li 
91*67e74705SXin Li     unsigned TryFinallyContainsReturnDiag;
92*67e74705SXin Li     // Needed for super.
93*67e74705SXin Li     ObjCMethodDecl *CurMethodDef;
94*67e74705SXin Li     RecordDecl *SuperStructDecl;
95*67e74705SXin Li     RecordDecl *ConstantStringDecl;
96*67e74705SXin Li 
97*67e74705SXin Li     FunctionDecl *MsgSendFunctionDecl;
98*67e74705SXin Li     FunctionDecl *MsgSendSuperFunctionDecl;
99*67e74705SXin Li     FunctionDecl *MsgSendStretFunctionDecl;
100*67e74705SXin Li     FunctionDecl *MsgSendSuperStretFunctionDecl;
101*67e74705SXin Li     FunctionDecl *MsgSendFpretFunctionDecl;
102*67e74705SXin Li     FunctionDecl *GetClassFunctionDecl;
103*67e74705SXin Li     FunctionDecl *GetMetaClassFunctionDecl;
104*67e74705SXin Li     FunctionDecl *GetSuperClassFunctionDecl;
105*67e74705SXin Li     FunctionDecl *SelGetUidFunctionDecl;
106*67e74705SXin Li     FunctionDecl *CFStringFunctionDecl;
107*67e74705SXin Li     FunctionDecl *SuperConstructorFunctionDecl;
108*67e74705SXin Li     FunctionDecl *CurFunctionDef;
109*67e74705SXin Li 
110*67e74705SXin Li     /* Misc. containers needed for meta-data rewrite. */
111*67e74705SXin Li     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112*67e74705SXin Li     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113*67e74705SXin Li     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114*67e74705SXin Li     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115*67e74705SXin Li     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116*67e74705SXin Li     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117*67e74705SXin Li     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118*67e74705SXin Li     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119*67e74705SXin Li     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120*67e74705SXin Li 
121*67e74705SXin Li     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122*67e74705SXin Li     SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123*67e74705SXin Li 
124*67e74705SXin Li     SmallVector<Stmt *, 32> Stmts;
125*67e74705SXin Li     SmallVector<int, 8> ObjCBcLabelNo;
126*67e74705SXin Li     // Remember all the @protocol(<expr>) expressions.
127*67e74705SXin Li     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128*67e74705SXin Li 
129*67e74705SXin Li     llvm::DenseSet<uint64_t> CopyDestroyCache;
130*67e74705SXin Li 
131*67e74705SXin Li     // Block expressions.
132*67e74705SXin Li     SmallVector<BlockExpr *, 32> Blocks;
133*67e74705SXin Li     SmallVector<int, 32> InnerDeclRefsCount;
134*67e74705SXin Li     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135*67e74705SXin Li 
136*67e74705SXin Li     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137*67e74705SXin Li 
138*67e74705SXin Li     // Block related declarations.
139*67e74705SXin Li     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140*67e74705SXin Li     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141*67e74705SXin Li     SmallVector<ValueDecl *, 8> BlockByRefDecls;
142*67e74705SXin Li     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143*67e74705SXin Li     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144*67e74705SXin Li     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145*67e74705SXin Li     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146*67e74705SXin Li 
147*67e74705SXin Li     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
148*67e74705SXin Li     llvm::DenseMap<ObjCInterfaceDecl *,
149*67e74705SXin Li                     llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
150*67e74705SXin Li 
151*67e74705SXin Li     // ivar bitfield grouping containers
152*67e74705SXin Li     llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153*67e74705SXin Li     llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154*67e74705SXin Li     // This container maps an <class, group number for ivar> tuple to the type
155*67e74705SXin Li     // of the struct where the bitfield belongs.
156*67e74705SXin Li     llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
157*67e74705SXin Li     SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
158*67e74705SXin Li 
159*67e74705SXin Li     // This maps an original source AST to it's rewritten form. This allows
160*67e74705SXin Li     // us to avoid rewriting the same node twice (which is very uncommon).
161*67e74705SXin Li     // This is needed to support some of the exotic property rewriting.
162*67e74705SXin Li     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163*67e74705SXin Li 
164*67e74705SXin Li     // Needed for header files being rewritten
165*67e74705SXin Li     bool IsHeader;
166*67e74705SXin Li     bool SilenceRewriteMacroWarning;
167*67e74705SXin Li     bool GenerateLineInfo;
168*67e74705SXin Li     bool objc_impl_method;
169*67e74705SXin Li 
170*67e74705SXin Li     bool DisableReplaceStmt;
171*67e74705SXin Li     class DisableReplaceStmtScope {
172*67e74705SXin Li       RewriteModernObjC &R;
173*67e74705SXin Li       bool SavedValue;
174*67e74705SXin Li 
175*67e74705SXin Li     public:
DisableReplaceStmtScope(RewriteModernObjC & R)176*67e74705SXin Li       DisableReplaceStmtScope(RewriteModernObjC &R)
177*67e74705SXin Li         : R(R), SavedValue(R.DisableReplaceStmt) {
178*67e74705SXin Li         R.DisableReplaceStmt = true;
179*67e74705SXin Li       }
~DisableReplaceStmtScope()180*67e74705SXin Li       ~DisableReplaceStmtScope() {
181*67e74705SXin Li         R.DisableReplaceStmt = SavedValue;
182*67e74705SXin Li       }
183*67e74705SXin Li     };
184*67e74705SXin Li     void InitializeCommon(ASTContext &context);
185*67e74705SXin Li 
186*67e74705SXin Li   public:
187*67e74705SXin Li     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
188*67e74705SXin Li 
189*67e74705SXin Li     // Top Level Driver code.
HandleTopLevelDecl(DeclGroupRef D)190*67e74705SXin Li     bool HandleTopLevelDecl(DeclGroupRef D) override {
191*67e74705SXin Li       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192*67e74705SXin Li         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193*67e74705SXin Li           if (!Class->isThisDeclarationADefinition()) {
194*67e74705SXin Li             RewriteForwardClassDecl(D);
195*67e74705SXin Li             break;
196*67e74705SXin Li           } else {
197*67e74705SXin Li             // Keep track of all interface declarations seen.
198*67e74705SXin Li             ObjCInterfacesSeen.push_back(Class);
199*67e74705SXin Li             break;
200*67e74705SXin Li           }
201*67e74705SXin Li         }
202*67e74705SXin Li 
203*67e74705SXin Li         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204*67e74705SXin Li           if (!Proto->isThisDeclarationADefinition()) {
205*67e74705SXin Li             RewriteForwardProtocolDecl(D);
206*67e74705SXin Li             break;
207*67e74705SXin Li           }
208*67e74705SXin Li         }
209*67e74705SXin Li 
210*67e74705SXin Li         if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211*67e74705SXin Li           // Under modern abi, we cannot translate body of the function
212*67e74705SXin Li           // yet until all class extensions and its implementation is seen.
213*67e74705SXin Li           // This is because they may introduce new bitfields which must go
214*67e74705SXin Li           // into their grouping struct.
215*67e74705SXin Li           if (FDecl->isThisDeclarationADefinition() &&
216*67e74705SXin Li               // Not c functions defined inside an objc container.
217*67e74705SXin Li               !FDecl->isTopLevelDeclInObjCContainer()) {
218*67e74705SXin Li             FunctionDefinitionsSeen.push_back(FDecl);
219*67e74705SXin Li             break;
220*67e74705SXin Li           }
221*67e74705SXin Li         }
222*67e74705SXin Li         HandleTopLevelSingleDecl(*I);
223*67e74705SXin Li       }
224*67e74705SXin Li       return true;
225*67e74705SXin Li     }
226*67e74705SXin Li 
HandleTopLevelDeclInObjCContainer(DeclGroupRef D)227*67e74705SXin Li     void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228*67e74705SXin Li       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229*67e74705SXin Li         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230*67e74705SXin Li           if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231*67e74705SXin Li             RewriteBlockPointerDecl(TD);
232*67e74705SXin Li           else if (TD->getUnderlyingType()->isFunctionPointerType())
233*67e74705SXin Li             CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234*67e74705SXin Li           else
235*67e74705SXin Li             RewriteObjCQualifiedInterfaceTypes(TD);
236*67e74705SXin Li         }
237*67e74705SXin Li       }
238*67e74705SXin Li     }
239*67e74705SXin Li 
240*67e74705SXin Li     void HandleTopLevelSingleDecl(Decl *D);
241*67e74705SXin Li     void HandleDeclInMainFile(Decl *D);
242*67e74705SXin Li     RewriteModernObjC(std::string inFile, raw_ostream *OS,
243*67e74705SXin Li                 DiagnosticsEngine &D, const LangOptions &LOpts,
244*67e74705SXin Li                 bool silenceMacroWarn, bool LineInfo);
245*67e74705SXin Li 
~RewriteModernObjC()246*67e74705SXin Li     ~RewriteModernObjC() override {}
247*67e74705SXin Li 
248*67e74705SXin Li     void HandleTranslationUnit(ASTContext &C) override;
249*67e74705SXin Li 
ReplaceStmt(Stmt * Old,Stmt * New)250*67e74705SXin Li     void ReplaceStmt(Stmt *Old, Stmt *New) {
251*67e74705SXin Li       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
252*67e74705SXin Li     }
253*67e74705SXin Li 
ReplaceStmtWithRange(Stmt * Old,Stmt * New,SourceRange SrcRange)254*67e74705SXin Li     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255*67e74705SXin Li       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
256*67e74705SXin Li 
257*67e74705SXin Li       Stmt *ReplacingStmt = ReplacedNodes[Old];
258*67e74705SXin Li       if (ReplacingStmt)
259*67e74705SXin Li         return; // We can't rewrite the same node twice.
260*67e74705SXin Li 
261*67e74705SXin Li       if (DisableReplaceStmt)
262*67e74705SXin Li         return;
263*67e74705SXin Li 
264*67e74705SXin Li       // Measure the old text.
265*67e74705SXin Li       int Size = Rewrite.getRangeSize(SrcRange);
266*67e74705SXin Li       if (Size == -1) {
267*67e74705SXin Li         Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
268*67e74705SXin Li                      << Old->getSourceRange();
269*67e74705SXin Li         return;
270*67e74705SXin Li       }
271*67e74705SXin Li       // Get the new text.
272*67e74705SXin Li       std::string SStr;
273*67e74705SXin Li       llvm::raw_string_ostream S(SStr);
274*67e74705SXin Li       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
275*67e74705SXin Li       const std::string &Str = S.str();
276*67e74705SXin Li 
277*67e74705SXin Li       // If replacement succeeded or warning disabled return with no warning.
278*67e74705SXin Li       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279*67e74705SXin Li         ReplacedNodes[Old] = New;
280*67e74705SXin Li         return;
281*67e74705SXin Li       }
282*67e74705SXin Li       if (SilenceRewriteMacroWarning)
283*67e74705SXin Li         return;
284*67e74705SXin Li       Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
285*67e74705SXin Li                    << Old->getSourceRange();
286*67e74705SXin Li     }
287*67e74705SXin Li 
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter=true)288*67e74705SXin Li     void InsertText(SourceLocation Loc, StringRef Str,
289*67e74705SXin Li                     bool InsertAfter = true) {
290*67e74705SXin Li       // If insertion succeeded or warning disabled return with no warning.
291*67e74705SXin Li       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292*67e74705SXin Li           SilenceRewriteMacroWarning)
293*67e74705SXin Li         return;
294*67e74705SXin Li 
295*67e74705SXin Li       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296*67e74705SXin Li     }
297*67e74705SXin Li 
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef Str)298*67e74705SXin Li     void ReplaceText(SourceLocation Start, unsigned OrigLength,
299*67e74705SXin Li                      StringRef Str) {
300*67e74705SXin Li       // If removal succeeded or warning disabled return with no warning.
301*67e74705SXin Li       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302*67e74705SXin Li           SilenceRewriteMacroWarning)
303*67e74705SXin Li         return;
304*67e74705SXin Li 
305*67e74705SXin Li       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306*67e74705SXin Li     }
307*67e74705SXin Li 
308*67e74705SXin Li     // Syntactic Rewriting.
309*67e74705SXin Li     void RewriteRecordBody(RecordDecl *RD);
310*67e74705SXin Li     void RewriteInclude();
311*67e74705SXin Li     void RewriteLineDirective(const Decl *D);
312*67e74705SXin Li     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313*67e74705SXin Li                                               std::string &LineString);
314*67e74705SXin Li     void RewriteForwardClassDecl(DeclGroupRef D);
315*67e74705SXin Li     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
316*67e74705SXin Li     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317*67e74705SXin Li                                      const std::string &typedefString);
318*67e74705SXin Li     void RewriteImplementations();
319*67e74705SXin Li     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320*67e74705SXin Li                                  ObjCImplementationDecl *IMD,
321*67e74705SXin Li                                  ObjCCategoryImplDecl *CID);
322*67e74705SXin Li     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323*67e74705SXin Li     void RewriteImplementationDecl(Decl *Dcl);
324*67e74705SXin Li     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325*67e74705SXin Li                                ObjCMethodDecl *MDecl, std::string &ResultStr);
326*67e74705SXin Li     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327*67e74705SXin Li                                const FunctionType *&FPRetType);
328*67e74705SXin Li     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329*67e74705SXin Li                             ValueDecl *VD, bool def=false);
330*67e74705SXin Li     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331*67e74705SXin Li     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332*67e74705SXin Li     void RewriteForwardProtocolDecl(DeclGroupRef D);
333*67e74705SXin Li     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
334*67e74705SXin Li     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335*67e74705SXin Li     void RewriteProperty(ObjCPropertyDecl *prop);
336*67e74705SXin Li     void RewriteFunctionDecl(FunctionDecl *FD);
337*67e74705SXin Li     void RewriteBlockPointerType(std::string& Str, QualType Type);
338*67e74705SXin Li     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
339*67e74705SXin Li     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
340*67e74705SXin Li     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341*67e74705SXin Li     void RewriteTypeOfDecl(VarDecl *VD);
342*67e74705SXin Li     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
343*67e74705SXin Li 
344*67e74705SXin Li     std::string getIvarAccessString(ObjCIvarDecl *D);
345*67e74705SXin Li 
346*67e74705SXin Li     // Expression Rewriting.
347*67e74705SXin Li     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348*67e74705SXin Li     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349*67e74705SXin Li     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350*67e74705SXin Li     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351*67e74705SXin Li     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352*67e74705SXin Li     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353*67e74705SXin Li     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
354*67e74705SXin Li     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
355*67e74705SXin Li     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
356*67e74705SXin Li     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
357*67e74705SXin Li     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
358*67e74705SXin Li     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
359*67e74705SXin Li     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
360*67e74705SXin Li     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
361*67e74705SXin Li     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362*67e74705SXin Li     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363*67e74705SXin Li     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364*67e74705SXin Li                                        SourceLocation OrigEnd);
365*67e74705SXin Li     Stmt *RewriteBreakStmt(BreakStmt *S);
366*67e74705SXin Li     Stmt *RewriteContinueStmt(ContinueStmt *S);
367*67e74705SXin Li     void RewriteCastExpr(CStyleCastExpr *CE);
368*67e74705SXin Li     void RewriteImplicitCastObjCExpr(CastExpr *IE);
369*67e74705SXin Li 
370*67e74705SXin Li     // Computes ivar bitfield group no.
371*67e74705SXin Li     unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372*67e74705SXin Li     // Names field decl. for ivar bitfield group.
373*67e74705SXin Li     void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374*67e74705SXin Li     // Names struct type for ivar bitfield group.
375*67e74705SXin Li     void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376*67e74705SXin Li     // Names symbol for ivar bitfield group field offset.
377*67e74705SXin Li     void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378*67e74705SXin Li     // Given an ivar bitfield, it builds (or finds) its group record type.
379*67e74705SXin Li     QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380*67e74705SXin Li     QualType SynthesizeBitfieldGroupStructType(
381*67e74705SXin Li                                     ObjCIvarDecl *IV,
382*67e74705SXin Li                                     SmallVectorImpl<ObjCIvarDecl *> &IVars);
383*67e74705SXin Li 
384*67e74705SXin Li     // Block rewriting.
385*67e74705SXin Li     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386*67e74705SXin Li 
387*67e74705SXin Li     // Block specific rewrite rules.
388*67e74705SXin Li     void RewriteBlockPointerDecl(NamedDecl *VD);
389*67e74705SXin Li     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
390*67e74705SXin Li     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
391*67e74705SXin Li     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392*67e74705SXin Li     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393*67e74705SXin Li 
394*67e74705SXin Li     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395*67e74705SXin Li                                       std::string &Result);
396*67e74705SXin Li 
397*67e74705SXin Li     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
398*67e74705SXin Li     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
399*67e74705SXin Li                                  bool &IsNamedDefinition);
400*67e74705SXin Li     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401*67e74705SXin Li                                               std::string &Result);
402*67e74705SXin Li 
403*67e74705SXin Li     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404*67e74705SXin Li 
405*67e74705SXin Li     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406*67e74705SXin Li                                   std::string &Result);
407*67e74705SXin Li 
408*67e74705SXin Li     void Initialize(ASTContext &context) override;
409*67e74705SXin Li 
410*67e74705SXin Li     // Misc. AST transformation routines. Sometimes they end up calling
411*67e74705SXin Li     // rewriting routines on the new ASTs.
412*67e74705SXin Li     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
413*67e74705SXin Li                                            ArrayRef<Expr *> Args,
414*67e74705SXin Li                                            SourceLocation StartLoc=SourceLocation(),
415*67e74705SXin Li                                            SourceLocation EndLoc=SourceLocation());
416*67e74705SXin Li 
417*67e74705SXin Li     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
418*67e74705SXin Li                                         QualType returnType,
419*67e74705SXin Li                                         SmallVectorImpl<QualType> &ArgTypes,
420*67e74705SXin Li                                         SmallVectorImpl<Expr*> &MsgExprs,
421*67e74705SXin Li                                         ObjCMethodDecl *Method);
422*67e74705SXin Li 
423*67e74705SXin Li     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424*67e74705SXin Li                            SourceLocation StartLoc=SourceLocation(),
425*67e74705SXin Li                            SourceLocation EndLoc=SourceLocation());
426*67e74705SXin Li 
427*67e74705SXin Li     void SynthCountByEnumWithState(std::string &buf);
428*67e74705SXin Li     void SynthMsgSendFunctionDecl();
429*67e74705SXin Li     void SynthMsgSendSuperFunctionDecl();
430*67e74705SXin Li     void SynthMsgSendStretFunctionDecl();
431*67e74705SXin Li     void SynthMsgSendFpretFunctionDecl();
432*67e74705SXin Li     void SynthMsgSendSuperStretFunctionDecl();
433*67e74705SXin Li     void SynthGetClassFunctionDecl();
434*67e74705SXin Li     void SynthGetMetaClassFunctionDecl();
435*67e74705SXin Li     void SynthGetSuperClassFunctionDecl();
436*67e74705SXin Li     void SynthSelGetUidFunctionDecl();
437*67e74705SXin Li     void SynthSuperConstructorFunctionDecl();
438*67e74705SXin Li 
439*67e74705SXin Li     // Rewriting metadata
440*67e74705SXin Li     template<typename MethodIterator>
441*67e74705SXin Li     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442*67e74705SXin Li                                     MethodIterator MethodEnd,
443*67e74705SXin Li                                     bool IsInstanceMethod,
444*67e74705SXin Li                                     StringRef prefix,
445*67e74705SXin Li                                     StringRef ClassName,
446*67e74705SXin Li                                     std::string &Result);
447*67e74705SXin Li     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448*67e74705SXin Li                                      std::string &Result);
449*67e74705SXin Li     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
450*67e74705SXin Li                                           std::string &Result);
451*67e74705SXin Li     void RewriteClassSetupInitHook(std::string &Result);
452*67e74705SXin Li 
453*67e74705SXin Li     void RewriteMetaDataIntoBuffer(std::string &Result);
454*67e74705SXin Li     void WriteImageInfo(std::string &Result);
455*67e74705SXin Li     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
456*67e74705SXin Li                                              std::string &Result);
457*67e74705SXin Li     void RewriteCategorySetupInitHook(std::string &Result);
458*67e74705SXin Li 
459*67e74705SXin Li     // Rewriting ivar
460*67e74705SXin Li     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
461*67e74705SXin Li                                               std::string &Result);
462*67e74705SXin Li     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
463*67e74705SXin Li 
464*67e74705SXin Li 
465*67e74705SXin Li     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466*67e74705SXin Li     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467*67e74705SXin Li                                       StringRef funcName, std::string Tag);
468*67e74705SXin Li     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469*67e74705SXin Li                                       StringRef funcName, std::string Tag);
470*67e74705SXin Li     std::string SynthesizeBlockImpl(BlockExpr *CE,
471*67e74705SXin Li                                     std::string Tag, std::string Desc);
472*67e74705SXin Li     std::string SynthesizeBlockDescriptor(std::string DescTag,
473*67e74705SXin Li                                           std::string ImplTag,
474*67e74705SXin Li                                           int i, StringRef funcName,
475*67e74705SXin Li                                           unsigned hasCopy);
476*67e74705SXin Li     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477*67e74705SXin Li     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478*67e74705SXin Li                                  StringRef FunName);
479*67e74705SXin Li     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480*67e74705SXin Li     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
481*67e74705SXin Li                       const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
482*67e74705SXin Li 
483*67e74705SXin Li     // Misc. helper routines.
484*67e74705SXin Li     QualType getProtocolType();
485*67e74705SXin Li     void WarnAboutReturnGotoStmts(Stmt *S);
486*67e74705SXin Li     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487*67e74705SXin Li     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488*67e74705SXin Li     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489*67e74705SXin Li 
490*67e74705SXin Li     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491*67e74705SXin Li     void CollectBlockDeclRefInfo(BlockExpr *Exp);
492*67e74705SXin Li     void GetBlockDeclRefExprs(Stmt *S);
493*67e74705SXin Li     void GetInnerBlockDeclRefExprs(Stmt *S,
494*67e74705SXin Li                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
495*67e74705SXin Li                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
496*67e74705SXin Li 
497*67e74705SXin Li     // We avoid calling Type::isBlockPointerType(), since it operates on the
498*67e74705SXin Li     // canonical type. We only care if the top-level type is a closure pointer.
isTopLevelBlockPointerType(QualType T)499*67e74705SXin Li     bool isTopLevelBlockPointerType(QualType T) {
500*67e74705SXin Li       return isa<BlockPointerType>(T);
501*67e74705SXin Li     }
502*67e74705SXin Li 
503*67e74705SXin Li     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504*67e74705SXin Li     /// to a function pointer type and upon success, returns true; false
505*67e74705SXin Li     /// otherwise.
convertBlockPointerToFunctionPointer(QualType & T)506*67e74705SXin Li     bool convertBlockPointerToFunctionPointer(QualType &T) {
507*67e74705SXin Li       if (isTopLevelBlockPointerType(T)) {
508*67e74705SXin Li         const BlockPointerType *BPT = T->getAs<BlockPointerType>();
509*67e74705SXin Li         T = Context->getPointerType(BPT->getPointeeType());
510*67e74705SXin Li         return true;
511*67e74705SXin Li       }
512*67e74705SXin Li       return false;
513*67e74705SXin Li     }
514*67e74705SXin Li 
515*67e74705SXin Li     bool convertObjCTypeToCStyleType(QualType &T);
516*67e74705SXin Li 
517*67e74705SXin Li     bool needToScanForQualifiers(QualType T);
518*67e74705SXin Li     QualType getSuperStructType();
519*67e74705SXin Li     QualType getConstantStringStructType();
520*67e74705SXin Li     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521*67e74705SXin Li 
convertToUnqualifiedObjCType(QualType & T)522*67e74705SXin Li     void convertToUnqualifiedObjCType(QualType &T) {
523*67e74705SXin Li       if (T->isObjCQualifiedIdType()) {
524*67e74705SXin Li         bool isConst = T.isConstQualified();
525*67e74705SXin Li         T = isConst ? Context->getObjCIdType().withConst()
526*67e74705SXin Li                     : Context->getObjCIdType();
527*67e74705SXin Li       }
528*67e74705SXin Li       else if (T->isObjCQualifiedClassType())
529*67e74705SXin Li         T = Context->getObjCClassType();
530*67e74705SXin Li       else if (T->isObjCObjectPointerType() &&
531*67e74705SXin Li                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532*67e74705SXin Li         if (const ObjCObjectPointerType * OBJPT =
533*67e74705SXin Li               T->getAsObjCInterfacePointerType()) {
534*67e74705SXin Li           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535*67e74705SXin Li           T = QualType(IFaceT, 0);
536*67e74705SXin Li           T = Context->getPointerType(T);
537*67e74705SXin Li         }
538*67e74705SXin Li      }
539*67e74705SXin Li     }
540*67e74705SXin Li 
541*67e74705SXin Li     // FIXME: This predicate seems like it would be useful to add to ASTContext.
isObjCType(QualType T)542*67e74705SXin Li     bool isObjCType(QualType T) {
543*67e74705SXin Li       if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
544*67e74705SXin Li         return false;
545*67e74705SXin Li 
546*67e74705SXin Li       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547*67e74705SXin Li 
548*67e74705SXin Li       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549*67e74705SXin Li           OCT == Context->getCanonicalType(Context->getObjCClassType()))
550*67e74705SXin Li         return true;
551*67e74705SXin Li 
552*67e74705SXin Li       if (const PointerType *PT = OCT->getAs<PointerType>()) {
553*67e74705SXin Li         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554*67e74705SXin Li             PT->getPointeeType()->isObjCQualifiedIdType())
555*67e74705SXin Li           return true;
556*67e74705SXin Li       }
557*67e74705SXin Li       return false;
558*67e74705SXin Li     }
559*67e74705SXin Li 
560*67e74705SXin Li     bool PointerTypeTakesAnyBlockArguments(QualType QT);
561*67e74705SXin Li     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562*67e74705SXin Li     void GetExtentOfArgList(const char *Name, const char *&LParen,
563*67e74705SXin Li                             const char *&RParen);
564*67e74705SXin Li 
QuoteDoublequotes(std::string & From,std::string & To)565*67e74705SXin Li     void QuoteDoublequotes(std::string &From, std::string &To) {
566*67e74705SXin Li       for (unsigned i = 0; i < From.length(); i++) {
567*67e74705SXin Li         if (From[i] == '"')
568*67e74705SXin Li           To += "\\\"";
569*67e74705SXin Li         else
570*67e74705SXin Li           To += From[i];
571*67e74705SXin Li       }
572*67e74705SXin Li     }
573*67e74705SXin Li 
getSimpleFunctionType(QualType result,ArrayRef<QualType> args,bool variadic=false)574*67e74705SXin Li     QualType getSimpleFunctionType(QualType result,
575*67e74705SXin Li                                    ArrayRef<QualType> args,
576*67e74705SXin Li                                    bool variadic = false) {
577*67e74705SXin Li       if (result == Context->getObjCInstanceType())
578*67e74705SXin Li         result =  Context->getObjCIdType();
579*67e74705SXin Li       FunctionProtoType::ExtProtoInfo fpi;
580*67e74705SXin Li       fpi.Variadic = variadic;
581*67e74705SXin Li       return Context->getFunctionType(result, args, fpi);
582*67e74705SXin Li     }
583*67e74705SXin Li 
584*67e74705SXin Li     // Helper function: create a CStyleCastExpr with trivial type source info.
NoTypeInfoCStyleCastExpr(ASTContext * Ctx,QualType Ty,CastKind Kind,Expr * E)585*67e74705SXin Li     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586*67e74705SXin Li                                              CastKind Kind, Expr *E) {
587*67e74705SXin Li       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588*67e74705SXin Li       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589*67e74705SXin Li                                     TInfo, SourceLocation(), SourceLocation());
590*67e74705SXin Li     }
591*67e74705SXin Li 
ImplementationIsNonLazy(const ObjCImplDecl * OD) const592*67e74705SXin Li     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593*67e74705SXin Li       IdentifierInfo* II = &Context->Idents.get("load");
594*67e74705SXin Li       Selector LoadSel = Context->Selectors.getSelector(0, &II);
595*67e74705SXin Li       return OD->getClassMethod(LoadSel) != nullptr;
596*67e74705SXin Li     }
597*67e74705SXin Li 
getStringLiteral(StringRef Str)598*67e74705SXin Li     StringLiteral *getStringLiteral(StringRef Str) {
599*67e74705SXin Li       QualType StrType = Context->getConstantArrayType(
600*67e74705SXin Li           Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
601*67e74705SXin Li           0);
602*67e74705SXin Li       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603*67e74705SXin Li                                    /*Pascal=*/false, StrType, SourceLocation());
604*67e74705SXin Li     }
605*67e74705SXin Li   };
606*67e74705SXin Li } // end anonymous namespace
607*67e74705SXin Li 
RewriteBlocksInFunctionProtoType(QualType funcType,NamedDecl * D)608*67e74705SXin Li void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609*67e74705SXin Li                                                    NamedDecl *D) {
610*67e74705SXin Li   if (const FunctionProtoType *fproto
611*67e74705SXin Li       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
612*67e74705SXin Li     for (const auto &I : fproto->param_types())
613*67e74705SXin Li       if (isTopLevelBlockPointerType(I)) {
614*67e74705SXin Li         // All the args are checked/rewritten. Don't call twice!
615*67e74705SXin Li         RewriteBlockPointerDecl(D);
616*67e74705SXin Li         break;
617*67e74705SXin Li       }
618*67e74705SXin Li   }
619*67e74705SXin Li }
620*67e74705SXin Li 
CheckFunctionPointerDecl(QualType funcType,NamedDecl * ND)621*67e74705SXin Li void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622*67e74705SXin Li   const PointerType *PT = funcType->getAs<PointerType>();
623*67e74705SXin Li   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624*67e74705SXin Li     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625*67e74705SXin Li }
626*67e74705SXin Li 
IsHeaderFile(const std::string & Filename)627*67e74705SXin Li static bool IsHeaderFile(const std::string &Filename) {
628*67e74705SXin Li   std::string::size_type DotPos = Filename.rfind('.');
629*67e74705SXin Li 
630*67e74705SXin Li   if (DotPos == std::string::npos) {
631*67e74705SXin Li     // no file extension
632*67e74705SXin Li     return false;
633*67e74705SXin Li   }
634*67e74705SXin Li 
635*67e74705SXin Li   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636*67e74705SXin Li   // C header: .h
637*67e74705SXin Li   // C++ header: .hh or .H;
638*67e74705SXin Li   return Ext == "h" || Ext == "hh" || Ext == "H";
639*67e74705SXin Li }
640*67e74705SXin Li 
RewriteModernObjC(std::string inFile,raw_ostream * OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn,bool LineInfo)641*67e74705SXin Li RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
642*67e74705SXin Li                          DiagnosticsEngine &D, const LangOptions &LOpts,
643*67e74705SXin Li                          bool silenceMacroWarn,
644*67e74705SXin Li                          bool LineInfo)
645*67e74705SXin Li       : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
646*67e74705SXin Li         SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
647*67e74705SXin Li   IsHeader = IsHeaderFile(inFile);
648*67e74705SXin Li   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
649*67e74705SXin Li                "rewriting sub-expression within a macro (may not be correct)");
650*67e74705SXin Li   // FIXME. This should be an error. But if block is not called, it is OK. And it
651*67e74705SXin Li   // may break including some headers.
652*67e74705SXin Li   GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
653*67e74705SXin Li     "rewriting block literal declared in global scope is not implemented");
654*67e74705SXin Li 
655*67e74705SXin Li   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
656*67e74705SXin Li                DiagnosticsEngine::Warning,
657*67e74705SXin Li                "rewriter doesn't support user-specified control flow semantics "
658*67e74705SXin Li                "for @try/@finally (code may not execute properly)");
659*67e74705SXin Li }
660*67e74705SXin Li 
CreateModernObjCRewriter(const std::string & InFile,raw_ostream * OS,DiagnosticsEngine & Diags,const LangOptions & LOpts,bool SilenceRewriteMacroWarning,bool LineInfo)661*67e74705SXin Li std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
662*67e74705SXin Li     const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
663*67e74705SXin Li     const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
664*67e74705SXin Li   return llvm::make_unique<RewriteModernObjC>(
665*67e74705SXin Li       InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
666*67e74705SXin Li }
667*67e74705SXin Li 
InitializeCommon(ASTContext & context)668*67e74705SXin Li void RewriteModernObjC::InitializeCommon(ASTContext &context) {
669*67e74705SXin Li   Context = &context;
670*67e74705SXin Li   SM = &Context->getSourceManager();
671*67e74705SXin Li   TUDecl = Context->getTranslationUnitDecl();
672*67e74705SXin Li   MsgSendFunctionDecl = nullptr;
673*67e74705SXin Li   MsgSendSuperFunctionDecl = nullptr;
674*67e74705SXin Li   MsgSendStretFunctionDecl = nullptr;
675*67e74705SXin Li   MsgSendSuperStretFunctionDecl = nullptr;
676*67e74705SXin Li   MsgSendFpretFunctionDecl = nullptr;
677*67e74705SXin Li   GetClassFunctionDecl = nullptr;
678*67e74705SXin Li   GetMetaClassFunctionDecl = nullptr;
679*67e74705SXin Li   GetSuperClassFunctionDecl = nullptr;
680*67e74705SXin Li   SelGetUidFunctionDecl = nullptr;
681*67e74705SXin Li   CFStringFunctionDecl = nullptr;
682*67e74705SXin Li   ConstantStringClassReference = nullptr;
683*67e74705SXin Li   NSStringRecord = nullptr;
684*67e74705SXin Li   CurMethodDef = nullptr;
685*67e74705SXin Li   CurFunctionDef = nullptr;
686*67e74705SXin Li   GlobalVarDecl = nullptr;
687*67e74705SXin Li   GlobalConstructionExp = nullptr;
688*67e74705SXin Li   SuperStructDecl = nullptr;
689*67e74705SXin Li   ProtocolTypeDecl = nullptr;
690*67e74705SXin Li   ConstantStringDecl = nullptr;
691*67e74705SXin Li   BcLabelCount = 0;
692*67e74705SXin Li   SuperConstructorFunctionDecl = nullptr;
693*67e74705SXin Li   NumObjCStringLiterals = 0;
694*67e74705SXin Li   PropParentMap = nullptr;
695*67e74705SXin Li   CurrentBody = nullptr;
696*67e74705SXin Li   DisableReplaceStmt = false;
697*67e74705SXin Li   objc_impl_method = false;
698*67e74705SXin Li 
699*67e74705SXin Li   // Get the ID and start/end of the main file.
700*67e74705SXin Li   MainFileID = SM->getMainFileID();
701*67e74705SXin Li   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
702*67e74705SXin Li   MainFileStart = MainBuf->getBufferStart();
703*67e74705SXin Li   MainFileEnd = MainBuf->getBufferEnd();
704*67e74705SXin Li 
705*67e74705SXin Li   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
706*67e74705SXin Li }
707*67e74705SXin Li 
708*67e74705SXin Li //===----------------------------------------------------------------------===//
709*67e74705SXin Li // Top Level Driver Code
710*67e74705SXin Li //===----------------------------------------------------------------------===//
711*67e74705SXin Li 
HandleTopLevelSingleDecl(Decl * D)712*67e74705SXin Li void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
713*67e74705SXin Li   if (Diags.hasErrorOccurred())
714*67e74705SXin Li     return;
715*67e74705SXin Li 
716*67e74705SXin Li   // Two cases: either the decl could be in the main file, or it could be in a
717*67e74705SXin Li   // #included file.  If the former, rewrite it now.  If the later, check to see
718*67e74705SXin Li   // if we rewrote the #include/#import.
719*67e74705SXin Li   SourceLocation Loc = D->getLocation();
720*67e74705SXin Li   Loc = SM->getExpansionLoc(Loc);
721*67e74705SXin Li 
722*67e74705SXin Li   // If this is for a builtin, ignore it.
723*67e74705SXin Li   if (Loc.isInvalid()) return;
724*67e74705SXin Li 
725*67e74705SXin Li   // Look for built-in declarations that we need to refer during the rewrite.
726*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
727*67e74705SXin Li     RewriteFunctionDecl(FD);
728*67e74705SXin Li   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
729*67e74705SXin Li     // declared in <Foundation/NSString.h>
730*67e74705SXin Li     if (FVD->getName() == "_NSConstantStringClassReference") {
731*67e74705SXin Li       ConstantStringClassReference = FVD;
732*67e74705SXin Li       return;
733*67e74705SXin Li     }
734*67e74705SXin Li   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
735*67e74705SXin Li     RewriteCategoryDecl(CD);
736*67e74705SXin Li   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
737*67e74705SXin Li     if (PD->isThisDeclarationADefinition())
738*67e74705SXin Li       RewriteProtocolDecl(PD);
739*67e74705SXin Li   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
740*67e74705SXin Li     // Recurse into linkage specifications
741*67e74705SXin Li     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
742*67e74705SXin Li                                  DIEnd = LSD->decls_end();
743*67e74705SXin Li          DI != DIEnd; ) {
744*67e74705SXin Li       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
745*67e74705SXin Li         if (!IFace->isThisDeclarationADefinition()) {
746*67e74705SXin Li           SmallVector<Decl *, 8> DG;
747*67e74705SXin Li           SourceLocation StartLoc = IFace->getLocStart();
748*67e74705SXin Li           do {
749*67e74705SXin Li             if (isa<ObjCInterfaceDecl>(*DI) &&
750*67e74705SXin Li                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
751*67e74705SXin Li                 StartLoc == (*DI)->getLocStart())
752*67e74705SXin Li               DG.push_back(*DI);
753*67e74705SXin Li             else
754*67e74705SXin Li               break;
755*67e74705SXin Li 
756*67e74705SXin Li             ++DI;
757*67e74705SXin Li           } while (DI != DIEnd);
758*67e74705SXin Li           RewriteForwardClassDecl(DG);
759*67e74705SXin Li           continue;
760*67e74705SXin Li         }
761*67e74705SXin Li         else {
762*67e74705SXin Li           // Keep track of all interface declarations seen.
763*67e74705SXin Li           ObjCInterfacesSeen.push_back(IFace);
764*67e74705SXin Li           ++DI;
765*67e74705SXin Li           continue;
766*67e74705SXin Li         }
767*67e74705SXin Li       }
768*67e74705SXin Li 
769*67e74705SXin Li       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
770*67e74705SXin Li         if (!Proto->isThisDeclarationADefinition()) {
771*67e74705SXin Li           SmallVector<Decl *, 8> DG;
772*67e74705SXin Li           SourceLocation StartLoc = Proto->getLocStart();
773*67e74705SXin Li           do {
774*67e74705SXin Li             if (isa<ObjCProtocolDecl>(*DI) &&
775*67e74705SXin Li                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
776*67e74705SXin Li                 StartLoc == (*DI)->getLocStart())
777*67e74705SXin Li               DG.push_back(*DI);
778*67e74705SXin Li             else
779*67e74705SXin Li               break;
780*67e74705SXin Li 
781*67e74705SXin Li             ++DI;
782*67e74705SXin Li           } while (DI != DIEnd);
783*67e74705SXin Li           RewriteForwardProtocolDecl(DG);
784*67e74705SXin Li           continue;
785*67e74705SXin Li         }
786*67e74705SXin Li       }
787*67e74705SXin Li 
788*67e74705SXin Li       HandleTopLevelSingleDecl(*DI);
789*67e74705SXin Li       ++DI;
790*67e74705SXin Li     }
791*67e74705SXin Li   }
792*67e74705SXin Li   // If we have a decl in the main file, see if we should rewrite it.
793*67e74705SXin Li   if (SM->isWrittenInMainFile(Loc))
794*67e74705SXin Li     return HandleDeclInMainFile(D);
795*67e74705SXin Li }
796*67e74705SXin Li 
797*67e74705SXin Li //===----------------------------------------------------------------------===//
798*67e74705SXin Li // Syntactic (non-AST) Rewriting Code
799*67e74705SXin Li //===----------------------------------------------------------------------===//
800*67e74705SXin Li 
RewriteInclude()801*67e74705SXin Li void RewriteModernObjC::RewriteInclude() {
802*67e74705SXin Li   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
803*67e74705SXin Li   StringRef MainBuf = SM->getBufferData(MainFileID);
804*67e74705SXin Li   const char *MainBufStart = MainBuf.begin();
805*67e74705SXin Li   const char *MainBufEnd = MainBuf.end();
806*67e74705SXin Li   size_t ImportLen = strlen("import");
807*67e74705SXin Li 
808*67e74705SXin Li   // Loop over the whole file, looking for includes.
809*67e74705SXin Li   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
810*67e74705SXin Li     if (*BufPtr == '#') {
811*67e74705SXin Li       if (++BufPtr == MainBufEnd)
812*67e74705SXin Li         return;
813*67e74705SXin Li       while (*BufPtr == ' ' || *BufPtr == '\t')
814*67e74705SXin Li         if (++BufPtr == MainBufEnd)
815*67e74705SXin Li           return;
816*67e74705SXin Li       if (!strncmp(BufPtr, "import", ImportLen)) {
817*67e74705SXin Li         // replace import with include
818*67e74705SXin Li         SourceLocation ImportLoc =
819*67e74705SXin Li           LocStart.getLocWithOffset(BufPtr-MainBufStart);
820*67e74705SXin Li         ReplaceText(ImportLoc, ImportLen, "include");
821*67e74705SXin Li         BufPtr += ImportLen;
822*67e74705SXin Li       }
823*67e74705SXin Li     }
824*67e74705SXin Li   }
825*67e74705SXin Li }
826*67e74705SXin Li 
WriteInternalIvarName(const ObjCInterfaceDecl * IDecl,ObjCIvarDecl * IvarDecl,std::string & Result)827*67e74705SXin Li static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
828*67e74705SXin Li                                   ObjCIvarDecl *IvarDecl, std::string &Result) {
829*67e74705SXin Li   Result += "OBJC_IVAR_$_";
830*67e74705SXin Li   Result += IDecl->getName();
831*67e74705SXin Li   Result += "$";
832*67e74705SXin Li   Result += IvarDecl->getName();
833*67e74705SXin Li }
834*67e74705SXin Li 
835*67e74705SXin Li std::string
getIvarAccessString(ObjCIvarDecl * D)836*67e74705SXin Li RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
837*67e74705SXin Li   const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
838*67e74705SXin Li 
839*67e74705SXin Li   // Build name of symbol holding ivar offset.
840*67e74705SXin Li   std::string IvarOffsetName;
841*67e74705SXin Li   if (D->isBitField())
842*67e74705SXin Li     ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
843*67e74705SXin Li   else
844*67e74705SXin Li     WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
845*67e74705SXin Li 
846*67e74705SXin Li   std::string S = "(*(";
847*67e74705SXin Li   QualType IvarT = D->getType();
848*67e74705SXin Li   if (D->isBitField())
849*67e74705SXin Li     IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
850*67e74705SXin Li 
851*67e74705SXin Li   if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
852*67e74705SXin Li     RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
853*67e74705SXin Li     RD = RD->getDefinition();
854*67e74705SXin Li     if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
855*67e74705SXin Li       // decltype(((Foo_IMPL*)0)->bar) *
856*67e74705SXin Li       ObjCContainerDecl *CDecl =
857*67e74705SXin Li       dyn_cast<ObjCContainerDecl>(D->getDeclContext());
858*67e74705SXin Li       // ivar in class extensions requires special treatment.
859*67e74705SXin Li       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
860*67e74705SXin Li         CDecl = CatDecl->getClassInterface();
861*67e74705SXin Li       std::string RecName = CDecl->getName();
862*67e74705SXin Li       RecName += "_IMPL";
863*67e74705SXin Li       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
864*67e74705SXin Li                                           SourceLocation(), SourceLocation(),
865*67e74705SXin Li                                           &Context->Idents.get(RecName.c_str()));
866*67e74705SXin Li       QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
867*67e74705SXin Li       unsigned UnsignedIntSize =
868*67e74705SXin Li       static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
869*67e74705SXin Li       Expr *Zero = IntegerLiteral::Create(*Context,
870*67e74705SXin Li                                           llvm::APInt(UnsignedIntSize, 0),
871*67e74705SXin Li                                           Context->UnsignedIntTy, SourceLocation());
872*67e74705SXin Li       Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
873*67e74705SXin Li       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
874*67e74705SXin Li                                               Zero);
875*67e74705SXin Li       FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
876*67e74705SXin Li                                         SourceLocation(),
877*67e74705SXin Li                                         &Context->Idents.get(D->getNameAsString()),
878*67e74705SXin Li                                         IvarT, nullptr,
879*67e74705SXin Li                                         /*BitWidth=*/nullptr, /*Mutable=*/true,
880*67e74705SXin Li                                         ICIS_NoInit);
881*67e74705SXin Li       MemberExpr *ME = new (Context)
882*67e74705SXin Li           MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
883*67e74705SXin Li                      FD->getType(), VK_LValue, OK_Ordinary);
884*67e74705SXin Li       IvarT = Context->getDecltypeType(ME, ME->getType());
885*67e74705SXin Li     }
886*67e74705SXin Li   }
887*67e74705SXin Li   convertObjCTypeToCStyleType(IvarT);
888*67e74705SXin Li   QualType castT = Context->getPointerType(IvarT);
889*67e74705SXin Li   std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
890*67e74705SXin Li   S += TypeString;
891*67e74705SXin Li   S += ")";
892*67e74705SXin Li 
893*67e74705SXin Li   // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
894*67e74705SXin Li   S += "((char *)self + ";
895*67e74705SXin Li   S += IvarOffsetName;
896*67e74705SXin Li   S += "))";
897*67e74705SXin Li   if (D->isBitField()) {
898*67e74705SXin Li     S += ".";
899*67e74705SXin Li     S += D->getNameAsString();
900*67e74705SXin Li   }
901*67e74705SXin Li   ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
902*67e74705SXin Li   return S;
903*67e74705SXin Li }
904*67e74705SXin Li 
905*67e74705SXin Li /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
906*67e74705SXin Li /// been found in the class implementation. In this case, it must be synthesized.
mustSynthesizeSetterGetterMethod(ObjCImplementationDecl * IMP,ObjCPropertyDecl * PD,bool getter)907*67e74705SXin Li static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
908*67e74705SXin Li                                              ObjCPropertyDecl *PD,
909*67e74705SXin Li                                              bool getter) {
910*67e74705SXin Li   return getter ? !IMP->getInstanceMethod(PD->getGetterName())
911*67e74705SXin Li                 : !IMP->getInstanceMethod(PD->getSetterName());
912*67e74705SXin Li 
913*67e74705SXin Li }
914*67e74705SXin Li 
RewritePropertyImplDecl(ObjCPropertyImplDecl * PID,ObjCImplementationDecl * IMD,ObjCCategoryImplDecl * CID)915*67e74705SXin Li void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
916*67e74705SXin Li                                           ObjCImplementationDecl *IMD,
917*67e74705SXin Li                                           ObjCCategoryImplDecl *CID) {
918*67e74705SXin Li   static bool objcGetPropertyDefined = false;
919*67e74705SXin Li   static bool objcSetPropertyDefined = false;
920*67e74705SXin Li   SourceLocation startGetterSetterLoc;
921*67e74705SXin Li 
922*67e74705SXin Li   if (PID->getLocStart().isValid()) {
923*67e74705SXin Li     SourceLocation startLoc = PID->getLocStart();
924*67e74705SXin Li     InsertText(startLoc, "// ");
925*67e74705SXin Li     const char *startBuf = SM->getCharacterData(startLoc);
926*67e74705SXin Li     assert((*startBuf == '@') && "bogus @synthesize location");
927*67e74705SXin Li     const char *semiBuf = strchr(startBuf, ';');
928*67e74705SXin Li     assert((*semiBuf == ';') && "@synthesize: can't find ';'");
929*67e74705SXin Li     startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
930*67e74705SXin Li   }
931*67e74705SXin Li   else
932*67e74705SXin Li     startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
933*67e74705SXin Li 
934*67e74705SXin Li   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935*67e74705SXin Li     return; // FIXME: is this correct?
936*67e74705SXin Li 
937*67e74705SXin Li   // Generate the 'getter' function.
938*67e74705SXin Li   ObjCPropertyDecl *PD = PID->getPropertyDecl();
939*67e74705SXin Li   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
940*67e74705SXin Li   assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
941*67e74705SXin Li 
942*67e74705SXin Li   unsigned Attributes = PD->getPropertyAttributes();
943*67e74705SXin Li   if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
944*67e74705SXin Li     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945*67e74705SXin Li                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
946*67e74705SXin Li                                          ObjCPropertyDecl::OBJC_PR_copy));
947*67e74705SXin Li     std::string Getr;
948*67e74705SXin Li     if (GenGetProperty && !objcGetPropertyDefined) {
949*67e74705SXin Li       objcGetPropertyDefined = true;
950*67e74705SXin Li       // FIXME. Is this attribute correct in all cases?
951*67e74705SXin Li       Getr = "\nextern \"C\" __declspec(dllimport) "
952*67e74705SXin Li             "id objc_getProperty(id, SEL, long, bool);\n";
953*67e74705SXin Li     }
954*67e74705SXin Li     RewriteObjCMethodDecl(OID->getContainingInterface(),
955*67e74705SXin Li                           PD->getGetterMethodDecl(), Getr);
956*67e74705SXin Li     Getr += "{ ";
957*67e74705SXin Li     // Synthesize an explicit cast to gain access to the ivar.
958*67e74705SXin Li     // See objc-act.c:objc_synthesize_new_getter() for details.
959*67e74705SXin Li     if (GenGetProperty) {
960*67e74705SXin Li       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961*67e74705SXin Li       Getr += "typedef ";
962*67e74705SXin Li       const FunctionType *FPRetType = nullptr;
963*67e74705SXin Li       RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
964*67e74705SXin Li                             FPRetType);
965*67e74705SXin Li       Getr += " _TYPE";
966*67e74705SXin Li       if (FPRetType) {
967*67e74705SXin Li         Getr += ")"; // close the precedence "scope" for "*".
968*67e74705SXin Li 
969*67e74705SXin Li         // Now, emit the argument types (if any).
970*67e74705SXin Li         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971*67e74705SXin Li           Getr += "(";
972*67e74705SXin Li           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
973*67e74705SXin Li             if (i) Getr += ", ";
974*67e74705SXin Li             std::string ParamStr =
975*67e74705SXin Li                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
976*67e74705SXin Li             Getr += ParamStr;
977*67e74705SXin Li           }
978*67e74705SXin Li           if (FT->isVariadic()) {
979*67e74705SXin Li             if (FT->getNumParams())
980*67e74705SXin Li               Getr += ", ";
981*67e74705SXin Li             Getr += "...";
982*67e74705SXin Li           }
983*67e74705SXin Li           Getr += ")";
984*67e74705SXin Li         } else
985*67e74705SXin Li           Getr += "()";
986*67e74705SXin Li       }
987*67e74705SXin Li       Getr += ";\n";
988*67e74705SXin Li       Getr += "return (_TYPE)";
989*67e74705SXin Li       Getr += "objc_getProperty(self, _cmd, ";
990*67e74705SXin Li       RewriteIvarOffsetComputation(OID, Getr);
991*67e74705SXin Li       Getr += ", 1)";
992*67e74705SXin Li     }
993*67e74705SXin Li     else
994*67e74705SXin Li       Getr += "return " + getIvarAccessString(OID);
995*67e74705SXin Li     Getr += "; }";
996*67e74705SXin Li     InsertText(startGetterSetterLoc, Getr);
997*67e74705SXin Li   }
998*67e74705SXin Li 
999*67e74705SXin Li   if (PD->isReadOnly() ||
1000*67e74705SXin Li       !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1001*67e74705SXin Li     return;
1002*67e74705SXin Li 
1003*67e74705SXin Li   // Generate the 'setter' function.
1004*67e74705SXin Li   std::string Setr;
1005*67e74705SXin Li   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1006*67e74705SXin Li                                       ObjCPropertyDecl::OBJC_PR_copy);
1007*67e74705SXin Li   if (GenSetProperty && !objcSetPropertyDefined) {
1008*67e74705SXin Li     objcSetPropertyDefined = true;
1009*67e74705SXin Li     // FIXME. Is this attribute correct in all cases?
1010*67e74705SXin Li     Setr = "\nextern \"C\" __declspec(dllimport) "
1011*67e74705SXin Li     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012*67e74705SXin Li   }
1013*67e74705SXin Li 
1014*67e74705SXin Li   RewriteObjCMethodDecl(OID->getContainingInterface(),
1015*67e74705SXin Li                         PD->getSetterMethodDecl(), Setr);
1016*67e74705SXin Li   Setr += "{ ";
1017*67e74705SXin Li   // Synthesize an explicit cast to initialize the ivar.
1018*67e74705SXin Li   // See objc-act.c:objc_synthesize_new_setter() for details.
1019*67e74705SXin Li   if (GenSetProperty) {
1020*67e74705SXin Li     Setr += "objc_setProperty (self, _cmd, ";
1021*67e74705SXin Li     RewriteIvarOffsetComputation(OID, Setr);
1022*67e74705SXin Li     Setr += ", (id)";
1023*67e74705SXin Li     Setr += PD->getName();
1024*67e74705SXin Li     Setr += ", ";
1025*67e74705SXin Li     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1026*67e74705SXin Li       Setr += "0, ";
1027*67e74705SXin Li     else
1028*67e74705SXin Li       Setr += "1, ";
1029*67e74705SXin Li     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1030*67e74705SXin Li       Setr += "1)";
1031*67e74705SXin Li     else
1032*67e74705SXin Li       Setr += "0)";
1033*67e74705SXin Li   }
1034*67e74705SXin Li   else {
1035*67e74705SXin Li     Setr += getIvarAccessString(OID) + " = ";
1036*67e74705SXin Li     Setr += PD->getName();
1037*67e74705SXin Li   }
1038*67e74705SXin Li   Setr += "; }\n";
1039*67e74705SXin Li   InsertText(startGetterSetterLoc, Setr);
1040*67e74705SXin Li }
1041*67e74705SXin Li 
RewriteOneForwardClassDecl(ObjCInterfaceDecl * ForwardDecl,std::string & typedefString)1042*67e74705SXin Li static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043*67e74705SXin Li                                        std::string &typedefString) {
1044*67e74705SXin Li   typedefString += "\n#ifndef _REWRITER_typedef_";
1045*67e74705SXin Li   typedefString += ForwardDecl->getNameAsString();
1046*67e74705SXin Li   typedefString += "\n";
1047*67e74705SXin Li   typedefString += "#define _REWRITER_typedef_";
1048*67e74705SXin Li   typedefString += ForwardDecl->getNameAsString();
1049*67e74705SXin Li   typedefString += "\n";
1050*67e74705SXin Li   typedefString += "typedef struct objc_object ";
1051*67e74705SXin Li   typedefString += ForwardDecl->getNameAsString();
1052*67e74705SXin Li   // typedef struct { } _objc_exc_Classname;
1053*67e74705SXin Li   typedefString += ";\ntypedef struct {} _objc_exc_";
1054*67e74705SXin Li   typedefString += ForwardDecl->getNameAsString();
1055*67e74705SXin Li   typedefString += ";\n#endif\n";
1056*67e74705SXin Li }
1057*67e74705SXin Li 
RewriteForwardClassEpilogue(ObjCInterfaceDecl * ClassDecl,const std::string & typedefString)1058*67e74705SXin Li void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059*67e74705SXin Li                                               const std::string &typedefString) {
1060*67e74705SXin Li   SourceLocation startLoc = ClassDecl->getLocStart();
1061*67e74705SXin Li   const char *startBuf = SM->getCharacterData(startLoc);
1062*67e74705SXin Li   const char *semiPtr = strchr(startBuf, ';');
1063*67e74705SXin Li   // Replace the @class with typedefs corresponding to the classes.
1064*67e74705SXin Li   ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1065*67e74705SXin Li }
1066*67e74705SXin Li 
RewriteForwardClassDecl(DeclGroupRef D)1067*67e74705SXin Li void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068*67e74705SXin Li   std::string typedefString;
1069*67e74705SXin Li   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1070*67e74705SXin Li     if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1071*67e74705SXin Li       if (I == D.begin()) {
1072*67e74705SXin Li         // Translate to typedef's that forward reference structs with the same name
1073*67e74705SXin Li         // as the class. As a convenience, we include the original declaration
1074*67e74705SXin Li         // as a comment.
1075*67e74705SXin Li         typedefString += "// @class ";
1076*67e74705SXin Li         typedefString += ForwardDecl->getNameAsString();
1077*67e74705SXin Li         typedefString += ";";
1078*67e74705SXin Li       }
1079*67e74705SXin Li       RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1080*67e74705SXin Li     }
1081*67e74705SXin Li     else
1082*67e74705SXin Li       HandleTopLevelSingleDecl(*I);
1083*67e74705SXin Li   }
1084*67e74705SXin Li   DeclGroupRef::iterator I = D.begin();
1085*67e74705SXin Li   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086*67e74705SXin Li }
1087*67e74705SXin Li 
RewriteForwardClassDecl(const SmallVectorImpl<Decl * > & D)1088*67e74705SXin Li void RewriteModernObjC::RewriteForwardClassDecl(
1089*67e74705SXin Li                                 const SmallVectorImpl<Decl *> &D) {
1090*67e74705SXin Li   std::string typedefString;
1091*67e74705SXin Li   for (unsigned i = 0; i < D.size(); i++) {
1092*67e74705SXin Li     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093*67e74705SXin Li     if (i == 0) {
1094*67e74705SXin Li       typedefString += "// @class ";
1095*67e74705SXin Li       typedefString += ForwardDecl->getNameAsString();
1096*67e74705SXin Li       typedefString += ";";
1097*67e74705SXin Li     }
1098*67e74705SXin Li     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099*67e74705SXin Li   }
1100*67e74705SXin Li   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101*67e74705SXin Li }
1102*67e74705SXin Li 
RewriteMethodDeclaration(ObjCMethodDecl * Method)1103*67e74705SXin Li void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104*67e74705SXin Li   // When method is a synthesized one, such as a getter/setter there is
1105*67e74705SXin Li   // nothing to rewrite.
1106*67e74705SXin Li   if (Method->isImplicit())
1107*67e74705SXin Li     return;
1108*67e74705SXin Li   SourceLocation LocStart = Method->getLocStart();
1109*67e74705SXin Li   SourceLocation LocEnd = Method->getLocEnd();
1110*67e74705SXin Li 
1111*67e74705SXin Li   if (SM->getExpansionLineNumber(LocEnd) >
1112*67e74705SXin Li       SM->getExpansionLineNumber(LocStart)) {
1113*67e74705SXin Li     InsertText(LocStart, "#if 0\n");
1114*67e74705SXin Li     ReplaceText(LocEnd, 1, ";\n#endif\n");
1115*67e74705SXin Li   } else {
1116*67e74705SXin Li     InsertText(LocStart, "// ");
1117*67e74705SXin Li   }
1118*67e74705SXin Li }
1119*67e74705SXin Li 
RewriteProperty(ObjCPropertyDecl * prop)1120*67e74705SXin Li void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121*67e74705SXin Li   SourceLocation Loc = prop->getAtLoc();
1122*67e74705SXin Li 
1123*67e74705SXin Li   ReplaceText(Loc, 0, "// ");
1124*67e74705SXin Li   // FIXME: handle properties that are declared across multiple lines.
1125*67e74705SXin Li }
1126*67e74705SXin Li 
RewriteCategoryDecl(ObjCCategoryDecl * CatDecl)1127*67e74705SXin Li void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128*67e74705SXin Li   SourceLocation LocStart = CatDecl->getLocStart();
1129*67e74705SXin Li 
1130*67e74705SXin Li   // FIXME: handle category headers that are declared across multiple lines.
1131*67e74705SXin Li   if (CatDecl->getIvarRBraceLoc().isValid()) {
1132*67e74705SXin Li     ReplaceText(LocStart, 1, "/** ");
1133*67e74705SXin Li     ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134*67e74705SXin Li   }
1135*67e74705SXin Li   else {
1136*67e74705SXin Li     ReplaceText(LocStart, 0, "// ");
1137*67e74705SXin Li   }
1138*67e74705SXin Li 
1139*67e74705SXin Li   for (auto *I : CatDecl->instance_properties())
1140*67e74705SXin Li     RewriteProperty(I);
1141*67e74705SXin Li 
1142*67e74705SXin Li   for (auto *I : CatDecl->instance_methods())
1143*67e74705SXin Li     RewriteMethodDeclaration(I);
1144*67e74705SXin Li   for (auto *I : CatDecl->class_methods())
1145*67e74705SXin Li     RewriteMethodDeclaration(I);
1146*67e74705SXin Li 
1147*67e74705SXin Li   // Lastly, comment out the @end.
1148*67e74705SXin Li   ReplaceText(CatDecl->getAtEndRange().getBegin(),
1149*67e74705SXin Li               strlen("@end"), "/* @end */\n");
1150*67e74705SXin Li }
1151*67e74705SXin Li 
RewriteProtocolDecl(ObjCProtocolDecl * PDecl)1152*67e74705SXin Li void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153*67e74705SXin Li   SourceLocation LocStart = PDecl->getLocStart();
1154*67e74705SXin Li   assert(PDecl->isThisDeclarationADefinition());
1155*67e74705SXin Li 
1156*67e74705SXin Li   // FIXME: handle protocol headers that are declared across multiple lines.
1157*67e74705SXin Li   ReplaceText(LocStart, 0, "// ");
1158*67e74705SXin Li 
1159*67e74705SXin Li   for (auto *I : PDecl->instance_methods())
1160*67e74705SXin Li     RewriteMethodDeclaration(I);
1161*67e74705SXin Li   for (auto *I : PDecl->class_methods())
1162*67e74705SXin Li     RewriteMethodDeclaration(I);
1163*67e74705SXin Li   for (auto *I : PDecl->instance_properties())
1164*67e74705SXin Li     RewriteProperty(I);
1165*67e74705SXin Li 
1166*67e74705SXin Li   // Lastly, comment out the @end.
1167*67e74705SXin Li   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1168*67e74705SXin Li   ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1169*67e74705SXin Li 
1170*67e74705SXin Li   // Must comment out @optional/@required
1171*67e74705SXin Li   const char *startBuf = SM->getCharacterData(LocStart);
1172*67e74705SXin Li   const char *endBuf = SM->getCharacterData(LocEnd);
1173*67e74705SXin Li   for (const char *p = startBuf; p < endBuf; p++) {
1174*67e74705SXin Li     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1175*67e74705SXin Li       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1176*67e74705SXin Li       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1177*67e74705SXin Li 
1178*67e74705SXin Li     }
1179*67e74705SXin Li     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1180*67e74705SXin Li       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1181*67e74705SXin Li       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1182*67e74705SXin Li 
1183*67e74705SXin Li     }
1184*67e74705SXin Li   }
1185*67e74705SXin Li }
1186*67e74705SXin Li 
RewriteForwardProtocolDecl(DeclGroupRef D)1187*67e74705SXin Li void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1188*67e74705SXin Li   SourceLocation LocStart = (*D.begin())->getLocStart();
1189*67e74705SXin Li   if (LocStart.isInvalid())
1190*67e74705SXin Li     llvm_unreachable("Invalid SourceLocation");
1191*67e74705SXin Li   // FIXME: handle forward protocol that are declared across multiple lines.
1192*67e74705SXin Li   ReplaceText(LocStart, 0, "// ");
1193*67e74705SXin Li }
1194*67e74705SXin Li 
1195*67e74705SXin Li void
RewriteForwardProtocolDecl(const SmallVectorImpl<Decl * > & DG)1196*67e74705SXin Li RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1197*67e74705SXin Li   SourceLocation LocStart = DG[0]->getLocStart();
1198*67e74705SXin Li   if (LocStart.isInvalid())
1199*67e74705SXin Li     llvm_unreachable("Invalid SourceLocation");
1200*67e74705SXin Li   // FIXME: handle forward protocol that are declared across multiple lines.
1201*67e74705SXin Li   ReplaceText(LocStart, 0, "// ");
1202*67e74705SXin Li }
1203*67e74705SXin Li 
RewriteTypeIntoString(QualType T,std::string & ResultStr,const FunctionType * & FPRetType)1204*67e74705SXin Li void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1205*67e74705SXin Li                                         const FunctionType *&FPRetType) {
1206*67e74705SXin Li   if (T->isObjCQualifiedIdType())
1207*67e74705SXin Li     ResultStr += "id";
1208*67e74705SXin Li   else if (T->isFunctionPointerType() ||
1209*67e74705SXin Li            T->isBlockPointerType()) {
1210*67e74705SXin Li     // needs special handling, since pointer-to-functions have special
1211*67e74705SXin Li     // syntax (where a decaration models use).
1212*67e74705SXin Li     QualType retType = T;
1213*67e74705SXin Li     QualType PointeeTy;
1214*67e74705SXin Li     if (const PointerType* PT = retType->getAs<PointerType>())
1215*67e74705SXin Li       PointeeTy = PT->getPointeeType();
1216*67e74705SXin Li     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1217*67e74705SXin Li       PointeeTy = BPT->getPointeeType();
1218*67e74705SXin Li     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1219*67e74705SXin Li       ResultStr +=
1220*67e74705SXin Li           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1221*67e74705SXin Li       ResultStr += "(*";
1222*67e74705SXin Li     }
1223*67e74705SXin Li   } else
1224*67e74705SXin Li     ResultStr += T.getAsString(Context->getPrintingPolicy());
1225*67e74705SXin Li }
1226*67e74705SXin Li 
RewriteObjCMethodDecl(const ObjCInterfaceDecl * IDecl,ObjCMethodDecl * OMD,std::string & ResultStr)1227*67e74705SXin Li void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1228*67e74705SXin Li                                         ObjCMethodDecl *OMD,
1229*67e74705SXin Li                                         std::string &ResultStr) {
1230*67e74705SXin Li   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1231*67e74705SXin Li   const FunctionType *FPRetType = nullptr;
1232*67e74705SXin Li   ResultStr += "\nstatic ";
1233*67e74705SXin Li   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1234*67e74705SXin Li   ResultStr += " ";
1235*67e74705SXin Li 
1236*67e74705SXin Li   // Unique method name
1237*67e74705SXin Li   std::string NameStr;
1238*67e74705SXin Li 
1239*67e74705SXin Li   if (OMD->isInstanceMethod())
1240*67e74705SXin Li     NameStr += "_I_";
1241*67e74705SXin Li   else
1242*67e74705SXin Li     NameStr += "_C_";
1243*67e74705SXin Li 
1244*67e74705SXin Li   NameStr += IDecl->getNameAsString();
1245*67e74705SXin Li   NameStr += "_";
1246*67e74705SXin Li 
1247*67e74705SXin Li   if (ObjCCategoryImplDecl *CID =
1248*67e74705SXin Li       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1249*67e74705SXin Li     NameStr += CID->getNameAsString();
1250*67e74705SXin Li     NameStr += "_";
1251*67e74705SXin Li   }
1252*67e74705SXin Li   // Append selector names, replacing ':' with '_'
1253*67e74705SXin Li   {
1254*67e74705SXin Li     std::string selString = OMD->getSelector().getAsString();
1255*67e74705SXin Li     int len = selString.size();
1256*67e74705SXin Li     for (int i = 0; i < len; i++)
1257*67e74705SXin Li       if (selString[i] == ':')
1258*67e74705SXin Li         selString[i] = '_';
1259*67e74705SXin Li     NameStr += selString;
1260*67e74705SXin Li   }
1261*67e74705SXin Li   // Remember this name for metadata emission
1262*67e74705SXin Li   MethodInternalNames[OMD] = NameStr;
1263*67e74705SXin Li   ResultStr += NameStr;
1264*67e74705SXin Li 
1265*67e74705SXin Li   // Rewrite arguments
1266*67e74705SXin Li   ResultStr += "(";
1267*67e74705SXin Li 
1268*67e74705SXin Li   // invisible arguments
1269*67e74705SXin Li   if (OMD->isInstanceMethod()) {
1270*67e74705SXin Li     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1271*67e74705SXin Li     selfTy = Context->getPointerType(selfTy);
1272*67e74705SXin Li     if (!LangOpts.MicrosoftExt) {
1273*67e74705SXin Li       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1274*67e74705SXin Li         ResultStr += "struct ";
1275*67e74705SXin Li     }
1276*67e74705SXin Li     // When rewriting for Microsoft, explicitly omit the structure name.
1277*67e74705SXin Li     ResultStr += IDecl->getNameAsString();
1278*67e74705SXin Li     ResultStr += " *";
1279*67e74705SXin Li   }
1280*67e74705SXin Li   else
1281*67e74705SXin Li     ResultStr += Context->getObjCClassType().getAsString(
1282*67e74705SXin Li       Context->getPrintingPolicy());
1283*67e74705SXin Li 
1284*67e74705SXin Li   ResultStr += " self, ";
1285*67e74705SXin Li   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1286*67e74705SXin Li   ResultStr += " _cmd";
1287*67e74705SXin Li 
1288*67e74705SXin Li   // Method arguments.
1289*67e74705SXin Li   for (const auto *PDecl : OMD->parameters()) {
1290*67e74705SXin Li     ResultStr += ", ";
1291*67e74705SXin Li     if (PDecl->getType()->isObjCQualifiedIdType()) {
1292*67e74705SXin Li       ResultStr += "id ";
1293*67e74705SXin Li       ResultStr += PDecl->getNameAsString();
1294*67e74705SXin Li     } else {
1295*67e74705SXin Li       std::string Name = PDecl->getNameAsString();
1296*67e74705SXin Li       QualType QT = PDecl->getType();
1297*67e74705SXin Li       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1298*67e74705SXin Li       (void)convertBlockPointerToFunctionPointer(QT);
1299*67e74705SXin Li       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1300*67e74705SXin Li       ResultStr += Name;
1301*67e74705SXin Li     }
1302*67e74705SXin Li   }
1303*67e74705SXin Li   if (OMD->isVariadic())
1304*67e74705SXin Li     ResultStr += ", ...";
1305*67e74705SXin Li   ResultStr += ") ";
1306*67e74705SXin Li 
1307*67e74705SXin Li   if (FPRetType) {
1308*67e74705SXin Li     ResultStr += ")"; // close the precedence "scope" for "*".
1309*67e74705SXin Li 
1310*67e74705SXin Li     // Now, emit the argument types (if any).
1311*67e74705SXin Li     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1312*67e74705SXin Li       ResultStr += "(";
1313*67e74705SXin Li       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1314*67e74705SXin Li         if (i) ResultStr += ", ";
1315*67e74705SXin Li         std::string ParamStr =
1316*67e74705SXin Li             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1317*67e74705SXin Li         ResultStr += ParamStr;
1318*67e74705SXin Li       }
1319*67e74705SXin Li       if (FT->isVariadic()) {
1320*67e74705SXin Li         if (FT->getNumParams())
1321*67e74705SXin Li           ResultStr += ", ";
1322*67e74705SXin Li         ResultStr += "...";
1323*67e74705SXin Li       }
1324*67e74705SXin Li       ResultStr += ")";
1325*67e74705SXin Li     } else {
1326*67e74705SXin Li       ResultStr += "()";
1327*67e74705SXin Li     }
1328*67e74705SXin Li   }
1329*67e74705SXin Li }
1330*67e74705SXin Li 
RewriteImplementationDecl(Decl * OID)1331*67e74705SXin Li void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1332*67e74705SXin Li   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1333*67e74705SXin Li   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1334*67e74705SXin Li 
1335*67e74705SXin Li   if (IMD) {
1336*67e74705SXin Li     if (IMD->getIvarRBraceLoc().isValid()) {
1337*67e74705SXin Li       ReplaceText(IMD->getLocStart(), 1, "/** ");
1338*67e74705SXin Li       ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1339*67e74705SXin Li     }
1340*67e74705SXin Li     else {
1341*67e74705SXin Li       InsertText(IMD->getLocStart(), "// ");
1342*67e74705SXin Li     }
1343*67e74705SXin Li   }
1344*67e74705SXin Li   else
1345*67e74705SXin Li     InsertText(CID->getLocStart(), "// ");
1346*67e74705SXin Li 
1347*67e74705SXin Li   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1348*67e74705SXin Li     std::string ResultStr;
1349*67e74705SXin Li     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1350*67e74705SXin Li     SourceLocation LocStart = OMD->getLocStart();
1351*67e74705SXin Li     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1352*67e74705SXin Li 
1353*67e74705SXin Li     const char *startBuf = SM->getCharacterData(LocStart);
1354*67e74705SXin Li     const char *endBuf = SM->getCharacterData(LocEnd);
1355*67e74705SXin Li     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1356*67e74705SXin Li   }
1357*67e74705SXin Li 
1358*67e74705SXin Li   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1359*67e74705SXin Li     std::string ResultStr;
1360*67e74705SXin Li     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1361*67e74705SXin Li     SourceLocation LocStart = OMD->getLocStart();
1362*67e74705SXin Li     SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1363*67e74705SXin Li 
1364*67e74705SXin Li     const char *startBuf = SM->getCharacterData(LocStart);
1365*67e74705SXin Li     const char *endBuf = SM->getCharacterData(LocEnd);
1366*67e74705SXin Li     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1367*67e74705SXin Li   }
1368*67e74705SXin Li   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1369*67e74705SXin Li     RewritePropertyImplDecl(I, IMD, CID);
1370*67e74705SXin Li 
1371*67e74705SXin Li   InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1372*67e74705SXin Li }
1373*67e74705SXin Li 
RewriteInterfaceDecl(ObjCInterfaceDecl * ClassDecl)1374*67e74705SXin Li void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1375*67e74705SXin Li   // Do not synthesize more than once.
1376*67e74705SXin Li   if (ObjCSynthesizedStructs.count(ClassDecl))
1377*67e74705SXin Li     return;
1378*67e74705SXin Li   // Make sure super class's are written before current class is written.
1379*67e74705SXin Li   ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1380*67e74705SXin Li   while (SuperClass) {
1381*67e74705SXin Li     RewriteInterfaceDecl(SuperClass);
1382*67e74705SXin Li     SuperClass = SuperClass->getSuperClass();
1383*67e74705SXin Li   }
1384*67e74705SXin Li   std::string ResultStr;
1385*67e74705SXin Li   if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1386*67e74705SXin Li     // we haven't seen a forward decl - generate a typedef.
1387*67e74705SXin Li     RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1388*67e74705SXin Li     RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1389*67e74705SXin Li 
1390*67e74705SXin Li     RewriteObjCInternalStruct(ClassDecl, ResultStr);
1391*67e74705SXin Li     // Mark this typedef as having been written into its c++ equivalent.
1392*67e74705SXin Li     ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1393*67e74705SXin Li 
1394*67e74705SXin Li     for (auto *I : ClassDecl->instance_properties())
1395*67e74705SXin Li       RewriteProperty(I);
1396*67e74705SXin Li     for (auto *I : ClassDecl->instance_methods())
1397*67e74705SXin Li       RewriteMethodDeclaration(I);
1398*67e74705SXin Li     for (auto *I : ClassDecl->class_methods())
1399*67e74705SXin Li       RewriteMethodDeclaration(I);
1400*67e74705SXin Li 
1401*67e74705SXin Li     // Lastly, comment out the @end.
1402*67e74705SXin Li     ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1403*67e74705SXin Li                 "/* @end */\n");
1404*67e74705SXin Li   }
1405*67e74705SXin Li }
1406*67e74705SXin Li 
RewritePropertyOrImplicitSetter(PseudoObjectExpr * PseudoOp)1407*67e74705SXin Li Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1408*67e74705SXin Li   SourceRange OldRange = PseudoOp->getSourceRange();
1409*67e74705SXin Li 
1410*67e74705SXin Li   // We just magically know some things about the structure of this
1411*67e74705SXin Li   // expression.
1412*67e74705SXin Li   ObjCMessageExpr *OldMsg =
1413*67e74705SXin Li     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1414*67e74705SXin Li                             PseudoOp->getNumSemanticExprs() - 1));
1415*67e74705SXin Li 
1416*67e74705SXin Li   // Because the rewriter doesn't allow us to rewrite rewritten code,
1417*67e74705SXin Li   // we need to suppress rewriting the sub-statements.
1418*67e74705SXin Li   Expr *Base;
1419*67e74705SXin Li   SmallVector<Expr*, 2> Args;
1420*67e74705SXin Li   {
1421*67e74705SXin Li     DisableReplaceStmtScope S(*this);
1422*67e74705SXin Li 
1423*67e74705SXin Li     // Rebuild the base expression if we have one.
1424*67e74705SXin Li     Base = nullptr;
1425*67e74705SXin Li     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1426*67e74705SXin Li       Base = OldMsg->getInstanceReceiver();
1427*67e74705SXin Li       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1428*67e74705SXin Li       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1429*67e74705SXin Li     }
1430*67e74705SXin Li 
1431*67e74705SXin Li     unsigned numArgs = OldMsg->getNumArgs();
1432*67e74705SXin Li     for (unsigned i = 0; i < numArgs; i++) {
1433*67e74705SXin Li       Expr *Arg = OldMsg->getArg(i);
1434*67e74705SXin Li       if (isa<OpaqueValueExpr>(Arg))
1435*67e74705SXin Li         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1436*67e74705SXin Li       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1437*67e74705SXin Li       Args.push_back(Arg);
1438*67e74705SXin Li     }
1439*67e74705SXin Li   }
1440*67e74705SXin Li 
1441*67e74705SXin Li   // TODO: avoid this copy.
1442*67e74705SXin Li   SmallVector<SourceLocation, 1> SelLocs;
1443*67e74705SXin Li   OldMsg->getSelectorLocs(SelLocs);
1444*67e74705SXin Li 
1445*67e74705SXin Li   ObjCMessageExpr *NewMsg = nullptr;
1446*67e74705SXin Li   switch (OldMsg->getReceiverKind()) {
1447*67e74705SXin Li   case ObjCMessageExpr::Class:
1448*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1449*67e74705SXin Li                                      OldMsg->getValueKind(),
1450*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1451*67e74705SXin Li                                      OldMsg->getClassReceiverTypeInfo(),
1452*67e74705SXin Li                                      OldMsg->getSelector(),
1453*67e74705SXin Li                                      SelLocs,
1454*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1455*67e74705SXin Li                                      Args,
1456*67e74705SXin Li                                      OldMsg->getRightLoc(),
1457*67e74705SXin Li                                      OldMsg->isImplicit());
1458*67e74705SXin Li     break;
1459*67e74705SXin Li 
1460*67e74705SXin Li   case ObjCMessageExpr::Instance:
1461*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1462*67e74705SXin Li                                      OldMsg->getValueKind(),
1463*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1464*67e74705SXin Li                                      Base,
1465*67e74705SXin Li                                      OldMsg->getSelector(),
1466*67e74705SXin Li                                      SelLocs,
1467*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1468*67e74705SXin Li                                      Args,
1469*67e74705SXin Li                                      OldMsg->getRightLoc(),
1470*67e74705SXin Li                                      OldMsg->isImplicit());
1471*67e74705SXin Li     break;
1472*67e74705SXin Li 
1473*67e74705SXin Li   case ObjCMessageExpr::SuperClass:
1474*67e74705SXin Li   case ObjCMessageExpr::SuperInstance:
1475*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1476*67e74705SXin Li                                      OldMsg->getValueKind(),
1477*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1478*67e74705SXin Li                                      OldMsg->getSuperLoc(),
1479*67e74705SXin Li                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1480*67e74705SXin Li                                      OldMsg->getSuperType(),
1481*67e74705SXin Li                                      OldMsg->getSelector(),
1482*67e74705SXin Li                                      SelLocs,
1483*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1484*67e74705SXin Li                                      Args,
1485*67e74705SXin Li                                      OldMsg->getRightLoc(),
1486*67e74705SXin Li                                      OldMsg->isImplicit());
1487*67e74705SXin Li     break;
1488*67e74705SXin Li   }
1489*67e74705SXin Li 
1490*67e74705SXin Li   Stmt *Replacement = SynthMessageExpr(NewMsg);
1491*67e74705SXin Li   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1492*67e74705SXin Li   return Replacement;
1493*67e74705SXin Li }
1494*67e74705SXin Li 
RewritePropertyOrImplicitGetter(PseudoObjectExpr * PseudoOp)1495*67e74705SXin Li Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1496*67e74705SXin Li   SourceRange OldRange = PseudoOp->getSourceRange();
1497*67e74705SXin Li 
1498*67e74705SXin Li   // We just magically know some things about the structure of this
1499*67e74705SXin Li   // expression.
1500*67e74705SXin Li   ObjCMessageExpr *OldMsg =
1501*67e74705SXin Li     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1502*67e74705SXin Li 
1503*67e74705SXin Li   // Because the rewriter doesn't allow us to rewrite rewritten code,
1504*67e74705SXin Li   // we need to suppress rewriting the sub-statements.
1505*67e74705SXin Li   Expr *Base = nullptr;
1506*67e74705SXin Li   SmallVector<Expr*, 1> Args;
1507*67e74705SXin Li   {
1508*67e74705SXin Li     DisableReplaceStmtScope S(*this);
1509*67e74705SXin Li     // Rebuild the base expression if we have one.
1510*67e74705SXin Li     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1511*67e74705SXin Li       Base = OldMsg->getInstanceReceiver();
1512*67e74705SXin Li       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1513*67e74705SXin Li       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1514*67e74705SXin Li     }
1515*67e74705SXin Li     unsigned numArgs = OldMsg->getNumArgs();
1516*67e74705SXin Li     for (unsigned i = 0; i < numArgs; i++) {
1517*67e74705SXin Li       Expr *Arg = OldMsg->getArg(i);
1518*67e74705SXin Li       if (isa<OpaqueValueExpr>(Arg))
1519*67e74705SXin Li         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1520*67e74705SXin Li       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1521*67e74705SXin Li       Args.push_back(Arg);
1522*67e74705SXin Li     }
1523*67e74705SXin Li   }
1524*67e74705SXin Li 
1525*67e74705SXin Li   // Intentionally empty.
1526*67e74705SXin Li   SmallVector<SourceLocation, 1> SelLocs;
1527*67e74705SXin Li 
1528*67e74705SXin Li   ObjCMessageExpr *NewMsg = nullptr;
1529*67e74705SXin Li   switch (OldMsg->getReceiverKind()) {
1530*67e74705SXin Li   case ObjCMessageExpr::Class:
1531*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1532*67e74705SXin Li                                      OldMsg->getValueKind(),
1533*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1534*67e74705SXin Li                                      OldMsg->getClassReceiverTypeInfo(),
1535*67e74705SXin Li                                      OldMsg->getSelector(),
1536*67e74705SXin Li                                      SelLocs,
1537*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1538*67e74705SXin Li                                      Args,
1539*67e74705SXin Li                                      OldMsg->getRightLoc(),
1540*67e74705SXin Li                                      OldMsg->isImplicit());
1541*67e74705SXin Li     break;
1542*67e74705SXin Li 
1543*67e74705SXin Li   case ObjCMessageExpr::Instance:
1544*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1545*67e74705SXin Li                                      OldMsg->getValueKind(),
1546*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1547*67e74705SXin Li                                      Base,
1548*67e74705SXin Li                                      OldMsg->getSelector(),
1549*67e74705SXin Li                                      SelLocs,
1550*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1551*67e74705SXin Li                                      Args,
1552*67e74705SXin Li                                      OldMsg->getRightLoc(),
1553*67e74705SXin Li                                      OldMsg->isImplicit());
1554*67e74705SXin Li     break;
1555*67e74705SXin Li 
1556*67e74705SXin Li   case ObjCMessageExpr::SuperClass:
1557*67e74705SXin Li   case ObjCMessageExpr::SuperInstance:
1558*67e74705SXin Li     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1559*67e74705SXin Li                                      OldMsg->getValueKind(),
1560*67e74705SXin Li                                      OldMsg->getLeftLoc(),
1561*67e74705SXin Li                                      OldMsg->getSuperLoc(),
1562*67e74705SXin Li                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1563*67e74705SXin Li                                      OldMsg->getSuperType(),
1564*67e74705SXin Li                                      OldMsg->getSelector(),
1565*67e74705SXin Li                                      SelLocs,
1566*67e74705SXin Li                                      OldMsg->getMethodDecl(),
1567*67e74705SXin Li                                      Args,
1568*67e74705SXin Li                                      OldMsg->getRightLoc(),
1569*67e74705SXin Li                                      OldMsg->isImplicit());
1570*67e74705SXin Li     break;
1571*67e74705SXin Li   }
1572*67e74705SXin Li 
1573*67e74705SXin Li   Stmt *Replacement = SynthMessageExpr(NewMsg);
1574*67e74705SXin Li   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1575*67e74705SXin Li   return Replacement;
1576*67e74705SXin Li }
1577*67e74705SXin Li 
1578*67e74705SXin Li /// SynthCountByEnumWithState - To print:
1579*67e74705SXin Li /// ((NSUInteger (*)
1580*67e74705SXin Li ///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1581*67e74705SXin Li ///  (void *)objc_msgSend)((id)l_collection,
1582*67e74705SXin Li ///                        sel_registerName(
1583*67e74705SXin Li ///                          "countByEnumeratingWithState:objects:count:"),
1584*67e74705SXin Li ///                        &enumState,
1585*67e74705SXin Li ///                        (id *)__rw_items, (NSUInteger)16)
1586*67e74705SXin Li ///
SynthCountByEnumWithState(std::string & buf)1587*67e74705SXin Li void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1588*67e74705SXin Li   buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1589*67e74705SXin Li   "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1590*67e74705SXin Li   buf += "\n\t\t";
1591*67e74705SXin Li   buf += "((id)l_collection,\n\t\t";
1592*67e74705SXin Li   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1593*67e74705SXin Li   buf += "\n\t\t";
1594*67e74705SXin Li   buf += "&enumState, "
1595*67e74705SXin Li          "(id *)__rw_items, (_WIN_NSUInteger)16)";
1596*67e74705SXin Li }
1597*67e74705SXin Li 
1598*67e74705SXin Li /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1599*67e74705SXin Li /// statement to exit to its outer synthesized loop.
1600*67e74705SXin Li ///
RewriteBreakStmt(BreakStmt * S)1601*67e74705SXin Li Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1602*67e74705SXin Li   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1603*67e74705SXin Li     return S;
1604*67e74705SXin Li   // replace break with goto __break_label
1605*67e74705SXin Li   std::string buf;
1606*67e74705SXin Li 
1607*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
1608*67e74705SXin Li   buf = "goto __break_label_";
1609*67e74705SXin Li   buf += utostr(ObjCBcLabelNo.back());
1610*67e74705SXin Li   ReplaceText(startLoc, strlen("break"), buf);
1611*67e74705SXin Li 
1612*67e74705SXin Li   return nullptr;
1613*67e74705SXin Li }
1614*67e74705SXin Li 
ConvertSourceLocationToLineDirective(SourceLocation Loc,std::string & LineString)1615*67e74705SXin Li void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1616*67e74705SXin Li                                           SourceLocation Loc,
1617*67e74705SXin Li                                           std::string &LineString) {
1618*67e74705SXin Li   if (Loc.isFileID() && GenerateLineInfo) {
1619*67e74705SXin Li     LineString += "\n#line ";
1620*67e74705SXin Li     PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1621*67e74705SXin Li     LineString += utostr(PLoc.getLine());
1622*67e74705SXin Li     LineString += " \"";
1623*67e74705SXin Li     LineString += Lexer::Stringify(PLoc.getFilename());
1624*67e74705SXin Li     LineString += "\"\n";
1625*67e74705SXin Li   }
1626*67e74705SXin Li }
1627*67e74705SXin Li 
1628*67e74705SXin Li /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1629*67e74705SXin Li /// statement to continue with its inner synthesized loop.
1630*67e74705SXin Li ///
RewriteContinueStmt(ContinueStmt * S)1631*67e74705SXin Li Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1632*67e74705SXin Li   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1633*67e74705SXin Li     return S;
1634*67e74705SXin Li   // replace continue with goto __continue_label
1635*67e74705SXin Li   std::string buf;
1636*67e74705SXin Li 
1637*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
1638*67e74705SXin Li   buf = "goto __continue_label_";
1639*67e74705SXin Li   buf += utostr(ObjCBcLabelNo.back());
1640*67e74705SXin Li   ReplaceText(startLoc, strlen("continue"), buf);
1641*67e74705SXin Li 
1642*67e74705SXin Li   return nullptr;
1643*67e74705SXin Li }
1644*67e74705SXin Li 
1645*67e74705SXin Li /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1646*67e74705SXin Li ///  It rewrites:
1647*67e74705SXin Li /// for ( type elem in collection) { stmts; }
1648*67e74705SXin Li 
1649*67e74705SXin Li /// Into:
1650*67e74705SXin Li /// {
1651*67e74705SXin Li ///   type elem;
1652*67e74705SXin Li ///   struct __objcFastEnumerationState enumState = { 0 };
1653*67e74705SXin Li ///   id __rw_items[16];
1654*67e74705SXin Li ///   id l_collection = (id)collection;
1655*67e74705SXin Li ///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1656*67e74705SXin Li ///                                       objects:__rw_items count:16];
1657*67e74705SXin Li /// if (limit) {
1658*67e74705SXin Li ///   unsigned long startMutations = *enumState.mutationsPtr;
1659*67e74705SXin Li ///   do {
1660*67e74705SXin Li ///        unsigned long counter = 0;
1661*67e74705SXin Li ///        do {
1662*67e74705SXin Li ///             if (startMutations != *enumState.mutationsPtr)
1663*67e74705SXin Li ///               objc_enumerationMutation(l_collection);
1664*67e74705SXin Li ///             elem = (type)enumState.itemsPtr[counter++];
1665*67e74705SXin Li ///             stmts;
1666*67e74705SXin Li ///             __continue_label: ;
1667*67e74705SXin Li ///        } while (counter < limit);
1668*67e74705SXin Li ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1669*67e74705SXin Li ///                                  objects:__rw_items count:16]));
1670*67e74705SXin Li ///   elem = nil;
1671*67e74705SXin Li ///   __break_label: ;
1672*67e74705SXin Li ///  }
1673*67e74705SXin Li ///  else
1674*67e74705SXin Li ///       elem = nil;
1675*67e74705SXin Li ///  }
1676*67e74705SXin Li ///
RewriteObjCForCollectionStmt(ObjCForCollectionStmt * S,SourceLocation OrigEnd)1677*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1678*67e74705SXin Li                                                 SourceLocation OrigEnd) {
1679*67e74705SXin Li   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1680*67e74705SXin Li   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1681*67e74705SXin Li          "ObjCForCollectionStmt Statement stack mismatch");
1682*67e74705SXin Li   assert(!ObjCBcLabelNo.empty() &&
1683*67e74705SXin Li          "ObjCForCollectionStmt - Label No stack empty");
1684*67e74705SXin Li 
1685*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
1686*67e74705SXin Li   const char *startBuf = SM->getCharacterData(startLoc);
1687*67e74705SXin Li   StringRef elementName;
1688*67e74705SXin Li   std::string elementTypeAsString;
1689*67e74705SXin Li   std::string buf;
1690*67e74705SXin Li   // line directive first.
1691*67e74705SXin Li   SourceLocation ForEachLoc = S->getForLoc();
1692*67e74705SXin Li   ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1693*67e74705SXin Li   buf += "{\n\t";
1694*67e74705SXin Li   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1695*67e74705SXin Li     // type elem;
1696*67e74705SXin Li     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1697*67e74705SXin Li     QualType ElementType = cast<ValueDecl>(D)->getType();
1698*67e74705SXin Li     if (ElementType->isObjCQualifiedIdType() ||
1699*67e74705SXin Li         ElementType->isObjCQualifiedInterfaceType())
1700*67e74705SXin Li       // Simply use 'id' for all qualified types.
1701*67e74705SXin Li       elementTypeAsString = "id";
1702*67e74705SXin Li     else
1703*67e74705SXin Li       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1704*67e74705SXin Li     buf += elementTypeAsString;
1705*67e74705SXin Li     buf += " ";
1706*67e74705SXin Li     elementName = D->getName();
1707*67e74705SXin Li     buf += elementName;
1708*67e74705SXin Li     buf += ";\n\t";
1709*67e74705SXin Li   }
1710*67e74705SXin Li   else {
1711*67e74705SXin Li     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1712*67e74705SXin Li     elementName = DR->getDecl()->getName();
1713*67e74705SXin Li     ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1714*67e74705SXin Li     if (VD->getType()->isObjCQualifiedIdType() ||
1715*67e74705SXin Li         VD->getType()->isObjCQualifiedInterfaceType())
1716*67e74705SXin Li       // Simply use 'id' for all qualified types.
1717*67e74705SXin Li       elementTypeAsString = "id";
1718*67e74705SXin Li     else
1719*67e74705SXin Li       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1720*67e74705SXin Li   }
1721*67e74705SXin Li 
1722*67e74705SXin Li   // struct __objcFastEnumerationState enumState = { 0 };
1723*67e74705SXin Li   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1724*67e74705SXin Li   // id __rw_items[16];
1725*67e74705SXin Li   buf += "id __rw_items[16];\n\t";
1726*67e74705SXin Li   // id l_collection = (id)
1727*67e74705SXin Li   buf += "id l_collection = (id)";
1728*67e74705SXin Li   // Find start location of 'collection' the hard way!
1729*67e74705SXin Li   const char *startCollectionBuf = startBuf;
1730*67e74705SXin Li   startCollectionBuf += 3;  // skip 'for'
1731*67e74705SXin Li   startCollectionBuf = strchr(startCollectionBuf, '(');
1732*67e74705SXin Li   startCollectionBuf++; // skip '('
1733*67e74705SXin Li   // find 'in' and skip it.
1734*67e74705SXin Li   while (*startCollectionBuf != ' ' ||
1735*67e74705SXin Li          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1736*67e74705SXin Li          (*(startCollectionBuf+3) != ' ' &&
1737*67e74705SXin Li           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1738*67e74705SXin Li     startCollectionBuf++;
1739*67e74705SXin Li   startCollectionBuf += 3;
1740*67e74705SXin Li 
1741*67e74705SXin Li   // Replace: "for (type element in" with string constructed thus far.
1742*67e74705SXin Li   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1743*67e74705SXin Li   // Replace ')' in for '(' type elem in collection ')' with ';'
1744*67e74705SXin Li   SourceLocation rightParenLoc = S->getRParenLoc();
1745*67e74705SXin Li   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1746*67e74705SXin Li   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1747*67e74705SXin Li   buf = ";\n\t";
1748*67e74705SXin Li 
1749*67e74705SXin Li   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1750*67e74705SXin Li   //                                   objects:__rw_items count:16];
1751*67e74705SXin Li   // which is synthesized into:
1752*67e74705SXin Li   // NSUInteger limit =
1753*67e74705SXin Li   // ((NSUInteger (*)
1754*67e74705SXin Li   //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1755*67e74705SXin Li   //  (void *)objc_msgSend)((id)l_collection,
1756*67e74705SXin Li   //                        sel_registerName(
1757*67e74705SXin Li   //                          "countByEnumeratingWithState:objects:count:"),
1758*67e74705SXin Li   //                        (struct __objcFastEnumerationState *)&state,
1759*67e74705SXin Li   //                        (id *)__rw_items, (NSUInteger)16);
1760*67e74705SXin Li   buf += "_WIN_NSUInteger limit =\n\t\t";
1761*67e74705SXin Li   SynthCountByEnumWithState(buf);
1762*67e74705SXin Li   buf += ";\n\t";
1763*67e74705SXin Li   /// if (limit) {
1764*67e74705SXin Li   ///   unsigned long startMutations = *enumState.mutationsPtr;
1765*67e74705SXin Li   ///   do {
1766*67e74705SXin Li   ///        unsigned long counter = 0;
1767*67e74705SXin Li   ///        do {
1768*67e74705SXin Li   ///             if (startMutations != *enumState.mutationsPtr)
1769*67e74705SXin Li   ///               objc_enumerationMutation(l_collection);
1770*67e74705SXin Li   ///             elem = (type)enumState.itemsPtr[counter++];
1771*67e74705SXin Li   buf += "if (limit) {\n\t";
1772*67e74705SXin Li   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1773*67e74705SXin Li   buf += "do {\n\t\t";
1774*67e74705SXin Li   buf += "unsigned long counter = 0;\n\t\t";
1775*67e74705SXin Li   buf += "do {\n\t\t\t";
1776*67e74705SXin Li   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1777*67e74705SXin Li   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1778*67e74705SXin Li   buf += elementName;
1779*67e74705SXin Li   buf += " = (";
1780*67e74705SXin Li   buf += elementTypeAsString;
1781*67e74705SXin Li   buf += ")enumState.itemsPtr[counter++];";
1782*67e74705SXin Li   // Replace ')' in for '(' type elem in collection ')' with all of these.
1783*67e74705SXin Li   ReplaceText(lparenLoc, 1, buf);
1784*67e74705SXin Li 
1785*67e74705SXin Li   ///            __continue_label: ;
1786*67e74705SXin Li   ///        } while (counter < limit);
1787*67e74705SXin Li   ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1788*67e74705SXin Li   ///                                  objects:__rw_items count:16]));
1789*67e74705SXin Li   ///   elem = nil;
1790*67e74705SXin Li   ///   __break_label: ;
1791*67e74705SXin Li   ///  }
1792*67e74705SXin Li   ///  else
1793*67e74705SXin Li   ///       elem = nil;
1794*67e74705SXin Li   ///  }
1795*67e74705SXin Li   ///
1796*67e74705SXin Li   buf = ";\n\t";
1797*67e74705SXin Li   buf += "__continue_label_";
1798*67e74705SXin Li   buf += utostr(ObjCBcLabelNo.back());
1799*67e74705SXin Li   buf += ": ;";
1800*67e74705SXin Li   buf += "\n\t\t";
1801*67e74705SXin Li   buf += "} while (counter < limit);\n\t";
1802*67e74705SXin Li   buf += "} while ((limit = ";
1803*67e74705SXin Li   SynthCountByEnumWithState(buf);
1804*67e74705SXin Li   buf += "));\n\t";
1805*67e74705SXin Li   buf += elementName;
1806*67e74705SXin Li   buf += " = ((";
1807*67e74705SXin Li   buf += elementTypeAsString;
1808*67e74705SXin Li   buf += ")0);\n\t";
1809*67e74705SXin Li   buf += "__break_label_";
1810*67e74705SXin Li   buf += utostr(ObjCBcLabelNo.back());
1811*67e74705SXin Li   buf += ": ;\n\t";
1812*67e74705SXin Li   buf += "}\n\t";
1813*67e74705SXin Li   buf += "else\n\t\t";
1814*67e74705SXin Li   buf += elementName;
1815*67e74705SXin Li   buf += " = ((";
1816*67e74705SXin Li   buf += elementTypeAsString;
1817*67e74705SXin Li   buf += ")0);\n\t";
1818*67e74705SXin Li   buf += "}\n";
1819*67e74705SXin Li 
1820*67e74705SXin Li   // Insert all these *after* the statement body.
1821*67e74705SXin Li   // FIXME: If this should support Obj-C++, support CXXTryStmt
1822*67e74705SXin Li   if (isa<CompoundStmt>(S->getBody())) {
1823*67e74705SXin Li     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1824*67e74705SXin Li     InsertText(endBodyLoc, buf);
1825*67e74705SXin Li   } else {
1826*67e74705SXin Li     /* Need to treat single statements specially. For example:
1827*67e74705SXin Li      *
1828*67e74705SXin Li      *     for (A *a in b) if (stuff()) break;
1829*67e74705SXin Li      *     for (A *a in b) xxxyy;
1830*67e74705SXin Li      *
1831*67e74705SXin Li      * The following code simply scans ahead to the semi to find the actual end.
1832*67e74705SXin Li      */
1833*67e74705SXin Li     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1834*67e74705SXin Li     const char *semiBuf = strchr(stmtBuf, ';');
1835*67e74705SXin Li     assert(semiBuf && "Can't find ';'");
1836*67e74705SXin Li     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1837*67e74705SXin Li     InsertText(endBodyLoc, buf);
1838*67e74705SXin Li   }
1839*67e74705SXin Li   Stmts.pop_back();
1840*67e74705SXin Li   ObjCBcLabelNo.pop_back();
1841*67e74705SXin Li   return nullptr;
1842*67e74705SXin Li }
1843*67e74705SXin Li 
Write_RethrowObject(std::string & buf)1844*67e74705SXin Li static void Write_RethrowObject(std::string &buf) {
1845*67e74705SXin Li   buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1846*67e74705SXin Li   buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1847*67e74705SXin Li   buf += "\tid rethrow;\n";
1848*67e74705SXin Li   buf += "\t} _fin_force_rethow(_rethrow);";
1849*67e74705SXin Li }
1850*67e74705SXin Li 
1851*67e74705SXin Li /// RewriteObjCSynchronizedStmt -
1852*67e74705SXin Li /// This routine rewrites @synchronized(expr) stmt;
1853*67e74705SXin Li /// into:
1854*67e74705SXin Li /// objc_sync_enter(expr);
1855*67e74705SXin Li /// @try stmt @finally { objc_sync_exit(expr); }
1856*67e74705SXin Li ///
RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt * S)1857*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1858*67e74705SXin Li   // Get the start location and compute the semi location.
1859*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
1860*67e74705SXin Li   const char *startBuf = SM->getCharacterData(startLoc);
1861*67e74705SXin Li 
1862*67e74705SXin Li   assert((*startBuf == '@') && "bogus @synchronized location");
1863*67e74705SXin Li 
1864*67e74705SXin Li   std::string buf;
1865*67e74705SXin Li   SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1866*67e74705SXin Li   ConvertSourceLocationToLineDirective(SynchLoc, buf);
1867*67e74705SXin Li   buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1868*67e74705SXin Li 
1869*67e74705SXin Li   const char *lparenBuf = startBuf;
1870*67e74705SXin Li   while (*lparenBuf != '(') lparenBuf++;
1871*67e74705SXin Li   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1872*67e74705SXin Li 
1873*67e74705SXin Li   buf = "; objc_sync_enter(_sync_obj);\n";
1874*67e74705SXin Li   buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1875*67e74705SXin Li   buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1876*67e74705SXin Li   buf += "\n\tid sync_exit;";
1877*67e74705SXin Li   buf += "\n\t} _sync_exit(_sync_obj);\n";
1878*67e74705SXin Li 
1879*67e74705SXin Li   // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1880*67e74705SXin Li   // the sync expression is typically a message expression that's already
1881*67e74705SXin Li   // been rewritten! (which implies the SourceLocation's are invalid).
1882*67e74705SXin Li   SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1883*67e74705SXin Li   const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1884*67e74705SXin Li   while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1885*67e74705SXin Li   RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1886*67e74705SXin Li 
1887*67e74705SXin Li   SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1888*67e74705SXin Li   const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1889*67e74705SXin Li   assert (*LBraceLocBuf == '{');
1890*67e74705SXin Li   ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1891*67e74705SXin Li 
1892*67e74705SXin Li   SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1893*67e74705SXin Li   assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1894*67e74705SXin Li          "bogus @synchronized block");
1895*67e74705SXin Li 
1896*67e74705SXin Li   buf = "} catch (id e) {_rethrow = e;}\n";
1897*67e74705SXin Li   Write_RethrowObject(buf);
1898*67e74705SXin Li   buf += "}\n";
1899*67e74705SXin Li   buf += "}\n";
1900*67e74705SXin Li 
1901*67e74705SXin Li   ReplaceText(startRBraceLoc, 1, buf);
1902*67e74705SXin Li 
1903*67e74705SXin Li   return nullptr;
1904*67e74705SXin Li }
1905*67e74705SXin Li 
WarnAboutReturnGotoStmts(Stmt * S)1906*67e74705SXin Li void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1907*67e74705SXin Li {
1908*67e74705SXin Li   // Perform a bottom up traversal of all children.
1909*67e74705SXin Li   for (Stmt *SubStmt : S->children())
1910*67e74705SXin Li     if (SubStmt)
1911*67e74705SXin Li       WarnAboutReturnGotoStmts(SubStmt);
1912*67e74705SXin Li 
1913*67e74705SXin Li   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1914*67e74705SXin Li     Diags.Report(Context->getFullLoc(S->getLocStart()),
1915*67e74705SXin Li                  TryFinallyContainsReturnDiag);
1916*67e74705SXin Li   }
1917*67e74705SXin Li }
1918*67e74705SXin Li 
RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt * S)1919*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1920*67e74705SXin Li   SourceLocation startLoc = S->getAtLoc();
1921*67e74705SXin Li   ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1922*67e74705SXin Li   ReplaceText(S->getSubStmt()->getLocStart(), 1,
1923*67e74705SXin Li               "{ __AtAutoreleasePool __autoreleasepool; ");
1924*67e74705SXin Li 
1925*67e74705SXin Li   return nullptr;
1926*67e74705SXin Li }
1927*67e74705SXin Li 
RewriteObjCTryStmt(ObjCAtTryStmt * S)1928*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1929*67e74705SXin Li   ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1930*67e74705SXin Li   bool noCatch = S->getNumCatchStmts() == 0;
1931*67e74705SXin Li   std::string buf;
1932*67e74705SXin Li   SourceLocation TryLocation = S->getAtTryLoc();
1933*67e74705SXin Li   ConvertSourceLocationToLineDirective(TryLocation, buf);
1934*67e74705SXin Li 
1935*67e74705SXin Li   if (finalStmt) {
1936*67e74705SXin Li     if (noCatch)
1937*67e74705SXin Li       buf += "{ id volatile _rethrow = 0;\n";
1938*67e74705SXin Li     else {
1939*67e74705SXin Li       buf += "{ id volatile _rethrow = 0;\ntry {\n";
1940*67e74705SXin Li     }
1941*67e74705SXin Li   }
1942*67e74705SXin Li   // Get the start location and compute the semi location.
1943*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
1944*67e74705SXin Li   const char *startBuf = SM->getCharacterData(startLoc);
1945*67e74705SXin Li 
1946*67e74705SXin Li   assert((*startBuf == '@') && "bogus @try location");
1947*67e74705SXin Li   if (finalStmt)
1948*67e74705SXin Li     ReplaceText(startLoc, 1, buf);
1949*67e74705SXin Li   else
1950*67e74705SXin Li     // @try -> try
1951*67e74705SXin Li     ReplaceText(startLoc, 1, "");
1952*67e74705SXin Li 
1953*67e74705SXin Li   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1954*67e74705SXin Li     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1955*67e74705SXin Li     VarDecl *catchDecl = Catch->getCatchParamDecl();
1956*67e74705SXin Li 
1957*67e74705SXin Li     startLoc = Catch->getLocStart();
1958*67e74705SXin Li     bool AtRemoved = false;
1959*67e74705SXin Li     if (catchDecl) {
1960*67e74705SXin Li       QualType t = catchDecl->getType();
1961*67e74705SXin Li       if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1962*67e74705SXin Li         // Should be a pointer to a class.
1963*67e74705SXin Li         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1964*67e74705SXin Li         if (IDecl) {
1965*67e74705SXin Li           std::string Result;
1966*67e74705SXin Li           ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1967*67e74705SXin Li 
1968*67e74705SXin Li           startBuf = SM->getCharacterData(startLoc);
1969*67e74705SXin Li           assert((*startBuf == '@') && "bogus @catch location");
1970*67e74705SXin Li           SourceLocation rParenLoc = Catch->getRParenLoc();
1971*67e74705SXin Li           const char *rParenBuf = SM->getCharacterData(rParenLoc);
1972*67e74705SXin Li 
1973*67e74705SXin Li           // _objc_exc_Foo *_e as argument to catch.
1974*67e74705SXin Li           Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1975*67e74705SXin Li           Result += " *_"; Result += catchDecl->getNameAsString();
1976*67e74705SXin Li           Result += ")";
1977*67e74705SXin Li           ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1978*67e74705SXin Li           // Foo *e = (Foo *)_e;
1979*67e74705SXin Li           Result.clear();
1980*67e74705SXin Li           Result = "{ ";
1981*67e74705SXin Li           Result += IDecl->getNameAsString();
1982*67e74705SXin Li           Result += " *"; Result += catchDecl->getNameAsString();
1983*67e74705SXin Li           Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1984*67e74705SXin Li           Result += "_"; Result += catchDecl->getNameAsString();
1985*67e74705SXin Li 
1986*67e74705SXin Li           Result += "; ";
1987*67e74705SXin Li           SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1988*67e74705SXin Li           ReplaceText(lBraceLoc, 1, Result);
1989*67e74705SXin Li           AtRemoved = true;
1990*67e74705SXin Li         }
1991*67e74705SXin Li       }
1992*67e74705SXin Li     }
1993*67e74705SXin Li     if (!AtRemoved)
1994*67e74705SXin Li       // @catch -> catch
1995*67e74705SXin Li       ReplaceText(startLoc, 1, "");
1996*67e74705SXin Li 
1997*67e74705SXin Li   }
1998*67e74705SXin Li   if (finalStmt) {
1999*67e74705SXin Li     buf.clear();
2000*67e74705SXin Li     SourceLocation FinallyLoc = finalStmt->getLocStart();
2001*67e74705SXin Li 
2002*67e74705SXin Li     if (noCatch) {
2003*67e74705SXin Li       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2004*67e74705SXin Li       buf += "catch (id e) {_rethrow = e;}\n";
2005*67e74705SXin Li     }
2006*67e74705SXin Li     else {
2007*67e74705SXin Li       buf += "}\n";
2008*67e74705SXin Li       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2009*67e74705SXin Li       buf += "catch (id e) {_rethrow = e;}\n";
2010*67e74705SXin Li     }
2011*67e74705SXin Li 
2012*67e74705SXin Li     SourceLocation startFinalLoc = finalStmt->getLocStart();
2013*67e74705SXin Li     ReplaceText(startFinalLoc, 8, buf);
2014*67e74705SXin Li     Stmt *body = finalStmt->getFinallyBody();
2015*67e74705SXin Li     SourceLocation startFinalBodyLoc = body->getLocStart();
2016*67e74705SXin Li     buf.clear();
2017*67e74705SXin Li     Write_RethrowObject(buf);
2018*67e74705SXin Li     ReplaceText(startFinalBodyLoc, 1, buf);
2019*67e74705SXin Li 
2020*67e74705SXin Li     SourceLocation endFinalBodyLoc = body->getLocEnd();
2021*67e74705SXin Li     ReplaceText(endFinalBodyLoc, 1, "}\n}");
2022*67e74705SXin Li     // Now check for any return/continue/go statements within the @try.
2023*67e74705SXin Li     WarnAboutReturnGotoStmts(S->getTryBody());
2024*67e74705SXin Li   }
2025*67e74705SXin Li 
2026*67e74705SXin Li   return nullptr;
2027*67e74705SXin Li }
2028*67e74705SXin Li 
2029*67e74705SXin Li // This can't be done with ReplaceStmt(S, ThrowExpr), since
2030*67e74705SXin Li // the throw expression is typically a message expression that's already
2031*67e74705SXin Li // been rewritten! (which implies the SourceLocation's are invalid).
RewriteObjCThrowStmt(ObjCAtThrowStmt * S)2032*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2033*67e74705SXin Li   // Get the start location and compute the semi location.
2034*67e74705SXin Li   SourceLocation startLoc = S->getLocStart();
2035*67e74705SXin Li   const char *startBuf = SM->getCharacterData(startLoc);
2036*67e74705SXin Li 
2037*67e74705SXin Li   assert((*startBuf == '@') && "bogus @throw location");
2038*67e74705SXin Li 
2039*67e74705SXin Li   std::string buf;
2040*67e74705SXin Li   /* void objc_exception_throw(id) __attribute__((noreturn)); */
2041*67e74705SXin Li   if (S->getThrowExpr())
2042*67e74705SXin Li     buf = "objc_exception_throw(";
2043*67e74705SXin Li   else
2044*67e74705SXin Li     buf = "throw";
2045*67e74705SXin Li 
2046*67e74705SXin Li   // handle "@  throw" correctly.
2047*67e74705SXin Li   const char *wBuf = strchr(startBuf, 'w');
2048*67e74705SXin Li   assert((*wBuf == 'w') && "@throw: can't find 'w'");
2049*67e74705SXin Li   ReplaceText(startLoc, wBuf-startBuf+1, buf);
2050*67e74705SXin Li 
2051*67e74705SXin Li   SourceLocation endLoc = S->getLocEnd();
2052*67e74705SXin Li   const char *endBuf = SM->getCharacterData(endLoc);
2053*67e74705SXin Li   const char *semiBuf = strchr(endBuf, ';');
2054*67e74705SXin Li   assert((*semiBuf == ';') && "@throw: can't find ';'");
2055*67e74705SXin Li   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2056*67e74705SXin Li   if (S->getThrowExpr())
2057*67e74705SXin Li     ReplaceText(semiLoc, 1, ");");
2058*67e74705SXin Li   return nullptr;
2059*67e74705SXin Li }
2060*67e74705SXin Li 
RewriteAtEncode(ObjCEncodeExpr * Exp)2061*67e74705SXin Li Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2062*67e74705SXin Li   // Create a new string expression.
2063*67e74705SXin Li   std::string StrEncoding;
2064*67e74705SXin Li   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2065*67e74705SXin Li   Expr *Replacement = getStringLiteral(StrEncoding);
2066*67e74705SXin Li   ReplaceStmt(Exp, Replacement);
2067*67e74705SXin Li 
2068*67e74705SXin Li   // Replace this subexpr in the parent.
2069*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2070*67e74705SXin Li   return Replacement;
2071*67e74705SXin Li }
2072*67e74705SXin Li 
RewriteAtSelector(ObjCSelectorExpr * Exp)2073*67e74705SXin Li Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2074*67e74705SXin Li   if (!SelGetUidFunctionDecl)
2075*67e74705SXin Li     SynthSelGetUidFunctionDecl();
2076*67e74705SXin Li   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2077*67e74705SXin Li   // Create a call to sel_registerName("selName").
2078*67e74705SXin Li   SmallVector<Expr*, 8> SelExprs;
2079*67e74705SXin Li   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2080*67e74705SXin Li   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2081*67e74705SXin Li                                                   SelExprs);
2082*67e74705SXin Li   ReplaceStmt(Exp, SelExp);
2083*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2084*67e74705SXin Li   return SelExp;
2085*67e74705SXin Li }
2086*67e74705SXin Li 
2087*67e74705SXin Li CallExpr *
SynthesizeCallToFunctionDecl(FunctionDecl * FD,ArrayRef<Expr * > Args,SourceLocation StartLoc,SourceLocation EndLoc)2088*67e74705SXin Li RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2089*67e74705SXin Li                                                 ArrayRef<Expr *> Args,
2090*67e74705SXin Li                                                 SourceLocation StartLoc,
2091*67e74705SXin Li                                                 SourceLocation EndLoc) {
2092*67e74705SXin Li   // Get the type, we will need to reference it in a couple spots.
2093*67e74705SXin Li   QualType msgSendType = FD->getType();
2094*67e74705SXin Li 
2095*67e74705SXin Li   // Create a reference to the objc_msgSend() declaration.
2096*67e74705SXin Li   DeclRefExpr *DRE =
2097*67e74705SXin Li     new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2098*67e74705SXin Li 
2099*67e74705SXin Li   // Now, we cast the reference to a pointer to the objc_msgSend type.
2100*67e74705SXin Li   QualType pToFunc = Context->getPointerType(msgSendType);
2101*67e74705SXin Li   ImplicitCastExpr *ICE =
2102*67e74705SXin Li     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2103*67e74705SXin Li                              DRE, nullptr, VK_RValue);
2104*67e74705SXin Li 
2105*67e74705SXin Li   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2106*67e74705SXin Li 
2107*67e74705SXin Li   CallExpr *Exp =  new (Context) CallExpr(*Context, ICE, Args,
2108*67e74705SXin Li                                           FT->getCallResultType(*Context),
2109*67e74705SXin Li                                           VK_RValue, EndLoc);
2110*67e74705SXin Li   return Exp;
2111*67e74705SXin Li }
2112*67e74705SXin Li 
scanForProtocolRefs(const char * startBuf,const char * endBuf,const char * & startRef,const char * & endRef)2113*67e74705SXin Li static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2114*67e74705SXin Li                                 const char *&startRef, const char *&endRef) {
2115*67e74705SXin Li   while (startBuf < endBuf) {
2116*67e74705SXin Li     if (*startBuf == '<')
2117*67e74705SXin Li       startRef = startBuf; // mark the start.
2118*67e74705SXin Li     if (*startBuf == '>') {
2119*67e74705SXin Li       if (startRef && *startRef == '<') {
2120*67e74705SXin Li         endRef = startBuf; // mark the end.
2121*67e74705SXin Li         return true;
2122*67e74705SXin Li       }
2123*67e74705SXin Li       return false;
2124*67e74705SXin Li     }
2125*67e74705SXin Li     startBuf++;
2126*67e74705SXin Li   }
2127*67e74705SXin Li   return false;
2128*67e74705SXin Li }
2129*67e74705SXin Li 
scanToNextArgument(const char * & argRef)2130*67e74705SXin Li static void scanToNextArgument(const char *&argRef) {
2131*67e74705SXin Li   int angle = 0;
2132*67e74705SXin Li   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2133*67e74705SXin Li     if (*argRef == '<')
2134*67e74705SXin Li       angle++;
2135*67e74705SXin Li     else if (*argRef == '>')
2136*67e74705SXin Li       angle--;
2137*67e74705SXin Li     argRef++;
2138*67e74705SXin Li   }
2139*67e74705SXin Li   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2140*67e74705SXin Li }
2141*67e74705SXin Li 
needToScanForQualifiers(QualType T)2142*67e74705SXin Li bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2143*67e74705SXin Li   if (T->isObjCQualifiedIdType())
2144*67e74705SXin Li     return true;
2145*67e74705SXin Li   if (const PointerType *PT = T->getAs<PointerType>()) {
2146*67e74705SXin Li     if (PT->getPointeeType()->isObjCQualifiedIdType())
2147*67e74705SXin Li       return true;
2148*67e74705SXin Li   }
2149*67e74705SXin Li   if (T->isObjCObjectPointerType()) {
2150*67e74705SXin Li     T = T->getPointeeType();
2151*67e74705SXin Li     return T->isObjCQualifiedInterfaceType();
2152*67e74705SXin Li   }
2153*67e74705SXin Li   if (T->isArrayType()) {
2154*67e74705SXin Li     QualType ElemTy = Context->getBaseElementType(T);
2155*67e74705SXin Li     return needToScanForQualifiers(ElemTy);
2156*67e74705SXin Li   }
2157*67e74705SXin Li   return false;
2158*67e74705SXin Li }
2159*67e74705SXin Li 
RewriteObjCQualifiedInterfaceTypes(Expr * E)2160*67e74705SXin Li void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2161*67e74705SXin Li   QualType Type = E->getType();
2162*67e74705SXin Li   if (needToScanForQualifiers(Type)) {
2163*67e74705SXin Li     SourceLocation Loc, EndLoc;
2164*67e74705SXin Li 
2165*67e74705SXin Li     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2166*67e74705SXin Li       Loc = ECE->getLParenLoc();
2167*67e74705SXin Li       EndLoc = ECE->getRParenLoc();
2168*67e74705SXin Li     } else {
2169*67e74705SXin Li       Loc = E->getLocStart();
2170*67e74705SXin Li       EndLoc = E->getLocEnd();
2171*67e74705SXin Li     }
2172*67e74705SXin Li     // This will defend against trying to rewrite synthesized expressions.
2173*67e74705SXin Li     if (Loc.isInvalid() || EndLoc.isInvalid())
2174*67e74705SXin Li       return;
2175*67e74705SXin Li 
2176*67e74705SXin Li     const char *startBuf = SM->getCharacterData(Loc);
2177*67e74705SXin Li     const char *endBuf = SM->getCharacterData(EndLoc);
2178*67e74705SXin Li     const char *startRef = nullptr, *endRef = nullptr;
2179*67e74705SXin Li     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180*67e74705SXin Li       // Get the locations of the startRef, endRef.
2181*67e74705SXin Li       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2182*67e74705SXin Li       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2183*67e74705SXin Li       // Comment out the protocol references.
2184*67e74705SXin Li       InsertText(LessLoc, "/*");
2185*67e74705SXin Li       InsertText(GreaterLoc, "*/");
2186*67e74705SXin Li     }
2187*67e74705SXin Li   }
2188*67e74705SXin Li }
2189*67e74705SXin Li 
RewriteObjCQualifiedInterfaceTypes(Decl * Dcl)2190*67e74705SXin Li void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2191*67e74705SXin Li   SourceLocation Loc;
2192*67e74705SXin Li   QualType Type;
2193*67e74705SXin Li   const FunctionProtoType *proto = nullptr;
2194*67e74705SXin Li   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2195*67e74705SXin Li     Loc = VD->getLocation();
2196*67e74705SXin Li     Type = VD->getType();
2197*67e74705SXin Li   }
2198*67e74705SXin Li   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2199*67e74705SXin Li     Loc = FD->getLocation();
2200*67e74705SXin Li     // Check for ObjC 'id' and class types that have been adorned with protocol
2201*67e74705SXin Li     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2202*67e74705SXin Li     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203*67e74705SXin Li     assert(funcType && "missing function type");
2204*67e74705SXin Li     proto = dyn_cast<FunctionProtoType>(funcType);
2205*67e74705SXin Li     if (!proto)
2206*67e74705SXin Li       return;
2207*67e74705SXin Li     Type = proto->getReturnType();
2208*67e74705SXin Li   }
2209*67e74705SXin Li   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2210*67e74705SXin Li     Loc = FD->getLocation();
2211*67e74705SXin Li     Type = FD->getType();
2212*67e74705SXin Li   }
2213*67e74705SXin Li   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2214*67e74705SXin Li     Loc = TD->getLocation();
2215*67e74705SXin Li     Type = TD->getUnderlyingType();
2216*67e74705SXin Li   }
2217*67e74705SXin Li   else
2218*67e74705SXin Li     return;
2219*67e74705SXin Li 
2220*67e74705SXin Li   if (needToScanForQualifiers(Type)) {
2221*67e74705SXin Li     // Since types are unique, we need to scan the buffer.
2222*67e74705SXin Li 
2223*67e74705SXin Li     const char *endBuf = SM->getCharacterData(Loc);
2224*67e74705SXin Li     const char *startBuf = endBuf;
2225*67e74705SXin Li     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2226*67e74705SXin Li       startBuf--; // scan backward (from the decl location) for return type.
2227*67e74705SXin Li     const char *startRef = nullptr, *endRef = nullptr;
2228*67e74705SXin Li     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229*67e74705SXin Li       // Get the locations of the startRef, endRef.
2230*67e74705SXin Li       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2231*67e74705SXin Li       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2232*67e74705SXin Li       // Comment out the protocol references.
2233*67e74705SXin Li       InsertText(LessLoc, "/*");
2234*67e74705SXin Li       InsertText(GreaterLoc, "*/");
2235*67e74705SXin Li     }
2236*67e74705SXin Li   }
2237*67e74705SXin Li   if (!proto)
2238*67e74705SXin Li       return; // most likely, was a variable
2239*67e74705SXin Li   // Now check arguments.
2240*67e74705SXin Li   const char *startBuf = SM->getCharacterData(Loc);
2241*67e74705SXin Li   const char *startFuncBuf = startBuf;
2242*67e74705SXin Li   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2243*67e74705SXin Li     if (needToScanForQualifiers(proto->getParamType(i))) {
2244*67e74705SXin Li       // Since types are unique, we need to scan the buffer.
2245*67e74705SXin Li 
2246*67e74705SXin Li       const char *endBuf = startBuf;
2247*67e74705SXin Li       // scan forward (from the decl location) for argument types.
2248*67e74705SXin Li       scanToNextArgument(endBuf);
2249*67e74705SXin Li       const char *startRef = nullptr, *endRef = nullptr;
2250*67e74705SXin Li       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2251*67e74705SXin Li         // Get the locations of the startRef, endRef.
2252*67e74705SXin Li         SourceLocation LessLoc =
2253*67e74705SXin Li           Loc.getLocWithOffset(startRef-startFuncBuf);
2254*67e74705SXin Li         SourceLocation GreaterLoc =
2255*67e74705SXin Li           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2256*67e74705SXin Li         // Comment out the protocol references.
2257*67e74705SXin Li         InsertText(LessLoc, "/*");
2258*67e74705SXin Li         InsertText(GreaterLoc, "*/");
2259*67e74705SXin Li       }
2260*67e74705SXin Li       startBuf = ++endBuf;
2261*67e74705SXin Li     }
2262*67e74705SXin Li     else {
2263*67e74705SXin Li       // If the function name is derived from a macro expansion, then the
2264*67e74705SXin Li       // argument buffer will not follow the name. Need to speak with Chris.
2265*67e74705SXin Li       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2266*67e74705SXin Li         startBuf++; // scan forward (from the decl location) for argument types.
2267*67e74705SXin Li       startBuf++;
2268*67e74705SXin Li     }
2269*67e74705SXin Li   }
2270*67e74705SXin Li }
2271*67e74705SXin Li 
RewriteTypeOfDecl(VarDecl * ND)2272*67e74705SXin Li void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2273*67e74705SXin Li   QualType QT = ND->getType();
2274*67e74705SXin Li   const Type* TypePtr = QT->getAs<Type>();
2275*67e74705SXin Li   if (!isa<TypeOfExprType>(TypePtr))
2276*67e74705SXin Li     return;
2277*67e74705SXin Li   while (isa<TypeOfExprType>(TypePtr)) {
2278*67e74705SXin Li     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2279*67e74705SXin Li     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2280*67e74705SXin Li     TypePtr = QT->getAs<Type>();
2281*67e74705SXin Li   }
2282*67e74705SXin Li   // FIXME. This will not work for multiple declarators; as in:
2283*67e74705SXin Li   // __typeof__(a) b,c,d;
2284*67e74705SXin Li   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2285*67e74705SXin Li   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2286*67e74705SXin Li   const char *startBuf = SM->getCharacterData(DeclLoc);
2287*67e74705SXin Li   if (ND->getInit()) {
2288*67e74705SXin Li     std::string Name(ND->getNameAsString());
2289*67e74705SXin Li     TypeAsString += " " + Name + " = ";
2290*67e74705SXin Li     Expr *E = ND->getInit();
2291*67e74705SXin Li     SourceLocation startLoc;
2292*67e74705SXin Li     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2293*67e74705SXin Li       startLoc = ECE->getLParenLoc();
2294*67e74705SXin Li     else
2295*67e74705SXin Li       startLoc = E->getLocStart();
2296*67e74705SXin Li     startLoc = SM->getExpansionLoc(startLoc);
2297*67e74705SXin Li     const char *endBuf = SM->getCharacterData(startLoc);
2298*67e74705SXin Li     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2299*67e74705SXin Li   }
2300*67e74705SXin Li   else {
2301*67e74705SXin Li     SourceLocation X = ND->getLocEnd();
2302*67e74705SXin Li     X = SM->getExpansionLoc(X);
2303*67e74705SXin Li     const char *endBuf = SM->getCharacterData(X);
2304*67e74705SXin Li     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2305*67e74705SXin Li   }
2306*67e74705SXin Li }
2307*67e74705SXin Li 
2308*67e74705SXin Li // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
SynthSelGetUidFunctionDecl()2309*67e74705SXin Li void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2310*67e74705SXin Li   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2311*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2312*67e74705SXin Li   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2313*67e74705SXin Li   QualType getFuncType =
2314*67e74705SXin Li     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2315*67e74705SXin Li   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2316*67e74705SXin Li                                                SourceLocation(),
2317*67e74705SXin Li                                                SourceLocation(),
2318*67e74705SXin Li                                                SelGetUidIdent, getFuncType,
2319*67e74705SXin Li                                                nullptr, SC_Extern);
2320*67e74705SXin Li }
2321*67e74705SXin Li 
RewriteFunctionDecl(FunctionDecl * FD)2322*67e74705SXin Li void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2323*67e74705SXin Li   // declared in <objc/objc.h>
2324*67e74705SXin Li   if (FD->getIdentifier() &&
2325*67e74705SXin Li       FD->getName() == "sel_registerName") {
2326*67e74705SXin Li     SelGetUidFunctionDecl = FD;
2327*67e74705SXin Li     return;
2328*67e74705SXin Li   }
2329*67e74705SXin Li   RewriteObjCQualifiedInterfaceTypes(FD);
2330*67e74705SXin Li }
2331*67e74705SXin Li 
RewriteBlockPointerType(std::string & Str,QualType Type)2332*67e74705SXin Li void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2333*67e74705SXin Li   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2334*67e74705SXin Li   const char *argPtr = TypeString.c_str();
2335*67e74705SXin Li   if (!strchr(argPtr, '^')) {
2336*67e74705SXin Li     Str += TypeString;
2337*67e74705SXin Li     return;
2338*67e74705SXin Li   }
2339*67e74705SXin Li   while (*argPtr) {
2340*67e74705SXin Li     Str += (*argPtr == '^' ? '*' : *argPtr);
2341*67e74705SXin Li     argPtr++;
2342*67e74705SXin Li   }
2343*67e74705SXin Li }
2344*67e74705SXin Li 
2345*67e74705SXin Li // FIXME. Consolidate this routine with RewriteBlockPointerType.
RewriteBlockPointerTypeVariable(std::string & Str,ValueDecl * VD)2346*67e74705SXin Li void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2347*67e74705SXin Li                                                   ValueDecl *VD) {
2348*67e74705SXin Li   QualType Type = VD->getType();
2349*67e74705SXin Li   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2350*67e74705SXin Li   const char *argPtr = TypeString.c_str();
2351*67e74705SXin Li   int paren = 0;
2352*67e74705SXin Li   while (*argPtr) {
2353*67e74705SXin Li     switch (*argPtr) {
2354*67e74705SXin Li       case '(':
2355*67e74705SXin Li         Str += *argPtr;
2356*67e74705SXin Li         paren++;
2357*67e74705SXin Li         break;
2358*67e74705SXin Li       case ')':
2359*67e74705SXin Li         Str += *argPtr;
2360*67e74705SXin Li         paren--;
2361*67e74705SXin Li         break;
2362*67e74705SXin Li       case '^':
2363*67e74705SXin Li         Str += '*';
2364*67e74705SXin Li         if (paren == 1)
2365*67e74705SXin Li           Str += VD->getNameAsString();
2366*67e74705SXin Li         break;
2367*67e74705SXin Li       default:
2368*67e74705SXin Li         Str += *argPtr;
2369*67e74705SXin Li         break;
2370*67e74705SXin Li     }
2371*67e74705SXin Li     argPtr++;
2372*67e74705SXin Li   }
2373*67e74705SXin Li }
2374*67e74705SXin Li 
RewriteBlockLiteralFunctionDecl(FunctionDecl * FD)2375*67e74705SXin Li void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2376*67e74705SXin Li   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2377*67e74705SXin Li   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2378*67e74705SXin Li   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2379*67e74705SXin Li   if (!proto)
2380*67e74705SXin Li     return;
2381*67e74705SXin Li   QualType Type = proto->getReturnType();
2382*67e74705SXin Li   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2383*67e74705SXin Li   FdStr += " ";
2384*67e74705SXin Li   FdStr += FD->getName();
2385*67e74705SXin Li   FdStr +=  "(";
2386*67e74705SXin Li   unsigned numArgs = proto->getNumParams();
2387*67e74705SXin Li   for (unsigned i = 0; i < numArgs; i++) {
2388*67e74705SXin Li     QualType ArgType = proto->getParamType(i);
2389*67e74705SXin Li   RewriteBlockPointerType(FdStr, ArgType);
2390*67e74705SXin Li   if (i+1 < numArgs)
2391*67e74705SXin Li     FdStr += ", ";
2392*67e74705SXin Li   }
2393*67e74705SXin Li   if (FD->isVariadic()) {
2394*67e74705SXin Li     FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
2395*67e74705SXin Li   }
2396*67e74705SXin Li   else
2397*67e74705SXin Li     FdStr +=  ");\n";
2398*67e74705SXin Li   InsertText(FunLocStart, FdStr);
2399*67e74705SXin Li }
2400*67e74705SXin Li 
2401*67e74705SXin Li // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
SynthSuperConstructorFunctionDecl()2402*67e74705SXin Li void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2403*67e74705SXin Li   if (SuperConstructorFunctionDecl)
2404*67e74705SXin Li     return;
2405*67e74705SXin Li   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2406*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2407*67e74705SXin Li   QualType argT = Context->getObjCIdType();
2408*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'id' type");
2409*67e74705SXin Li   ArgTys.push_back(argT);
2410*67e74705SXin Li   ArgTys.push_back(argT);
2411*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2412*67e74705SXin Li                                                ArgTys);
2413*67e74705SXin Li   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414*67e74705SXin Li                                                      SourceLocation(),
2415*67e74705SXin Li                                                      SourceLocation(),
2416*67e74705SXin Li                                                      msgSendIdent, msgSendType,
2417*67e74705SXin Li                                                      nullptr, SC_Extern);
2418*67e74705SXin Li }
2419*67e74705SXin Li 
2420*67e74705SXin Li // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
SynthMsgSendFunctionDecl()2421*67e74705SXin Li void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2422*67e74705SXin Li   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2423*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2424*67e74705SXin Li   QualType argT = Context->getObjCIdType();
2425*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'id' type");
2426*67e74705SXin Li   ArgTys.push_back(argT);
2427*67e74705SXin Li   argT = Context->getObjCSelType();
2428*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'SEL' type");
2429*67e74705SXin Li   ArgTys.push_back(argT);
2430*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2431*67e74705SXin Li                                                ArgTys, /*isVariadic=*/true);
2432*67e74705SXin Li   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2433*67e74705SXin Li                                              SourceLocation(),
2434*67e74705SXin Li                                              SourceLocation(),
2435*67e74705SXin Li                                              msgSendIdent, msgSendType, nullptr,
2436*67e74705SXin Li                                              SC_Extern);
2437*67e74705SXin Li }
2438*67e74705SXin Li 
2439*67e74705SXin Li // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
SynthMsgSendSuperFunctionDecl()2440*67e74705SXin Li void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2441*67e74705SXin Li   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2442*67e74705SXin Li   SmallVector<QualType, 2> ArgTys;
2443*67e74705SXin Li   ArgTys.push_back(Context->VoidTy);
2444*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2445*67e74705SXin Li                                                ArgTys, /*isVariadic=*/true);
2446*67e74705SXin Li   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2447*67e74705SXin Li                                                   SourceLocation(),
2448*67e74705SXin Li                                                   SourceLocation(),
2449*67e74705SXin Li                                                   msgSendIdent, msgSendType,
2450*67e74705SXin Li                                                   nullptr, SC_Extern);
2451*67e74705SXin Li }
2452*67e74705SXin Li 
2453*67e74705SXin Li // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
SynthMsgSendStretFunctionDecl()2454*67e74705SXin Li void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2455*67e74705SXin Li   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2456*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2457*67e74705SXin Li   QualType argT = Context->getObjCIdType();
2458*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'id' type");
2459*67e74705SXin Li   ArgTys.push_back(argT);
2460*67e74705SXin Li   argT = Context->getObjCSelType();
2461*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'SEL' type");
2462*67e74705SXin Li   ArgTys.push_back(argT);
2463*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2464*67e74705SXin Li                                                ArgTys, /*isVariadic=*/true);
2465*67e74705SXin Li   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2466*67e74705SXin Li                                                   SourceLocation(),
2467*67e74705SXin Li                                                   SourceLocation(),
2468*67e74705SXin Li                                                   msgSendIdent, msgSendType,
2469*67e74705SXin Li                                                   nullptr, SC_Extern);
2470*67e74705SXin Li }
2471*67e74705SXin Li 
2472*67e74705SXin Li // SynthMsgSendSuperStretFunctionDecl -
2473*67e74705SXin Li // id objc_msgSendSuper_stret(void);
SynthMsgSendSuperStretFunctionDecl()2474*67e74705SXin Li void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2475*67e74705SXin Li   IdentifierInfo *msgSendIdent =
2476*67e74705SXin Li     &Context->Idents.get("objc_msgSendSuper_stret");
2477*67e74705SXin Li   SmallVector<QualType, 2> ArgTys;
2478*67e74705SXin Li   ArgTys.push_back(Context->VoidTy);
2479*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2480*67e74705SXin Li                                                ArgTys, /*isVariadic=*/true);
2481*67e74705SXin Li   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2482*67e74705SXin Li                                                        SourceLocation(),
2483*67e74705SXin Li                                                        SourceLocation(),
2484*67e74705SXin Li                                                        msgSendIdent,
2485*67e74705SXin Li                                                        msgSendType, nullptr,
2486*67e74705SXin Li                                                        SC_Extern);
2487*67e74705SXin Li }
2488*67e74705SXin Li 
2489*67e74705SXin Li // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
SynthMsgSendFpretFunctionDecl()2490*67e74705SXin Li void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2491*67e74705SXin Li   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2492*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2493*67e74705SXin Li   QualType argT = Context->getObjCIdType();
2494*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'id' type");
2495*67e74705SXin Li   ArgTys.push_back(argT);
2496*67e74705SXin Li   argT = Context->getObjCSelType();
2497*67e74705SXin Li   assert(!argT.isNull() && "Can't find 'SEL' type");
2498*67e74705SXin Li   ArgTys.push_back(argT);
2499*67e74705SXin Li   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2500*67e74705SXin Li                                                ArgTys, /*isVariadic=*/true);
2501*67e74705SXin Li   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2502*67e74705SXin Li                                                   SourceLocation(),
2503*67e74705SXin Li                                                   SourceLocation(),
2504*67e74705SXin Li                                                   msgSendIdent, msgSendType,
2505*67e74705SXin Li                                                   nullptr, SC_Extern);
2506*67e74705SXin Li }
2507*67e74705SXin Li 
2508*67e74705SXin Li // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
SynthGetClassFunctionDecl()2509*67e74705SXin Li void RewriteModernObjC::SynthGetClassFunctionDecl() {
2510*67e74705SXin Li   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2511*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2512*67e74705SXin Li   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2513*67e74705SXin Li   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2514*67e74705SXin Li                                                 ArgTys);
2515*67e74705SXin Li   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2516*67e74705SXin Li                                               SourceLocation(),
2517*67e74705SXin Li                                               SourceLocation(),
2518*67e74705SXin Li                                               getClassIdent, getClassType,
2519*67e74705SXin Li                                               nullptr, SC_Extern);
2520*67e74705SXin Li }
2521*67e74705SXin Li 
2522*67e74705SXin Li // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
SynthGetSuperClassFunctionDecl()2523*67e74705SXin Li void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2524*67e74705SXin Li   IdentifierInfo *getSuperClassIdent =
2525*67e74705SXin Li     &Context->Idents.get("class_getSuperclass");
2526*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2527*67e74705SXin Li   ArgTys.push_back(Context->getObjCClassType());
2528*67e74705SXin Li   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2529*67e74705SXin Li                                                 ArgTys);
2530*67e74705SXin Li   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2531*67e74705SXin Li                                                    SourceLocation(),
2532*67e74705SXin Li                                                    SourceLocation(),
2533*67e74705SXin Li                                                    getSuperClassIdent,
2534*67e74705SXin Li                                                    getClassType, nullptr,
2535*67e74705SXin Li                                                    SC_Extern);
2536*67e74705SXin Li }
2537*67e74705SXin Li 
2538*67e74705SXin Li // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
SynthGetMetaClassFunctionDecl()2539*67e74705SXin Li void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2540*67e74705SXin Li   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2541*67e74705SXin Li   SmallVector<QualType, 16> ArgTys;
2542*67e74705SXin Li   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2543*67e74705SXin Li   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2544*67e74705SXin Li                                                 ArgTys);
2545*67e74705SXin Li   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2546*67e74705SXin Li                                                   SourceLocation(),
2547*67e74705SXin Li                                                   SourceLocation(),
2548*67e74705SXin Li                                                   getClassIdent, getClassType,
2549*67e74705SXin Li                                                   nullptr, SC_Extern);
2550*67e74705SXin Li }
2551*67e74705SXin Li 
RewriteObjCStringLiteral(ObjCStringLiteral * Exp)2552*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2553*67e74705SXin Li   assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2554*67e74705SXin Li   QualType strType = getConstantStringStructType();
2555*67e74705SXin Li 
2556*67e74705SXin Li   std::string S = "__NSConstantStringImpl_";
2557*67e74705SXin Li 
2558*67e74705SXin Li   std::string tmpName = InFileName;
2559*67e74705SXin Li   unsigned i;
2560*67e74705SXin Li   for (i=0; i < tmpName.length(); i++) {
2561*67e74705SXin Li     char c = tmpName.at(i);
2562*67e74705SXin Li     // replace any non-alphanumeric characters with '_'.
2563*67e74705SXin Li     if (!isAlphanumeric(c))
2564*67e74705SXin Li       tmpName[i] = '_';
2565*67e74705SXin Li   }
2566*67e74705SXin Li   S += tmpName;
2567*67e74705SXin Li   S += "_";
2568*67e74705SXin Li   S += utostr(NumObjCStringLiterals++);
2569*67e74705SXin Li 
2570*67e74705SXin Li   Preamble += "static __NSConstantStringImpl " + S;
2571*67e74705SXin Li   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2572*67e74705SXin Li   Preamble += "0x000007c8,"; // utf8_str
2573*67e74705SXin Li   // The pretty printer for StringLiteral handles escape characters properly.
2574*67e74705SXin Li   std::string prettyBufS;
2575*67e74705SXin Li   llvm::raw_string_ostream prettyBuf(prettyBufS);
2576*67e74705SXin Li   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2577*67e74705SXin Li   Preamble += prettyBuf.str();
2578*67e74705SXin Li   Preamble += ",";
2579*67e74705SXin Li   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2580*67e74705SXin Li 
2581*67e74705SXin Li   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2582*67e74705SXin Li                                    SourceLocation(), &Context->Idents.get(S),
2583*67e74705SXin Li                                    strType, nullptr, SC_Static);
2584*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2585*67e74705SXin Li                                                SourceLocation());
2586*67e74705SXin Li   Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2587*67e74705SXin Li                                  Context->getPointerType(DRE->getType()),
2588*67e74705SXin Li                                            VK_RValue, OK_Ordinary,
2589*67e74705SXin Li                                            SourceLocation());
2590*67e74705SXin Li   // cast to NSConstantString *
2591*67e74705SXin Li   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2592*67e74705SXin Li                                             CK_CPointerToObjCPointerCast, Unop);
2593*67e74705SXin Li   ReplaceStmt(Exp, cast);
2594*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2595*67e74705SXin Li   return cast;
2596*67e74705SXin Li }
2597*67e74705SXin Li 
RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr * Exp)2598*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2599*67e74705SXin Li   unsigned IntSize =
2600*67e74705SXin Li     static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2601*67e74705SXin Li 
2602*67e74705SXin Li   Expr *FlagExp = IntegerLiteral::Create(*Context,
2603*67e74705SXin Li                                          llvm::APInt(IntSize, Exp->getValue()),
2604*67e74705SXin Li                                          Context->IntTy, Exp->getLocation());
2605*67e74705SXin Li   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2606*67e74705SXin Li                                             CK_BitCast, FlagExp);
2607*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2608*67e74705SXin Li                                           cast);
2609*67e74705SXin Li   ReplaceStmt(Exp, PE);
2610*67e74705SXin Li   return PE;
2611*67e74705SXin Li }
2612*67e74705SXin Li 
RewriteObjCBoxedExpr(ObjCBoxedExpr * Exp)2613*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2614*67e74705SXin Li   // synthesize declaration of helper functions needed in this routine.
2615*67e74705SXin Li   if (!SelGetUidFunctionDecl)
2616*67e74705SXin Li     SynthSelGetUidFunctionDecl();
2617*67e74705SXin Li   // use objc_msgSend() for all.
2618*67e74705SXin Li   if (!MsgSendFunctionDecl)
2619*67e74705SXin Li     SynthMsgSendFunctionDecl();
2620*67e74705SXin Li   if (!GetClassFunctionDecl)
2621*67e74705SXin Li     SynthGetClassFunctionDecl();
2622*67e74705SXin Li 
2623*67e74705SXin Li   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2624*67e74705SXin Li   SourceLocation StartLoc = Exp->getLocStart();
2625*67e74705SXin Li   SourceLocation EndLoc = Exp->getLocEnd();
2626*67e74705SXin Li 
2627*67e74705SXin Li   // Synthesize a call to objc_msgSend().
2628*67e74705SXin Li   SmallVector<Expr*, 4> MsgExprs;
2629*67e74705SXin Li   SmallVector<Expr*, 4> ClsExprs;
2630*67e74705SXin Li 
2631*67e74705SXin Li   // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2632*67e74705SXin Li   ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2633*67e74705SXin Li   ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2634*67e74705SXin Li 
2635*67e74705SXin Li   IdentifierInfo *clsName = BoxingClass->getIdentifier();
2636*67e74705SXin Li   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2637*67e74705SXin Li   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2638*67e74705SXin Li                                                StartLoc, EndLoc);
2639*67e74705SXin Li   MsgExprs.push_back(Cls);
2640*67e74705SXin Li 
2641*67e74705SXin Li   // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2642*67e74705SXin Li   // it will be the 2nd argument.
2643*67e74705SXin Li   SmallVector<Expr*, 4> SelExprs;
2644*67e74705SXin Li   SelExprs.push_back(
2645*67e74705SXin Li       getStringLiteral(BoxingMethod->getSelector().getAsString()));
2646*67e74705SXin Li   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2647*67e74705SXin Li                                                   SelExprs, StartLoc, EndLoc);
2648*67e74705SXin Li   MsgExprs.push_back(SelExp);
2649*67e74705SXin Li 
2650*67e74705SXin Li   // User provided sub-expression is the 3rd, and last, argument.
2651*67e74705SXin Li   Expr *subExpr  = Exp->getSubExpr();
2652*67e74705SXin Li   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2653*67e74705SXin Li     QualType type = ICE->getType();
2654*67e74705SXin Li     const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2655*67e74705SXin Li     CastKind CK = CK_BitCast;
2656*67e74705SXin Li     if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2657*67e74705SXin Li       CK = CK_IntegralToBoolean;
2658*67e74705SXin Li     subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2659*67e74705SXin Li   }
2660*67e74705SXin Li   MsgExprs.push_back(subExpr);
2661*67e74705SXin Li 
2662*67e74705SXin Li   SmallVector<QualType, 4> ArgTypes;
2663*67e74705SXin Li   ArgTypes.push_back(Context->getObjCClassType());
2664*67e74705SXin Li   ArgTypes.push_back(Context->getObjCSelType());
2665*67e74705SXin Li   for (const auto PI : BoxingMethod->parameters())
2666*67e74705SXin Li     ArgTypes.push_back(PI->getType());
2667*67e74705SXin Li 
2668*67e74705SXin Li   QualType returnType = Exp->getType();
2669*67e74705SXin Li   // Get the type, we will need to reference it in a couple spots.
2670*67e74705SXin Li   QualType msgSendType = MsgSendFlavor->getType();
2671*67e74705SXin Li 
2672*67e74705SXin Li   // Create a reference to the objc_msgSend() declaration.
2673*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2674*67e74705SXin Li                                                VK_LValue, SourceLocation());
2675*67e74705SXin Li 
2676*67e74705SXin Li   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2677*67e74705SXin Li                                             Context->getPointerType(Context->VoidTy),
2678*67e74705SXin Li                                             CK_BitCast, DRE);
2679*67e74705SXin Li 
2680*67e74705SXin Li   // Now do the "normal" pointer to function cast.
2681*67e74705SXin Li   QualType castType =
2682*67e74705SXin Li     getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2683*67e74705SXin Li   castType = Context->getPointerType(castType);
2684*67e74705SXin Li   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2685*67e74705SXin Li                                   cast);
2686*67e74705SXin Li 
2687*67e74705SXin Li   // Don't forget the parens to enforce the proper binding.
2688*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2689*67e74705SXin Li 
2690*67e74705SXin Li   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2691*67e74705SXin Li   CallExpr *CE = new (Context)
2692*67e74705SXin Li       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2693*67e74705SXin Li   ReplaceStmt(Exp, CE);
2694*67e74705SXin Li   return CE;
2695*67e74705SXin Li }
2696*67e74705SXin Li 
RewriteObjCArrayLiteralExpr(ObjCArrayLiteral * Exp)2697*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2698*67e74705SXin Li   // synthesize declaration of helper functions needed in this routine.
2699*67e74705SXin Li   if (!SelGetUidFunctionDecl)
2700*67e74705SXin Li     SynthSelGetUidFunctionDecl();
2701*67e74705SXin Li   // use objc_msgSend() for all.
2702*67e74705SXin Li   if (!MsgSendFunctionDecl)
2703*67e74705SXin Li     SynthMsgSendFunctionDecl();
2704*67e74705SXin Li   if (!GetClassFunctionDecl)
2705*67e74705SXin Li     SynthGetClassFunctionDecl();
2706*67e74705SXin Li 
2707*67e74705SXin Li   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2708*67e74705SXin Li   SourceLocation StartLoc = Exp->getLocStart();
2709*67e74705SXin Li   SourceLocation EndLoc = Exp->getLocEnd();
2710*67e74705SXin Li 
2711*67e74705SXin Li   // Build the expression: __NSContainer_literal(int, ...).arr
2712*67e74705SXin Li   QualType IntQT = Context->IntTy;
2713*67e74705SXin Li   QualType NSArrayFType =
2714*67e74705SXin Li     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2715*67e74705SXin Li   std::string NSArrayFName("__NSContainer_literal");
2716*67e74705SXin Li   FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2717*67e74705SXin Li   DeclRefExpr *NSArrayDRE =
2718*67e74705SXin Li     new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2719*67e74705SXin Li                               SourceLocation());
2720*67e74705SXin Li 
2721*67e74705SXin Li   SmallVector<Expr*, 16> InitExprs;
2722*67e74705SXin Li   unsigned NumElements = Exp->getNumElements();
2723*67e74705SXin Li   unsigned UnsignedIntSize =
2724*67e74705SXin Li     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725*67e74705SXin Li   Expr *count = IntegerLiteral::Create(*Context,
2726*67e74705SXin Li                                        llvm::APInt(UnsignedIntSize, NumElements),
2727*67e74705SXin Li                                        Context->UnsignedIntTy, SourceLocation());
2728*67e74705SXin Li   InitExprs.push_back(count);
2729*67e74705SXin Li   for (unsigned i = 0; i < NumElements; i++)
2730*67e74705SXin Li     InitExprs.push_back(Exp->getElement(i));
2731*67e74705SXin Li   Expr *NSArrayCallExpr =
2732*67e74705SXin Li     new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2733*67e74705SXin Li                            NSArrayFType, VK_LValue, SourceLocation());
2734*67e74705SXin Li 
2735*67e74705SXin Li   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2736*67e74705SXin Li                                     SourceLocation(),
2737*67e74705SXin Li                                     &Context->Idents.get("arr"),
2738*67e74705SXin Li                                     Context->getPointerType(Context->VoidPtrTy),
2739*67e74705SXin Li                                     nullptr, /*BitWidth=*/nullptr,
2740*67e74705SXin Li                                     /*Mutable=*/true, ICIS_NoInit);
2741*67e74705SXin Li   MemberExpr *ArrayLiteralME = new (Context)
2742*67e74705SXin Li       MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2743*67e74705SXin Li                  SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2744*67e74705SXin Li   QualType ConstIdT = Context->getObjCIdType().withConst();
2745*67e74705SXin Li   CStyleCastExpr * ArrayLiteralObjects =
2746*67e74705SXin Li     NoTypeInfoCStyleCastExpr(Context,
2747*67e74705SXin Li                              Context->getPointerType(ConstIdT),
2748*67e74705SXin Li                              CK_BitCast,
2749*67e74705SXin Li                              ArrayLiteralME);
2750*67e74705SXin Li 
2751*67e74705SXin Li   // Synthesize a call to objc_msgSend().
2752*67e74705SXin Li   SmallVector<Expr*, 32> MsgExprs;
2753*67e74705SXin Li   SmallVector<Expr*, 4> ClsExprs;
2754*67e74705SXin Li   QualType expType = Exp->getType();
2755*67e74705SXin Li 
2756*67e74705SXin Li   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2757*67e74705SXin Li   ObjCInterfaceDecl *Class =
2758*67e74705SXin Li     expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2759*67e74705SXin Li 
2760*67e74705SXin Li   IdentifierInfo *clsName = Class->getIdentifier();
2761*67e74705SXin Li   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2762*67e74705SXin Li   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2763*67e74705SXin Li                                                StartLoc, EndLoc);
2764*67e74705SXin Li   MsgExprs.push_back(Cls);
2765*67e74705SXin Li 
2766*67e74705SXin Li   // Create a call to sel_registerName("arrayWithObjects:count:").
2767*67e74705SXin Li   // it will be the 2nd argument.
2768*67e74705SXin Li   SmallVector<Expr*, 4> SelExprs;
2769*67e74705SXin Li   ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2770*67e74705SXin Li   SelExprs.push_back(
2771*67e74705SXin Li       getStringLiteral(ArrayMethod->getSelector().getAsString()));
2772*67e74705SXin Li   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2773*67e74705SXin Li                                                   SelExprs, StartLoc, EndLoc);
2774*67e74705SXin Li   MsgExprs.push_back(SelExp);
2775*67e74705SXin Li 
2776*67e74705SXin Li   // (const id [])objects
2777*67e74705SXin Li   MsgExprs.push_back(ArrayLiteralObjects);
2778*67e74705SXin Li 
2779*67e74705SXin Li   // (NSUInteger)cnt
2780*67e74705SXin Li   Expr *cnt = IntegerLiteral::Create(*Context,
2781*67e74705SXin Li                                      llvm::APInt(UnsignedIntSize, NumElements),
2782*67e74705SXin Li                                      Context->UnsignedIntTy, SourceLocation());
2783*67e74705SXin Li   MsgExprs.push_back(cnt);
2784*67e74705SXin Li 
2785*67e74705SXin Li   SmallVector<QualType, 4> ArgTypes;
2786*67e74705SXin Li   ArgTypes.push_back(Context->getObjCClassType());
2787*67e74705SXin Li   ArgTypes.push_back(Context->getObjCSelType());
2788*67e74705SXin Li   for (const auto *PI : ArrayMethod->parameters())
2789*67e74705SXin Li     ArgTypes.push_back(PI->getType());
2790*67e74705SXin Li 
2791*67e74705SXin Li   QualType returnType = Exp->getType();
2792*67e74705SXin Li   // Get the type, we will need to reference it in a couple spots.
2793*67e74705SXin Li   QualType msgSendType = MsgSendFlavor->getType();
2794*67e74705SXin Li 
2795*67e74705SXin Li   // Create a reference to the objc_msgSend() declaration.
2796*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2797*67e74705SXin Li                                                VK_LValue, SourceLocation());
2798*67e74705SXin Li 
2799*67e74705SXin Li   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2800*67e74705SXin Li                                             Context->getPointerType(Context->VoidTy),
2801*67e74705SXin Li                                             CK_BitCast, DRE);
2802*67e74705SXin Li 
2803*67e74705SXin Li   // Now do the "normal" pointer to function cast.
2804*67e74705SXin Li   QualType castType =
2805*67e74705SXin Li   getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2806*67e74705SXin Li   castType = Context->getPointerType(castType);
2807*67e74705SXin Li   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2808*67e74705SXin Li                                   cast);
2809*67e74705SXin Li 
2810*67e74705SXin Li   // Don't forget the parens to enforce the proper binding.
2811*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2812*67e74705SXin Li 
2813*67e74705SXin Li   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2814*67e74705SXin Li   CallExpr *CE = new (Context)
2815*67e74705SXin Li       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2816*67e74705SXin Li   ReplaceStmt(Exp, CE);
2817*67e74705SXin Li   return CE;
2818*67e74705SXin Li }
2819*67e74705SXin Li 
RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral * Exp)2820*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2821*67e74705SXin Li   // synthesize declaration of helper functions needed in this routine.
2822*67e74705SXin Li   if (!SelGetUidFunctionDecl)
2823*67e74705SXin Li     SynthSelGetUidFunctionDecl();
2824*67e74705SXin Li   // use objc_msgSend() for all.
2825*67e74705SXin Li   if (!MsgSendFunctionDecl)
2826*67e74705SXin Li     SynthMsgSendFunctionDecl();
2827*67e74705SXin Li   if (!GetClassFunctionDecl)
2828*67e74705SXin Li     SynthGetClassFunctionDecl();
2829*67e74705SXin Li 
2830*67e74705SXin Li   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2831*67e74705SXin Li   SourceLocation StartLoc = Exp->getLocStart();
2832*67e74705SXin Li   SourceLocation EndLoc = Exp->getLocEnd();
2833*67e74705SXin Li 
2834*67e74705SXin Li   // Build the expression: __NSContainer_literal(int, ...).arr
2835*67e74705SXin Li   QualType IntQT = Context->IntTy;
2836*67e74705SXin Li   QualType NSDictFType =
2837*67e74705SXin Li     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2838*67e74705SXin Li   std::string NSDictFName("__NSContainer_literal");
2839*67e74705SXin Li   FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2840*67e74705SXin Li   DeclRefExpr *NSDictDRE =
2841*67e74705SXin Li     new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2842*67e74705SXin Li                               SourceLocation());
2843*67e74705SXin Li 
2844*67e74705SXin Li   SmallVector<Expr*, 16> KeyExprs;
2845*67e74705SXin Li   SmallVector<Expr*, 16> ValueExprs;
2846*67e74705SXin Li 
2847*67e74705SXin Li   unsigned NumElements = Exp->getNumElements();
2848*67e74705SXin Li   unsigned UnsignedIntSize =
2849*67e74705SXin Li     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2850*67e74705SXin Li   Expr *count = IntegerLiteral::Create(*Context,
2851*67e74705SXin Li                                        llvm::APInt(UnsignedIntSize, NumElements),
2852*67e74705SXin Li                                        Context->UnsignedIntTy, SourceLocation());
2853*67e74705SXin Li   KeyExprs.push_back(count);
2854*67e74705SXin Li   ValueExprs.push_back(count);
2855*67e74705SXin Li   for (unsigned i = 0; i < NumElements; i++) {
2856*67e74705SXin Li     ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2857*67e74705SXin Li     KeyExprs.push_back(Element.Key);
2858*67e74705SXin Li     ValueExprs.push_back(Element.Value);
2859*67e74705SXin Li   }
2860*67e74705SXin Li 
2861*67e74705SXin Li   // (const id [])objects
2862*67e74705SXin Li   Expr *NSValueCallExpr =
2863*67e74705SXin Li     new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2864*67e74705SXin Li                            NSDictFType, VK_LValue, SourceLocation());
2865*67e74705SXin Li 
2866*67e74705SXin Li   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2867*67e74705SXin Li                                        SourceLocation(),
2868*67e74705SXin Li                                        &Context->Idents.get("arr"),
2869*67e74705SXin Li                                        Context->getPointerType(Context->VoidPtrTy),
2870*67e74705SXin Li                                        nullptr, /*BitWidth=*/nullptr,
2871*67e74705SXin Li                                        /*Mutable=*/true, ICIS_NoInit);
2872*67e74705SXin Li   MemberExpr *DictLiteralValueME = new (Context)
2873*67e74705SXin Li       MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2874*67e74705SXin Li                  SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2875*67e74705SXin Li   QualType ConstIdT = Context->getObjCIdType().withConst();
2876*67e74705SXin Li   CStyleCastExpr * DictValueObjects =
2877*67e74705SXin Li     NoTypeInfoCStyleCastExpr(Context,
2878*67e74705SXin Li                              Context->getPointerType(ConstIdT),
2879*67e74705SXin Li                              CK_BitCast,
2880*67e74705SXin Li                              DictLiteralValueME);
2881*67e74705SXin Li   // (const id <NSCopying> [])keys
2882*67e74705SXin Li   Expr *NSKeyCallExpr =
2883*67e74705SXin Li     new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2884*67e74705SXin Li                            NSDictFType, VK_LValue, SourceLocation());
2885*67e74705SXin Li 
2886*67e74705SXin Li   MemberExpr *DictLiteralKeyME = new (Context)
2887*67e74705SXin Li       MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2888*67e74705SXin Li                  SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2889*67e74705SXin Li 
2890*67e74705SXin Li   CStyleCastExpr * DictKeyObjects =
2891*67e74705SXin Li     NoTypeInfoCStyleCastExpr(Context,
2892*67e74705SXin Li                              Context->getPointerType(ConstIdT),
2893*67e74705SXin Li                              CK_BitCast,
2894*67e74705SXin Li                              DictLiteralKeyME);
2895*67e74705SXin Li 
2896*67e74705SXin Li   // Synthesize a call to objc_msgSend().
2897*67e74705SXin Li   SmallVector<Expr*, 32> MsgExprs;
2898*67e74705SXin Li   SmallVector<Expr*, 4> ClsExprs;
2899*67e74705SXin Li   QualType expType = Exp->getType();
2900*67e74705SXin Li 
2901*67e74705SXin Li   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2902*67e74705SXin Li   ObjCInterfaceDecl *Class =
2903*67e74705SXin Li   expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2904*67e74705SXin Li 
2905*67e74705SXin Li   IdentifierInfo *clsName = Class->getIdentifier();
2906*67e74705SXin Li   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2907*67e74705SXin Li   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2908*67e74705SXin Li                                                StartLoc, EndLoc);
2909*67e74705SXin Li   MsgExprs.push_back(Cls);
2910*67e74705SXin Li 
2911*67e74705SXin Li   // Create a call to sel_registerName("arrayWithObjects:count:").
2912*67e74705SXin Li   // it will be the 2nd argument.
2913*67e74705SXin Li   SmallVector<Expr*, 4> SelExprs;
2914*67e74705SXin Li   ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2915*67e74705SXin Li   SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2916*67e74705SXin Li   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2917*67e74705SXin Li                                                   SelExprs, StartLoc, EndLoc);
2918*67e74705SXin Li   MsgExprs.push_back(SelExp);
2919*67e74705SXin Li 
2920*67e74705SXin Li   // (const id [])objects
2921*67e74705SXin Li   MsgExprs.push_back(DictValueObjects);
2922*67e74705SXin Li 
2923*67e74705SXin Li   // (const id <NSCopying> [])keys
2924*67e74705SXin Li   MsgExprs.push_back(DictKeyObjects);
2925*67e74705SXin Li 
2926*67e74705SXin Li   // (NSUInteger)cnt
2927*67e74705SXin Li   Expr *cnt = IntegerLiteral::Create(*Context,
2928*67e74705SXin Li                                      llvm::APInt(UnsignedIntSize, NumElements),
2929*67e74705SXin Li                                      Context->UnsignedIntTy, SourceLocation());
2930*67e74705SXin Li   MsgExprs.push_back(cnt);
2931*67e74705SXin Li 
2932*67e74705SXin Li   SmallVector<QualType, 8> ArgTypes;
2933*67e74705SXin Li   ArgTypes.push_back(Context->getObjCClassType());
2934*67e74705SXin Li   ArgTypes.push_back(Context->getObjCSelType());
2935*67e74705SXin Li   for (const auto *PI : DictMethod->parameters()) {
2936*67e74705SXin Li     QualType T = PI->getType();
2937*67e74705SXin Li     if (const PointerType* PT = T->getAs<PointerType>()) {
2938*67e74705SXin Li       QualType PointeeTy = PT->getPointeeType();
2939*67e74705SXin Li       convertToUnqualifiedObjCType(PointeeTy);
2940*67e74705SXin Li       T = Context->getPointerType(PointeeTy);
2941*67e74705SXin Li     }
2942*67e74705SXin Li     ArgTypes.push_back(T);
2943*67e74705SXin Li   }
2944*67e74705SXin Li 
2945*67e74705SXin Li   QualType returnType = Exp->getType();
2946*67e74705SXin Li   // Get the type, we will need to reference it in a couple spots.
2947*67e74705SXin Li   QualType msgSendType = MsgSendFlavor->getType();
2948*67e74705SXin Li 
2949*67e74705SXin Li   // Create a reference to the objc_msgSend() declaration.
2950*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2951*67e74705SXin Li                                                VK_LValue, SourceLocation());
2952*67e74705SXin Li 
2953*67e74705SXin Li   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2954*67e74705SXin Li                                             Context->getPointerType(Context->VoidTy),
2955*67e74705SXin Li                                             CK_BitCast, DRE);
2956*67e74705SXin Li 
2957*67e74705SXin Li   // Now do the "normal" pointer to function cast.
2958*67e74705SXin Li   QualType castType =
2959*67e74705SXin Li   getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2960*67e74705SXin Li   castType = Context->getPointerType(castType);
2961*67e74705SXin Li   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2962*67e74705SXin Li                                   cast);
2963*67e74705SXin Li 
2964*67e74705SXin Li   // Don't forget the parens to enforce the proper binding.
2965*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2966*67e74705SXin Li 
2967*67e74705SXin Li   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2968*67e74705SXin Li   CallExpr *CE = new (Context)
2969*67e74705SXin Li       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2970*67e74705SXin Li   ReplaceStmt(Exp, CE);
2971*67e74705SXin Li   return CE;
2972*67e74705SXin Li }
2973*67e74705SXin Li 
2974*67e74705SXin Li // struct __rw_objc_super {
2975*67e74705SXin Li //   struct objc_object *object; struct objc_object *superClass;
2976*67e74705SXin Li // };
getSuperStructType()2977*67e74705SXin Li QualType RewriteModernObjC::getSuperStructType() {
2978*67e74705SXin Li   if (!SuperStructDecl) {
2979*67e74705SXin Li     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2980*67e74705SXin Li                                          SourceLocation(), SourceLocation(),
2981*67e74705SXin Li                                          &Context->Idents.get("__rw_objc_super"));
2982*67e74705SXin Li     QualType FieldTypes[2];
2983*67e74705SXin Li 
2984*67e74705SXin Li     // struct objc_object *object;
2985*67e74705SXin Li     FieldTypes[0] = Context->getObjCIdType();
2986*67e74705SXin Li     // struct objc_object *superClass;
2987*67e74705SXin Li     FieldTypes[1] = Context->getObjCIdType();
2988*67e74705SXin Li 
2989*67e74705SXin Li     // Create fields
2990*67e74705SXin Li     for (unsigned i = 0; i < 2; ++i) {
2991*67e74705SXin Li       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2992*67e74705SXin Li                                                  SourceLocation(),
2993*67e74705SXin Li                                                  SourceLocation(), nullptr,
2994*67e74705SXin Li                                                  FieldTypes[i], nullptr,
2995*67e74705SXin Li                                                  /*BitWidth=*/nullptr,
2996*67e74705SXin Li                                                  /*Mutable=*/false,
2997*67e74705SXin Li                                                  ICIS_NoInit));
2998*67e74705SXin Li     }
2999*67e74705SXin Li 
3000*67e74705SXin Li     SuperStructDecl->completeDefinition();
3001*67e74705SXin Li   }
3002*67e74705SXin Li   return Context->getTagDeclType(SuperStructDecl);
3003*67e74705SXin Li }
3004*67e74705SXin Li 
getConstantStringStructType()3005*67e74705SXin Li QualType RewriteModernObjC::getConstantStringStructType() {
3006*67e74705SXin Li   if (!ConstantStringDecl) {
3007*67e74705SXin Li     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3008*67e74705SXin Li                                             SourceLocation(), SourceLocation(),
3009*67e74705SXin Li                          &Context->Idents.get("__NSConstantStringImpl"));
3010*67e74705SXin Li     QualType FieldTypes[4];
3011*67e74705SXin Li 
3012*67e74705SXin Li     // struct objc_object *receiver;
3013*67e74705SXin Li     FieldTypes[0] = Context->getObjCIdType();
3014*67e74705SXin Li     // int flags;
3015*67e74705SXin Li     FieldTypes[1] = Context->IntTy;
3016*67e74705SXin Li     // char *str;
3017*67e74705SXin Li     FieldTypes[2] = Context->getPointerType(Context->CharTy);
3018*67e74705SXin Li     // long length;
3019*67e74705SXin Li     FieldTypes[3] = Context->LongTy;
3020*67e74705SXin Li 
3021*67e74705SXin Li     // Create fields
3022*67e74705SXin Li     for (unsigned i = 0; i < 4; ++i) {
3023*67e74705SXin Li       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3024*67e74705SXin Li                                                     ConstantStringDecl,
3025*67e74705SXin Li                                                     SourceLocation(),
3026*67e74705SXin Li                                                     SourceLocation(), nullptr,
3027*67e74705SXin Li                                                     FieldTypes[i], nullptr,
3028*67e74705SXin Li                                                     /*BitWidth=*/nullptr,
3029*67e74705SXin Li                                                     /*Mutable=*/true,
3030*67e74705SXin Li                                                     ICIS_NoInit));
3031*67e74705SXin Li     }
3032*67e74705SXin Li 
3033*67e74705SXin Li     ConstantStringDecl->completeDefinition();
3034*67e74705SXin Li   }
3035*67e74705SXin Li   return Context->getTagDeclType(ConstantStringDecl);
3036*67e74705SXin Li }
3037*67e74705SXin Li 
3038*67e74705SXin Li /// getFunctionSourceLocation - returns start location of a function
3039*67e74705SXin Li /// definition. Complication arises when function has declared as
3040*67e74705SXin Li /// extern "C" or extern "C" {...}
getFunctionSourceLocation(RewriteModernObjC & R,FunctionDecl * FD)3041*67e74705SXin Li static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3042*67e74705SXin Li                                                  FunctionDecl *FD) {
3043*67e74705SXin Li   if (FD->isExternC()  && !FD->isMain()) {
3044*67e74705SXin Li     const DeclContext *DC = FD->getDeclContext();
3045*67e74705SXin Li     if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3046*67e74705SXin Li       // if it is extern "C" {...}, return function decl's own location.
3047*67e74705SXin Li       if (!LSD->getRBraceLoc().isValid())
3048*67e74705SXin Li         return LSD->getExternLoc();
3049*67e74705SXin Li   }
3050*67e74705SXin Li   if (FD->getStorageClass() != SC_None)
3051*67e74705SXin Li     R.RewriteBlockLiteralFunctionDecl(FD);
3052*67e74705SXin Li   return FD->getTypeSpecStartLoc();
3053*67e74705SXin Li }
3054*67e74705SXin Li 
RewriteLineDirective(const Decl * D)3055*67e74705SXin Li void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3056*67e74705SXin Li 
3057*67e74705SXin Li   SourceLocation Location = D->getLocation();
3058*67e74705SXin Li 
3059*67e74705SXin Li   if (Location.isFileID() && GenerateLineInfo) {
3060*67e74705SXin Li     std::string LineString("\n#line ");
3061*67e74705SXin Li     PresumedLoc PLoc = SM->getPresumedLoc(Location);
3062*67e74705SXin Li     LineString += utostr(PLoc.getLine());
3063*67e74705SXin Li     LineString += " \"";
3064*67e74705SXin Li     LineString += Lexer::Stringify(PLoc.getFilename());
3065*67e74705SXin Li     if (isa<ObjCMethodDecl>(D))
3066*67e74705SXin Li       LineString += "\"";
3067*67e74705SXin Li     else LineString += "\"\n";
3068*67e74705SXin Li 
3069*67e74705SXin Li     Location = D->getLocStart();
3070*67e74705SXin Li     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3071*67e74705SXin Li       if (FD->isExternC()  && !FD->isMain()) {
3072*67e74705SXin Li         const DeclContext *DC = FD->getDeclContext();
3073*67e74705SXin Li         if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3074*67e74705SXin Li           // if it is extern "C" {...}, return function decl's own location.
3075*67e74705SXin Li           if (!LSD->getRBraceLoc().isValid())
3076*67e74705SXin Li             Location = LSD->getExternLoc();
3077*67e74705SXin Li       }
3078*67e74705SXin Li     }
3079*67e74705SXin Li     InsertText(Location, LineString);
3080*67e74705SXin Li   }
3081*67e74705SXin Li }
3082*67e74705SXin Li 
3083*67e74705SXin Li /// SynthMsgSendStretCallExpr - This routine translates message expression
3084*67e74705SXin Li /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3085*67e74705SXin Li /// nil check on receiver must be performed before calling objc_msgSend_stret.
3086*67e74705SXin Li /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3087*67e74705SXin Li /// msgSendType - function type of objc_msgSend_stret(...)
3088*67e74705SXin Li /// returnType - Result type of the method being synthesized.
3089*67e74705SXin Li /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3090*67e74705SXin Li /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3091*67e74705SXin Li /// starting with receiver.
3092*67e74705SXin Li /// Method - Method being rewritten.
SynthMsgSendStretCallExpr(FunctionDecl * MsgSendStretFlavor,QualType returnType,SmallVectorImpl<QualType> & ArgTypes,SmallVectorImpl<Expr * > & MsgExprs,ObjCMethodDecl * Method)3093*67e74705SXin Li Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3094*67e74705SXin Li                                                  QualType returnType,
3095*67e74705SXin Li                                                  SmallVectorImpl<QualType> &ArgTypes,
3096*67e74705SXin Li                                                  SmallVectorImpl<Expr*> &MsgExprs,
3097*67e74705SXin Li                                                  ObjCMethodDecl *Method) {
3098*67e74705SXin Li   // Now do the "normal" pointer to function cast.
3099*67e74705SXin Li   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3100*67e74705SXin Li                                             Method ? Method->isVariadic()
3101*67e74705SXin Li                                                    : false);
3102*67e74705SXin Li   castType = Context->getPointerType(castType);
3103*67e74705SXin Li 
3104*67e74705SXin Li   // build type for containing the objc_msgSend_stret object.
3105*67e74705SXin Li   static unsigned stretCount=0;
3106*67e74705SXin Li   std::string name = "__Stret"; name += utostr(stretCount);
3107*67e74705SXin Li   std::string str =
3108*67e74705SXin Li     "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3109*67e74705SXin Li   str += "namespace {\n";
3110*67e74705SXin Li   str += "struct "; str += name;
3111*67e74705SXin Li   str += " {\n\t";
3112*67e74705SXin Li   str += name;
3113*67e74705SXin Li   str += "(id receiver, SEL sel";
3114*67e74705SXin Li   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3115*67e74705SXin Li     std::string ArgName = "arg"; ArgName += utostr(i);
3116*67e74705SXin Li     ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3117*67e74705SXin Li     str += ", "; str += ArgName;
3118*67e74705SXin Li   }
3119*67e74705SXin Li   // could be vararg.
3120*67e74705SXin Li   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3121*67e74705SXin Li     std::string ArgName = "arg"; ArgName += utostr(i);
3122*67e74705SXin Li     MsgExprs[i]->getType().getAsStringInternal(ArgName,
3123*67e74705SXin Li                                                Context->getPrintingPolicy());
3124*67e74705SXin Li     str += ", "; str += ArgName;
3125*67e74705SXin Li   }
3126*67e74705SXin Li 
3127*67e74705SXin Li   str += ") {\n";
3128*67e74705SXin Li   str += "\t  unsigned size = sizeof(";
3129*67e74705SXin Li   str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3130*67e74705SXin Li 
3131*67e74705SXin Li   str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3132*67e74705SXin Li 
3133*67e74705SXin Li   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3134*67e74705SXin Li   str += ")(void *)objc_msgSend)(receiver, sel";
3135*67e74705SXin Li   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3136*67e74705SXin Li     str += ", arg"; str += utostr(i);
3137*67e74705SXin Li   }
3138*67e74705SXin Li   // could be vararg.
3139*67e74705SXin Li   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3140*67e74705SXin Li     str += ", arg"; str += utostr(i);
3141*67e74705SXin Li   }
3142*67e74705SXin Li   str+= ");\n";
3143*67e74705SXin Li 
3144*67e74705SXin Li   str += "\t  else if (receiver == 0)\n";
3145*67e74705SXin Li   str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3146*67e74705SXin Li   str += "\t  else\n";
3147*67e74705SXin Li 
3148*67e74705SXin Li   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3149*67e74705SXin Li   str += ")(void *)objc_msgSend_stret)(receiver, sel";
3150*67e74705SXin Li   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3151*67e74705SXin Li     str += ", arg"; str += utostr(i);
3152*67e74705SXin Li   }
3153*67e74705SXin Li   // could be vararg.
3154*67e74705SXin Li   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3155*67e74705SXin Li     str += ", arg"; str += utostr(i);
3156*67e74705SXin Li   }
3157*67e74705SXin Li   str += ");\n";
3158*67e74705SXin Li 
3159*67e74705SXin Li   str += "\t}\n";
3160*67e74705SXin Li   str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3161*67e74705SXin Li   str += " s;\n";
3162*67e74705SXin Li   str += "};\n};\n\n";
3163*67e74705SXin Li   SourceLocation FunLocStart;
3164*67e74705SXin Li   if (CurFunctionDef)
3165*67e74705SXin Li     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3166*67e74705SXin Li   else {
3167*67e74705SXin Li     assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3168*67e74705SXin Li     FunLocStart = CurMethodDef->getLocStart();
3169*67e74705SXin Li   }
3170*67e74705SXin Li 
3171*67e74705SXin Li   InsertText(FunLocStart, str);
3172*67e74705SXin Li   ++stretCount;
3173*67e74705SXin Li 
3174*67e74705SXin Li   // AST for __Stretn(receiver, args).s;
3175*67e74705SXin Li   IdentifierInfo *ID = &Context->Idents.get(name);
3176*67e74705SXin Li   FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3177*67e74705SXin Li                                           SourceLocation(), ID, castType,
3178*67e74705SXin Li                                           nullptr, SC_Extern, false, false);
3179*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3180*67e74705SXin Li                                                SourceLocation());
3181*67e74705SXin Li   CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3182*67e74705SXin Li                                           castType, VK_LValue, SourceLocation());
3183*67e74705SXin Li 
3184*67e74705SXin Li   FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3185*67e74705SXin Li                                     SourceLocation(),
3186*67e74705SXin Li                                     &Context->Idents.get("s"),
3187*67e74705SXin Li                                     returnType, nullptr,
3188*67e74705SXin Li                                     /*BitWidth=*/nullptr,
3189*67e74705SXin Li                                     /*Mutable=*/true, ICIS_NoInit);
3190*67e74705SXin Li   MemberExpr *ME = new (Context)
3191*67e74705SXin Li       MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3192*67e74705SXin Li                  FieldD->getType(), VK_LValue, OK_Ordinary);
3193*67e74705SXin Li 
3194*67e74705SXin Li   return ME;
3195*67e74705SXin Li }
3196*67e74705SXin Li 
SynthMessageExpr(ObjCMessageExpr * Exp,SourceLocation StartLoc,SourceLocation EndLoc)3197*67e74705SXin Li Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3198*67e74705SXin Li                                     SourceLocation StartLoc,
3199*67e74705SXin Li                                     SourceLocation EndLoc) {
3200*67e74705SXin Li   if (!SelGetUidFunctionDecl)
3201*67e74705SXin Li     SynthSelGetUidFunctionDecl();
3202*67e74705SXin Li   if (!MsgSendFunctionDecl)
3203*67e74705SXin Li     SynthMsgSendFunctionDecl();
3204*67e74705SXin Li   if (!MsgSendSuperFunctionDecl)
3205*67e74705SXin Li     SynthMsgSendSuperFunctionDecl();
3206*67e74705SXin Li   if (!MsgSendStretFunctionDecl)
3207*67e74705SXin Li     SynthMsgSendStretFunctionDecl();
3208*67e74705SXin Li   if (!MsgSendSuperStretFunctionDecl)
3209*67e74705SXin Li     SynthMsgSendSuperStretFunctionDecl();
3210*67e74705SXin Li   if (!MsgSendFpretFunctionDecl)
3211*67e74705SXin Li     SynthMsgSendFpretFunctionDecl();
3212*67e74705SXin Li   if (!GetClassFunctionDecl)
3213*67e74705SXin Li     SynthGetClassFunctionDecl();
3214*67e74705SXin Li   if (!GetSuperClassFunctionDecl)
3215*67e74705SXin Li     SynthGetSuperClassFunctionDecl();
3216*67e74705SXin Li   if (!GetMetaClassFunctionDecl)
3217*67e74705SXin Li     SynthGetMetaClassFunctionDecl();
3218*67e74705SXin Li 
3219*67e74705SXin Li   // default to objc_msgSend().
3220*67e74705SXin Li   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3221*67e74705SXin Li   // May need to use objc_msgSend_stret() as well.
3222*67e74705SXin Li   FunctionDecl *MsgSendStretFlavor = nullptr;
3223*67e74705SXin Li   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3224*67e74705SXin Li     QualType resultType = mDecl->getReturnType();
3225*67e74705SXin Li     if (resultType->isRecordType())
3226*67e74705SXin Li       MsgSendStretFlavor = MsgSendStretFunctionDecl;
3227*67e74705SXin Li     else if (resultType->isRealFloatingType())
3228*67e74705SXin Li       MsgSendFlavor = MsgSendFpretFunctionDecl;
3229*67e74705SXin Li   }
3230*67e74705SXin Li 
3231*67e74705SXin Li   // Synthesize a call to objc_msgSend().
3232*67e74705SXin Li   SmallVector<Expr*, 8> MsgExprs;
3233*67e74705SXin Li   switch (Exp->getReceiverKind()) {
3234*67e74705SXin Li   case ObjCMessageExpr::SuperClass: {
3235*67e74705SXin Li     MsgSendFlavor = MsgSendSuperFunctionDecl;
3236*67e74705SXin Li     if (MsgSendStretFlavor)
3237*67e74705SXin Li       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3238*67e74705SXin Li     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3239*67e74705SXin Li 
3240*67e74705SXin Li     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3241*67e74705SXin Li 
3242*67e74705SXin Li     SmallVector<Expr*, 4> InitExprs;
3243*67e74705SXin Li 
3244*67e74705SXin Li     // set the receiver to self, the first argument to all methods.
3245*67e74705SXin Li     InitExprs.push_back(
3246*67e74705SXin Li       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3247*67e74705SXin Li                                CK_BitCast,
3248*67e74705SXin Li                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3249*67e74705SXin Li                                              false,
3250*67e74705SXin Li                                              Context->getObjCIdType(),
3251*67e74705SXin Li                                              VK_RValue,
3252*67e74705SXin Li                                              SourceLocation()))
3253*67e74705SXin Li                         ); // set the 'receiver'.
3254*67e74705SXin Li 
3255*67e74705SXin Li     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3256*67e74705SXin Li     SmallVector<Expr*, 8> ClsExprs;
3257*67e74705SXin Li     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3258*67e74705SXin Li     // (Class)objc_getClass("CurrentClass")
3259*67e74705SXin Li     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3260*67e74705SXin Li                                                  ClsExprs, StartLoc, EndLoc);
3261*67e74705SXin Li     ClsExprs.clear();
3262*67e74705SXin Li     ClsExprs.push_back(Cls);
3263*67e74705SXin Li     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3264*67e74705SXin Li                                        StartLoc, EndLoc);
3265*67e74705SXin Li 
3266*67e74705SXin Li     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3267*67e74705SXin Li     // To turn off a warning, type-cast to 'id'
3268*67e74705SXin Li     InitExprs.push_back( // set 'super class', using class_getSuperclass().
3269*67e74705SXin Li                         NoTypeInfoCStyleCastExpr(Context,
3270*67e74705SXin Li                                                  Context->getObjCIdType(),
3271*67e74705SXin Li                                                  CK_BitCast, Cls));
3272*67e74705SXin Li     // struct __rw_objc_super
3273*67e74705SXin Li     QualType superType = getSuperStructType();
3274*67e74705SXin Li     Expr *SuperRep;
3275*67e74705SXin Li 
3276*67e74705SXin Li     if (LangOpts.MicrosoftExt) {
3277*67e74705SXin Li       SynthSuperConstructorFunctionDecl();
3278*67e74705SXin Li       // Simulate a constructor call...
3279*67e74705SXin Li       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3280*67e74705SXin Li                                                    false, superType, VK_LValue,
3281*67e74705SXin Li                                                    SourceLocation());
3282*67e74705SXin Li       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3283*67e74705SXin Li                                         superType, VK_LValue,
3284*67e74705SXin Li                                         SourceLocation());
3285*67e74705SXin Li       // The code for super is a little tricky to prevent collision with
3286*67e74705SXin Li       // the structure definition in the header. The rewriter has it's own
3287*67e74705SXin Li       // internal definition (__rw_objc_super) that is uses. This is why
3288*67e74705SXin Li       // we need the cast below. For example:
3289*67e74705SXin Li       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3290*67e74705SXin Li       //
3291*67e74705SXin Li       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3292*67e74705SXin Li                                Context->getPointerType(SuperRep->getType()),
3293*67e74705SXin Li                                              VK_RValue, OK_Ordinary,
3294*67e74705SXin Li                                              SourceLocation());
3295*67e74705SXin Li       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3296*67e74705SXin Li                                           Context->getPointerType(superType),
3297*67e74705SXin Li                                           CK_BitCast, SuperRep);
3298*67e74705SXin Li     } else {
3299*67e74705SXin Li       // (struct __rw_objc_super) { <exprs from above> }
3300*67e74705SXin Li       InitListExpr *ILE =
3301*67e74705SXin Li         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3302*67e74705SXin Li                                    SourceLocation());
3303*67e74705SXin Li       TypeSourceInfo *superTInfo
3304*67e74705SXin Li         = Context->getTrivialTypeSourceInfo(superType);
3305*67e74705SXin Li       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3306*67e74705SXin Li                                                    superType, VK_LValue,
3307*67e74705SXin Li                                                    ILE, false);
3308*67e74705SXin Li       // struct __rw_objc_super *
3309*67e74705SXin Li       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3310*67e74705SXin Li                                Context->getPointerType(SuperRep->getType()),
3311*67e74705SXin Li                                              VK_RValue, OK_Ordinary,
3312*67e74705SXin Li                                              SourceLocation());
3313*67e74705SXin Li     }
3314*67e74705SXin Li     MsgExprs.push_back(SuperRep);
3315*67e74705SXin Li     break;
3316*67e74705SXin Li   }
3317*67e74705SXin Li 
3318*67e74705SXin Li   case ObjCMessageExpr::Class: {
3319*67e74705SXin Li     SmallVector<Expr*, 8> ClsExprs;
3320*67e74705SXin Li     ObjCInterfaceDecl *Class
3321*67e74705SXin Li       = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3322*67e74705SXin Li     IdentifierInfo *clsName = Class->getIdentifier();
3323*67e74705SXin Li     ClsExprs.push_back(getStringLiteral(clsName->getName()));
3324*67e74705SXin Li     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3325*67e74705SXin Li                                                  StartLoc, EndLoc);
3326*67e74705SXin Li     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3327*67e74705SXin Li                                                  Context->getObjCIdType(),
3328*67e74705SXin Li                                                  CK_BitCast, Cls);
3329*67e74705SXin Li     MsgExprs.push_back(ArgExpr);
3330*67e74705SXin Li     break;
3331*67e74705SXin Li   }
3332*67e74705SXin Li 
3333*67e74705SXin Li   case ObjCMessageExpr::SuperInstance:{
3334*67e74705SXin Li     MsgSendFlavor = MsgSendSuperFunctionDecl;
3335*67e74705SXin Li     if (MsgSendStretFlavor)
3336*67e74705SXin Li       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3337*67e74705SXin Li     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3338*67e74705SXin Li     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3339*67e74705SXin Li     SmallVector<Expr*, 4> InitExprs;
3340*67e74705SXin Li 
3341*67e74705SXin Li     InitExprs.push_back(
3342*67e74705SXin Li       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3343*67e74705SXin Li                                CK_BitCast,
3344*67e74705SXin Li                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3345*67e74705SXin Li                                              false,
3346*67e74705SXin Li                                              Context->getObjCIdType(),
3347*67e74705SXin Li                                              VK_RValue, SourceLocation()))
3348*67e74705SXin Li                         ); // set the 'receiver'.
3349*67e74705SXin Li 
3350*67e74705SXin Li     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3351*67e74705SXin Li     SmallVector<Expr*, 8> ClsExprs;
3352*67e74705SXin Li     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3353*67e74705SXin Li     // (Class)objc_getClass("CurrentClass")
3354*67e74705SXin Li     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3355*67e74705SXin Li                                                  StartLoc, EndLoc);
3356*67e74705SXin Li     ClsExprs.clear();
3357*67e74705SXin Li     ClsExprs.push_back(Cls);
3358*67e74705SXin Li     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3359*67e74705SXin Li                                        StartLoc, EndLoc);
3360*67e74705SXin Li 
3361*67e74705SXin Li     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3362*67e74705SXin Li     // To turn off a warning, type-cast to 'id'
3363*67e74705SXin Li     InitExprs.push_back(
3364*67e74705SXin Li       // set 'super class', using class_getSuperclass().
3365*67e74705SXin Li       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3366*67e74705SXin Li                                CK_BitCast, Cls));
3367*67e74705SXin Li     // struct __rw_objc_super
3368*67e74705SXin Li     QualType superType = getSuperStructType();
3369*67e74705SXin Li     Expr *SuperRep;
3370*67e74705SXin Li 
3371*67e74705SXin Li     if (LangOpts.MicrosoftExt) {
3372*67e74705SXin Li       SynthSuperConstructorFunctionDecl();
3373*67e74705SXin Li       // Simulate a constructor call...
3374*67e74705SXin Li       DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3375*67e74705SXin Li                                                    false, superType, VK_LValue,
3376*67e74705SXin Li                                                    SourceLocation());
3377*67e74705SXin Li       SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3378*67e74705SXin Li                                         superType, VK_LValue, SourceLocation());
3379*67e74705SXin Li       // The code for super is a little tricky to prevent collision with
3380*67e74705SXin Li       // the structure definition in the header. The rewriter has it's own
3381*67e74705SXin Li       // internal definition (__rw_objc_super) that is uses. This is why
3382*67e74705SXin Li       // we need the cast below. For example:
3383*67e74705SXin Li       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3384*67e74705SXin Li       //
3385*67e74705SXin Li       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3386*67e74705SXin Li                                Context->getPointerType(SuperRep->getType()),
3387*67e74705SXin Li                                VK_RValue, OK_Ordinary,
3388*67e74705SXin Li                                SourceLocation());
3389*67e74705SXin Li       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3390*67e74705SXin Li                                Context->getPointerType(superType),
3391*67e74705SXin Li                                CK_BitCast, SuperRep);
3392*67e74705SXin Li     } else {
3393*67e74705SXin Li       // (struct __rw_objc_super) { <exprs from above> }
3394*67e74705SXin Li       InitListExpr *ILE =
3395*67e74705SXin Li         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3396*67e74705SXin Li                                    SourceLocation());
3397*67e74705SXin Li       TypeSourceInfo *superTInfo
3398*67e74705SXin Li         = Context->getTrivialTypeSourceInfo(superType);
3399*67e74705SXin Li       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3400*67e74705SXin Li                                                    superType, VK_RValue, ILE,
3401*67e74705SXin Li                                                    false);
3402*67e74705SXin Li     }
3403*67e74705SXin Li     MsgExprs.push_back(SuperRep);
3404*67e74705SXin Li     break;
3405*67e74705SXin Li   }
3406*67e74705SXin Li 
3407*67e74705SXin Li   case ObjCMessageExpr::Instance: {
3408*67e74705SXin Li     // Remove all type-casts because it may contain objc-style types; e.g.
3409*67e74705SXin Li     // Foo<Proto> *.
3410*67e74705SXin Li     Expr *recExpr = Exp->getInstanceReceiver();
3411*67e74705SXin Li     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3412*67e74705SXin Li       recExpr = CE->getSubExpr();
3413*67e74705SXin Li     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3414*67e74705SXin Li                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3415*67e74705SXin Li                                      ? CK_BlockPointerToObjCPointerCast
3416*67e74705SXin Li                                      : CK_CPointerToObjCPointerCast;
3417*67e74705SXin Li 
3418*67e74705SXin Li     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3419*67e74705SXin Li                                        CK, recExpr);
3420*67e74705SXin Li     MsgExprs.push_back(recExpr);
3421*67e74705SXin Li     break;
3422*67e74705SXin Li   }
3423*67e74705SXin Li   }
3424*67e74705SXin Li 
3425*67e74705SXin Li   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3426*67e74705SXin Li   SmallVector<Expr*, 8> SelExprs;
3427*67e74705SXin Li   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3428*67e74705SXin Li   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3429*67e74705SXin Li                                                   SelExprs, StartLoc, EndLoc);
3430*67e74705SXin Li   MsgExprs.push_back(SelExp);
3431*67e74705SXin Li 
3432*67e74705SXin Li   // Now push any user supplied arguments.
3433*67e74705SXin Li   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3434*67e74705SXin Li     Expr *userExpr = Exp->getArg(i);
3435*67e74705SXin Li     // Make all implicit casts explicit...ICE comes in handy:-)
3436*67e74705SXin Li     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3437*67e74705SXin Li       // Reuse the ICE type, it is exactly what the doctor ordered.
3438*67e74705SXin Li       QualType type = ICE->getType();
3439*67e74705SXin Li       if (needToScanForQualifiers(type))
3440*67e74705SXin Li         type = Context->getObjCIdType();
3441*67e74705SXin Li       // Make sure we convert "type (^)(...)" to "type (*)(...)".
3442*67e74705SXin Li       (void)convertBlockPointerToFunctionPointer(type);
3443*67e74705SXin Li       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3444*67e74705SXin Li       CastKind CK;
3445*67e74705SXin Li       if (SubExpr->getType()->isIntegralType(*Context) &&
3446*67e74705SXin Li           type->isBooleanType()) {
3447*67e74705SXin Li         CK = CK_IntegralToBoolean;
3448*67e74705SXin Li       } else if (type->isObjCObjectPointerType()) {
3449*67e74705SXin Li         if (SubExpr->getType()->isBlockPointerType()) {
3450*67e74705SXin Li           CK = CK_BlockPointerToObjCPointerCast;
3451*67e74705SXin Li         } else if (SubExpr->getType()->isPointerType()) {
3452*67e74705SXin Li           CK = CK_CPointerToObjCPointerCast;
3453*67e74705SXin Li         } else {
3454*67e74705SXin Li           CK = CK_BitCast;
3455*67e74705SXin Li         }
3456*67e74705SXin Li       } else {
3457*67e74705SXin Li         CK = CK_BitCast;
3458*67e74705SXin Li       }
3459*67e74705SXin Li 
3460*67e74705SXin Li       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3461*67e74705SXin Li     }
3462*67e74705SXin Li     // Make id<P...> cast into an 'id' cast.
3463*67e74705SXin Li     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3464*67e74705SXin Li       if (CE->getType()->isObjCQualifiedIdType()) {
3465*67e74705SXin Li         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3466*67e74705SXin Li           userExpr = CE->getSubExpr();
3467*67e74705SXin Li         CastKind CK;
3468*67e74705SXin Li         if (userExpr->getType()->isIntegralType(*Context)) {
3469*67e74705SXin Li           CK = CK_IntegralToPointer;
3470*67e74705SXin Li         } else if (userExpr->getType()->isBlockPointerType()) {
3471*67e74705SXin Li           CK = CK_BlockPointerToObjCPointerCast;
3472*67e74705SXin Li         } else if (userExpr->getType()->isPointerType()) {
3473*67e74705SXin Li           CK = CK_CPointerToObjCPointerCast;
3474*67e74705SXin Li         } else {
3475*67e74705SXin Li           CK = CK_BitCast;
3476*67e74705SXin Li         }
3477*67e74705SXin Li         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3478*67e74705SXin Li                                             CK, userExpr);
3479*67e74705SXin Li       }
3480*67e74705SXin Li     }
3481*67e74705SXin Li     MsgExprs.push_back(userExpr);
3482*67e74705SXin Li     // We've transferred the ownership to MsgExprs. For now, we *don't* null
3483*67e74705SXin Li     // out the argument in the original expression (since we aren't deleting
3484*67e74705SXin Li     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3485*67e74705SXin Li     //Exp->setArg(i, 0);
3486*67e74705SXin Li   }
3487*67e74705SXin Li   // Generate the funky cast.
3488*67e74705SXin Li   CastExpr *cast;
3489*67e74705SXin Li   SmallVector<QualType, 8> ArgTypes;
3490*67e74705SXin Li   QualType returnType;
3491*67e74705SXin Li 
3492*67e74705SXin Li   // Push 'id' and 'SEL', the 2 implicit arguments.
3493*67e74705SXin Li   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3494*67e74705SXin Li     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3495*67e74705SXin Li   else
3496*67e74705SXin Li     ArgTypes.push_back(Context->getObjCIdType());
3497*67e74705SXin Li   ArgTypes.push_back(Context->getObjCSelType());
3498*67e74705SXin Li   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3499*67e74705SXin Li     // Push any user argument types.
3500*67e74705SXin Li     for (const auto *PI : OMD->parameters()) {
3501*67e74705SXin Li       QualType t = PI->getType()->isObjCQualifiedIdType()
3502*67e74705SXin Li                      ? Context->getObjCIdType()
3503*67e74705SXin Li                      : PI->getType();
3504*67e74705SXin Li       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3505*67e74705SXin Li       (void)convertBlockPointerToFunctionPointer(t);
3506*67e74705SXin Li       ArgTypes.push_back(t);
3507*67e74705SXin Li     }
3508*67e74705SXin Li     returnType = Exp->getType();
3509*67e74705SXin Li     convertToUnqualifiedObjCType(returnType);
3510*67e74705SXin Li     (void)convertBlockPointerToFunctionPointer(returnType);
3511*67e74705SXin Li   } else {
3512*67e74705SXin Li     returnType = Context->getObjCIdType();
3513*67e74705SXin Li   }
3514*67e74705SXin Li   // Get the type, we will need to reference it in a couple spots.
3515*67e74705SXin Li   QualType msgSendType = MsgSendFlavor->getType();
3516*67e74705SXin Li 
3517*67e74705SXin Li   // Create a reference to the objc_msgSend() declaration.
3518*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3519*67e74705SXin Li                                                VK_LValue, SourceLocation());
3520*67e74705SXin Li 
3521*67e74705SXin Li   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3522*67e74705SXin Li   // If we don't do this cast, we get the following bizarre warning/note:
3523*67e74705SXin Li   // xx.m:13: warning: function called through a non-compatible type
3524*67e74705SXin Li   // xx.m:13: note: if this code is reached, the program will abort
3525*67e74705SXin Li   cast = NoTypeInfoCStyleCastExpr(Context,
3526*67e74705SXin Li                                   Context->getPointerType(Context->VoidTy),
3527*67e74705SXin Li                                   CK_BitCast, DRE);
3528*67e74705SXin Li 
3529*67e74705SXin Li   // Now do the "normal" pointer to function cast.
3530*67e74705SXin Li   // If we don't have a method decl, force a variadic cast.
3531*67e74705SXin Li   const ObjCMethodDecl *MD = Exp->getMethodDecl();
3532*67e74705SXin Li   QualType castType =
3533*67e74705SXin Li     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3534*67e74705SXin Li   castType = Context->getPointerType(castType);
3535*67e74705SXin Li   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3536*67e74705SXin Li                                   cast);
3537*67e74705SXin Li 
3538*67e74705SXin Li   // Don't forget the parens to enforce the proper binding.
3539*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3540*67e74705SXin Li 
3541*67e74705SXin Li   const FunctionType *FT = msgSendType->getAs<FunctionType>();
3542*67e74705SXin Li   CallExpr *CE = new (Context)
3543*67e74705SXin Li       CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3544*67e74705SXin Li   Stmt *ReplacingStmt = CE;
3545*67e74705SXin Li   if (MsgSendStretFlavor) {
3546*67e74705SXin Li     // We have the method which returns a struct/union. Must also generate
3547*67e74705SXin Li     // call to objc_msgSend_stret and hang both varieties on a conditional
3548*67e74705SXin Li     // expression which dictate which one to envoke depending on size of
3549*67e74705SXin Li     // method's return type.
3550*67e74705SXin Li 
3551*67e74705SXin Li     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3552*67e74705SXin Li                                            returnType,
3553*67e74705SXin Li                                            ArgTypes, MsgExprs,
3554*67e74705SXin Li                                            Exp->getMethodDecl());
3555*67e74705SXin Li     ReplacingStmt = STCE;
3556*67e74705SXin Li   }
3557*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3558*67e74705SXin Li   return ReplacingStmt;
3559*67e74705SXin Li }
3560*67e74705SXin Li 
RewriteMessageExpr(ObjCMessageExpr * Exp)3561*67e74705SXin Li Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3562*67e74705SXin Li   Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3563*67e74705SXin Li                                          Exp->getLocEnd());
3564*67e74705SXin Li 
3565*67e74705SXin Li   // Now do the actual rewrite.
3566*67e74705SXin Li   ReplaceStmt(Exp, ReplacingStmt);
3567*67e74705SXin Li 
3568*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3569*67e74705SXin Li   return ReplacingStmt;
3570*67e74705SXin Li }
3571*67e74705SXin Li 
3572*67e74705SXin Li // typedef struct objc_object Protocol;
getProtocolType()3573*67e74705SXin Li QualType RewriteModernObjC::getProtocolType() {
3574*67e74705SXin Li   if (!ProtocolTypeDecl) {
3575*67e74705SXin Li     TypeSourceInfo *TInfo
3576*67e74705SXin Li       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3577*67e74705SXin Li     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3578*67e74705SXin Li                                            SourceLocation(), SourceLocation(),
3579*67e74705SXin Li                                            &Context->Idents.get("Protocol"),
3580*67e74705SXin Li                                            TInfo);
3581*67e74705SXin Li   }
3582*67e74705SXin Li   return Context->getTypeDeclType(ProtocolTypeDecl);
3583*67e74705SXin Li }
3584*67e74705SXin Li 
3585*67e74705SXin Li /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3586*67e74705SXin Li /// a synthesized/forward data reference (to the protocol's metadata).
3587*67e74705SXin Li /// The forward references (and metadata) are generated in
3588*67e74705SXin Li /// RewriteModernObjC::HandleTranslationUnit().
RewriteObjCProtocolExpr(ObjCProtocolExpr * Exp)3589*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3590*67e74705SXin Li   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3591*67e74705SXin Li                       Exp->getProtocol()->getNameAsString();
3592*67e74705SXin Li   IdentifierInfo *ID = &Context->Idents.get(Name);
3593*67e74705SXin Li   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3594*67e74705SXin Li                                 SourceLocation(), ID, getProtocolType(),
3595*67e74705SXin Li                                 nullptr, SC_Extern);
3596*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3597*67e74705SXin Li                                                VK_LValue, SourceLocation());
3598*67e74705SXin Li   CastExpr *castExpr =
3599*67e74705SXin Li     NoTypeInfoCStyleCastExpr(
3600*67e74705SXin Li       Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3601*67e74705SXin Li   ReplaceStmt(Exp, castExpr);
3602*67e74705SXin Li   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3603*67e74705SXin Li   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3604*67e74705SXin Li   return castExpr;
3605*67e74705SXin Li }
3606*67e74705SXin Li 
3607*67e74705SXin Li /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3608*67e74705SXin Li /// is defined inside an objective-c class. If so, it returns true.
IsTagDefinedInsideClass(ObjCContainerDecl * IDecl,TagDecl * Tag,bool & IsNamedDefinition)3609*67e74705SXin Li bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3610*67e74705SXin Li                                                 TagDecl *Tag,
3611*67e74705SXin Li                                                 bool &IsNamedDefinition) {
3612*67e74705SXin Li   if (!IDecl)
3613*67e74705SXin Li     return false;
3614*67e74705SXin Li   SourceLocation TagLocation;
3615*67e74705SXin Li   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3616*67e74705SXin Li     RD = RD->getDefinition();
3617*67e74705SXin Li     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3618*67e74705SXin Li       return false;
3619*67e74705SXin Li     IsNamedDefinition = true;
3620*67e74705SXin Li     TagLocation = RD->getLocation();
3621*67e74705SXin Li     return Context->getSourceManager().isBeforeInTranslationUnit(
3622*67e74705SXin Li                                           IDecl->getLocation(), TagLocation);
3623*67e74705SXin Li   }
3624*67e74705SXin Li   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3625*67e74705SXin Li     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3626*67e74705SXin Li       return false;
3627*67e74705SXin Li     IsNamedDefinition = true;
3628*67e74705SXin Li     TagLocation = ED->getLocation();
3629*67e74705SXin Li     return Context->getSourceManager().isBeforeInTranslationUnit(
3630*67e74705SXin Li                                           IDecl->getLocation(), TagLocation);
3631*67e74705SXin Li   }
3632*67e74705SXin Li   return false;
3633*67e74705SXin Li }
3634*67e74705SXin Li 
3635*67e74705SXin Li /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3636*67e74705SXin Li /// It handles elaborated types, as well as enum types in the process.
RewriteObjCFieldDeclType(QualType & Type,std::string & Result)3637*67e74705SXin Li bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3638*67e74705SXin Li                                                  std::string &Result) {
3639*67e74705SXin Li   if (isa<TypedefType>(Type)) {
3640*67e74705SXin Li     Result += "\t";
3641*67e74705SXin Li     return false;
3642*67e74705SXin Li   }
3643*67e74705SXin Li 
3644*67e74705SXin Li   if (Type->isArrayType()) {
3645*67e74705SXin Li     QualType ElemTy = Context->getBaseElementType(Type);
3646*67e74705SXin Li     return RewriteObjCFieldDeclType(ElemTy, Result);
3647*67e74705SXin Li   }
3648*67e74705SXin Li   else if (Type->isRecordType()) {
3649*67e74705SXin Li     RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3650*67e74705SXin Li     if (RD->isCompleteDefinition()) {
3651*67e74705SXin Li       if (RD->isStruct())
3652*67e74705SXin Li         Result += "\n\tstruct ";
3653*67e74705SXin Li       else if (RD->isUnion())
3654*67e74705SXin Li         Result += "\n\tunion ";
3655*67e74705SXin Li       else
3656*67e74705SXin Li         assert(false && "class not allowed as an ivar type");
3657*67e74705SXin Li 
3658*67e74705SXin Li       Result += RD->getName();
3659*67e74705SXin Li       if (GlobalDefinedTags.count(RD)) {
3660*67e74705SXin Li         // struct/union is defined globally, use it.
3661*67e74705SXin Li         Result += " ";
3662*67e74705SXin Li         return true;
3663*67e74705SXin Li       }
3664*67e74705SXin Li       Result += " {\n";
3665*67e74705SXin Li       for (auto *FD : RD->fields())
3666*67e74705SXin Li         RewriteObjCFieldDecl(FD, Result);
3667*67e74705SXin Li       Result += "\t} ";
3668*67e74705SXin Li       return true;
3669*67e74705SXin Li     }
3670*67e74705SXin Li   }
3671*67e74705SXin Li   else if (Type->isEnumeralType()) {
3672*67e74705SXin Li     EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3673*67e74705SXin Li     if (ED->isCompleteDefinition()) {
3674*67e74705SXin Li       Result += "\n\tenum ";
3675*67e74705SXin Li       Result += ED->getName();
3676*67e74705SXin Li       if (GlobalDefinedTags.count(ED)) {
3677*67e74705SXin Li         // Enum is globall defined, use it.
3678*67e74705SXin Li         Result += " ";
3679*67e74705SXin Li         return true;
3680*67e74705SXin Li       }
3681*67e74705SXin Li 
3682*67e74705SXin Li       Result += " {\n";
3683*67e74705SXin Li       for (const auto *EC : ED->enumerators()) {
3684*67e74705SXin Li         Result += "\t"; Result += EC->getName(); Result += " = ";
3685*67e74705SXin Li         llvm::APSInt Val = EC->getInitVal();
3686*67e74705SXin Li         Result += Val.toString(10);
3687*67e74705SXin Li         Result += ",\n";
3688*67e74705SXin Li       }
3689*67e74705SXin Li       Result += "\t} ";
3690*67e74705SXin Li       return true;
3691*67e74705SXin Li     }
3692*67e74705SXin Li   }
3693*67e74705SXin Li 
3694*67e74705SXin Li   Result += "\t";
3695*67e74705SXin Li   convertObjCTypeToCStyleType(Type);
3696*67e74705SXin Li   return false;
3697*67e74705SXin Li }
3698*67e74705SXin Li 
3699*67e74705SXin Li 
3700*67e74705SXin Li /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3701*67e74705SXin Li /// It handles elaborated types, as well as enum types in the process.
RewriteObjCFieldDecl(FieldDecl * fieldDecl,std::string & Result)3702*67e74705SXin Li void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3703*67e74705SXin Li                                              std::string &Result) {
3704*67e74705SXin Li   QualType Type = fieldDecl->getType();
3705*67e74705SXin Li   std::string Name = fieldDecl->getNameAsString();
3706*67e74705SXin Li 
3707*67e74705SXin Li   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3708*67e74705SXin Li   if (!EleboratedType)
3709*67e74705SXin Li     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3710*67e74705SXin Li   Result += Name;
3711*67e74705SXin Li   if (fieldDecl->isBitField()) {
3712*67e74705SXin Li     Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3713*67e74705SXin Li   }
3714*67e74705SXin Li   else if (EleboratedType && Type->isArrayType()) {
3715*67e74705SXin Li     const ArrayType *AT = Context->getAsArrayType(Type);
3716*67e74705SXin Li     do {
3717*67e74705SXin Li       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3718*67e74705SXin Li         Result += "[";
3719*67e74705SXin Li         llvm::APInt Dim = CAT->getSize();
3720*67e74705SXin Li         Result += utostr(Dim.getZExtValue());
3721*67e74705SXin Li         Result += "]";
3722*67e74705SXin Li       }
3723*67e74705SXin Li       AT = Context->getAsArrayType(AT->getElementType());
3724*67e74705SXin Li     } while (AT);
3725*67e74705SXin Li   }
3726*67e74705SXin Li 
3727*67e74705SXin Li   Result += ";\n";
3728*67e74705SXin Li }
3729*67e74705SXin Li 
3730*67e74705SXin Li /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3731*67e74705SXin Li /// named aggregate types into the input buffer.
RewriteLocallyDefinedNamedAggregates(FieldDecl * fieldDecl,std::string & Result)3732*67e74705SXin Li void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3733*67e74705SXin Li                                              std::string &Result) {
3734*67e74705SXin Li   QualType Type = fieldDecl->getType();
3735*67e74705SXin Li   if (isa<TypedefType>(Type))
3736*67e74705SXin Li     return;
3737*67e74705SXin Li   if (Type->isArrayType())
3738*67e74705SXin Li     Type = Context->getBaseElementType(Type);
3739*67e74705SXin Li   ObjCContainerDecl *IDecl =
3740*67e74705SXin Li     dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3741*67e74705SXin Li 
3742*67e74705SXin Li   TagDecl *TD = nullptr;
3743*67e74705SXin Li   if (Type->isRecordType()) {
3744*67e74705SXin Li     TD = Type->getAs<RecordType>()->getDecl();
3745*67e74705SXin Li   }
3746*67e74705SXin Li   else if (Type->isEnumeralType()) {
3747*67e74705SXin Li     TD = Type->getAs<EnumType>()->getDecl();
3748*67e74705SXin Li   }
3749*67e74705SXin Li 
3750*67e74705SXin Li   if (TD) {
3751*67e74705SXin Li     if (GlobalDefinedTags.count(TD))
3752*67e74705SXin Li       return;
3753*67e74705SXin Li 
3754*67e74705SXin Li     bool IsNamedDefinition = false;
3755*67e74705SXin Li     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3756*67e74705SXin Li       RewriteObjCFieldDeclType(Type, Result);
3757*67e74705SXin Li       Result += ";";
3758*67e74705SXin Li     }
3759*67e74705SXin Li     if (IsNamedDefinition)
3760*67e74705SXin Li       GlobalDefinedTags.insert(TD);
3761*67e74705SXin Li   }
3762*67e74705SXin Li }
3763*67e74705SXin Li 
ObjCIvarBitfieldGroupNo(ObjCIvarDecl * IV)3764*67e74705SXin Li unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3765*67e74705SXin Li   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3766*67e74705SXin Li   if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3767*67e74705SXin Li     return IvarGroupNumber[IV];
3768*67e74705SXin Li   }
3769*67e74705SXin Li   unsigned GroupNo = 0;
3770*67e74705SXin Li   SmallVector<const ObjCIvarDecl *, 8> IVars;
3771*67e74705SXin Li   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3772*67e74705SXin Li        IVD; IVD = IVD->getNextIvar())
3773*67e74705SXin Li     IVars.push_back(IVD);
3774*67e74705SXin Li 
3775*67e74705SXin Li   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3776*67e74705SXin Li     if (IVars[i]->isBitField()) {
3777*67e74705SXin Li       IvarGroupNumber[IVars[i++]] = ++GroupNo;
3778*67e74705SXin Li       while (i < e && IVars[i]->isBitField())
3779*67e74705SXin Li         IvarGroupNumber[IVars[i++]] = GroupNo;
3780*67e74705SXin Li       if (i < e)
3781*67e74705SXin Li         --i;
3782*67e74705SXin Li     }
3783*67e74705SXin Li 
3784*67e74705SXin Li   ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3785*67e74705SXin Li   return IvarGroupNumber[IV];
3786*67e74705SXin Li }
3787*67e74705SXin Li 
SynthesizeBitfieldGroupStructType(ObjCIvarDecl * IV,SmallVectorImpl<ObjCIvarDecl * > & IVars)3788*67e74705SXin Li QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3789*67e74705SXin Li                               ObjCIvarDecl *IV,
3790*67e74705SXin Li                               SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3791*67e74705SXin Li   std::string StructTagName;
3792*67e74705SXin Li   ObjCIvarBitfieldGroupType(IV, StructTagName);
3793*67e74705SXin Li   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3794*67e74705SXin Li                                       Context->getTranslationUnitDecl(),
3795*67e74705SXin Li                                       SourceLocation(), SourceLocation(),
3796*67e74705SXin Li                                       &Context->Idents.get(StructTagName));
3797*67e74705SXin Li   for (unsigned i=0, e = IVars.size(); i < e; i++) {
3798*67e74705SXin Li     ObjCIvarDecl *Ivar = IVars[i];
3799*67e74705SXin Li     RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3800*67e74705SXin Li                                   &Context->Idents.get(Ivar->getName()),
3801*67e74705SXin Li                                   Ivar->getType(),
3802*67e74705SXin Li                                   nullptr, /*Expr *BW */Ivar->getBitWidth(),
3803*67e74705SXin Li                                   false, ICIS_NoInit));
3804*67e74705SXin Li   }
3805*67e74705SXin Li   RD->completeDefinition();
3806*67e74705SXin Li   return Context->getTagDeclType(RD);
3807*67e74705SXin Li }
3808*67e74705SXin Li 
GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * IV)3809*67e74705SXin Li QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3810*67e74705SXin Li   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3811*67e74705SXin Li   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3812*67e74705SXin Li   std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3813*67e74705SXin Li   if (GroupRecordType.count(tuple))
3814*67e74705SXin Li     return GroupRecordType[tuple];
3815*67e74705SXin Li 
3816*67e74705SXin Li   SmallVector<ObjCIvarDecl *, 8> IVars;
3817*67e74705SXin Li   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3818*67e74705SXin Li        IVD; IVD = IVD->getNextIvar()) {
3819*67e74705SXin Li     if (IVD->isBitField())
3820*67e74705SXin Li       IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3821*67e74705SXin Li     else {
3822*67e74705SXin Li       if (!IVars.empty()) {
3823*67e74705SXin Li         unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3824*67e74705SXin Li         // Generate the struct type for this group of bitfield ivars.
3825*67e74705SXin Li         GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3826*67e74705SXin Li           SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3827*67e74705SXin Li         IVars.clear();
3828*67e74705SXin Li       }
3829*67e74705SXin Li     }
3830*67e74705SXin Li   }
3831*67e74705SXin Li   if (!IVars.empty()) {
3832*67e74705SXin Li     // Do the last one.
3833*67e74705SXin Li     unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3834*67e74705SXin Li     GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3835*67e74705SXin Li       SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3836*67e74705SXin Li   }
3837*67e74705SXin Li   QualType RetQT = GroupRecordType[tuple];
3838*67e74705SXin Li   assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3839*67e74705SXin Li 
3840*67e74705SXin Li   return RetQT;
3841*67e74705SXin Li }
3842*67e74705SXin Li 
3843*67e74705SXin Li /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3844*67e74705SXin Li /// Name would be: classname__GRBF_n where n is the group number for this ivar.
ObjCIvarBitfieldGroupDecl(ObjCIvarDecl * IV,std::string & Result)3845*67e74705SXin Li void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3846*67e74705SXin Li                                                   std::string &Result) {
3847*67e74705SXin Li   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3848*67e74705SXin Li   Result += CDecl->getName();
3849*67e74705SXin Li   Result += "__GRBF_";
3850*67e74705SXin Li   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3851*67e74705SXin Li   Result += utostr(GroupNo);
3852*67e74705SXin Li }
3853*67e74705SXin Li 
3854*67e74705SXin Li /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3855*67e74705SXin Li /// Name of the struct would be: classname__T_n where n is the group number for
3856*67e74705SXin Li /// this ivar.
ObjCIvarBitfieldGroupType(ObjCIvarDecl * IV,std::string & Result)3857*67e74705SXin Li void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3858*67e74705SXin Li                                                   std::string &Result) {
3859*67e74705SXin Li   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3860*67e74705SXin Li   Result += CDecl->getName();
3861*67e74705SXin Li   Result += "__T_";
3862*67e74705SXin Li   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3863*67e74705SXin Li   Result += utostr(GroupNo);
3864*67e74705SXin Li }
3865*67e74705SXin Li 
3866*67e74705SXin Li /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3867*67e74705SXin Li /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3868*67e74705SXin Li /// this ivar.
ObjCIvarBitfieldGroupOffset(ObjCIvarDecl * IV,std::string & Result)3869*67e74705SXin Li void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3870*67e74705SXin Li                                                     std::string &Result) {
3871*67e74705SXin Li   Result += "OBJC_IVAR_$_";
3872*67e74705SXin Li   ObjCIvarBitfieldGroupDecl(IV, Result);
3873*67e74705SXin Li }
3874*67e74705SXin Li 
3875*67e74705SXin Li #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3876*67e74705SXin Li       while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3877*67e74705SXin Li         ++IX; \
3878*67e74705SXin Li       if (IX < ENDIX) \
3879*67e74705SXin Li         --IX; \
3880*67e74705SXin Li }
3881*67e74705SXin Li 
3882*67e74705SXin Li /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3883*67e74705SXin Li /// an objective-c class with ivars.
RewriteObjCInternalStruct(ObjCInterfaceDecl * CDecl,std::string & Result)3884*67e74705SXin Li void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3885*67e74705SXin Li                                                std::string &Result) {
3886*67e74705SXin Li   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3887*67e74705SXin Li   assert(CDecl->getName() != "" &&
3888*67e74705SXin Li          "Name missing in SynthesizeObjCInternalStruct");
3889*67e74705SXin Li   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3890*67e74705SXin Li   SmallVector<ObjCIvarDecl *, 8> IVars;
3891*67e74705SXin Li   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3892*67e74705SXin Li        IVD; IVD = IVD->getNextIvar())
3893*67e74705SXin Li     IVars.push_back(IVD);
3894*67e74705SXin Li 
3895*67e74705SXin Li   SourceLocation LocStart = CDecl->getLocStart();
3896*67e74705SXin Li   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3897*67e74705SXin Li 
3898*67e74705SXin Li   const char *startBuf = SM->getCharacterData(LocStart);
3899*67e74705SXin Li   const char *endBuf = SM->getCharacterData(LocEnd);
3900*67e74705SXin Li 
3901*67e74705SXin Li   // If no ivars and no root or if its root, directly or indirectly,
3902*67e74705SXin Li   // have no ivars (thus not synthesized) then no need to synthesize this class.
3903*67e74705SXin Li   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3904*67e74705SXin Li       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3905*67e74705SXin Li     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3906*67e74705SXin Li     ReplaceText(LocStart, endBuf-startBuf, Result);
3907*67e74705SXin Li     return;
3908*67e74705SXin Li   }
3909*67e74705SXin Li 
3910*67e74705SXin Li   // Insert named struct/union definitions inside class to
3911*67e74705SXin Li   // outer scope. This follows semantics of locally defined
3912*67e74705SXin Li   // struct/unions in objective-c classes.
3913*67e74705SXin Li   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3914*67e74705SXin Li     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3915*67e74705SXin Li 
3916*67e74705SXin Li   // Insert named structs which are syntheized to group ivar bitfields
3917*67e74705SXin Li   // to outer scope as well.
3918*67e74705SXin Li   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3919*67e74705SXin Li     if (IVars[i]->isBitField()) {
3920*67e74705SXin Li       ObjCIvarDecl *IV = IVars[i];
3921*67e74705SXin Li       QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3922*67e74705SXin Li       RewriteObjCFieldDeclType(QT, Result);
3923*67e74705SXin Li       Result += ";";
3924*67e74705SXin Li       // skip over ivar bitfields in this group.
3925*67e74705SXin Li       SKIP_BITFIELDS(i , e, IVars);
3926*67e74705SXin Li     }
3927*67e74705SXin Li 
3928*67e74705SXin Li   Result += "\nstruct ";
3929*67e74705SXin Li   Result += CDecl->getNameAsString();
3930*67e74705SXin Li   Result += "_IMPL {\n";
3931*67e74705SXin Li 
3932*67e74705SXin Li   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3933*67e74705SXin Li     Result += "\tstruct "; Result += RCDecl->getNameAsString();
3934*67e74705SXin Li     Result += "_IMPL "; Result += RCDecl->getNameAsString();
3935*67e74705SXin Li     Result += "_IVARS;\n";
3936*67e74705SXin Li   }
3937*67e74705SXin Li 
3938*67e74705SXin Li   for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3939*67e74705SXin Li     if (IVars[i]->isBitField()) {
3940*67e74705SXin Li       ObjCIvarDecl *IV = IVars[i];
3941*67e74705SXin Li       Result += "\tstruct ";
3942*67e74705SXin Li       ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3943*67e74705SXin Li       ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3944*67e74705SXin Li       // skip over ivar bitfields in this group.
3945*67e74705SXin Li       SKIP_BITFIELDS(i , e, IVars);
3946*67e74705SXin Li     }
3947*67e74705SXin Li     else
3948*67e74705SXin Li       RewriteObjCFieldDecl(IVars[i], Result);
3949*67e74705SXin Li   }
3950*67e74705SXin Li 
3951*67e74705SXin Li   Result += "};\n";
3952*67e74705SXin Li   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3953*67e74705SXin Li   ReplaceText(LocStart, endBuf-startBuf, Result);
3954*67e74705SXin Li   // Mark this struct as having been generated.
3955*67e74705SXin Li   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3956*67e74705SXin Li     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3957*67e74705SXin Li }
3958*67e74705SXin Li 
3959*67e74705SXin Li /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3960*67e74705SXin Li /// have been referenced in an ivar access expression.
RewriteIvarOffsetSymbols(ObjCInterfaceDecl * CDecl,std::string & Result)3961*67e74705SXin Li void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3962*67e74705SXin Li                                                   std::string &Result) {
3963*67e74705SXin Li   // write out ivar offset symbols which have been referenced in an ivar
3964*67e74705SXin Li   // access expression.
3965*67e74705SXin Li   llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3966*67e74705SXin Li   if (Ivars.empty())
3967*67e74705SXin Li     return;
3968*67e74705SXin Li 
3969*67e74705SXin Li   llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3970*67e74705SXin Li   for (ObjCIvarDecl *IvarDecl : Ivars) {
3971*67e74705SXin Li     const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3972*67e74705SXin Li     unsigned GroupNo = 0;
3973*67e74705SXin Li     if (IvarDecl->isBitField()) {
3974*67e74705SXin Li       GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3975*67e74705SXin Li       if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3976*67e74705SXin Li         continue;
3977*67e74705SXin Li     }
3978*67e74705SXin Li     Result += "\n";
3979*67e74705SXin Li     if (LangOpts.MicrosoftExt)
3980*67e74705SXin Li       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3981*67e74705SXin Li     Result += "extern \"C\" ";
3982*67e74705SXin Li     if (LangOpts.MicrosoftExt &&
3983*67e74705SXin Li         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3984*67e74705SXin Li         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3985*67e74705SXin Li         Result += "__declspec(dllimport) ";
3986*67e74705SXin Li 
3987*67e74705SXin Li     Result += "unsigned long ";
3988*67e74705SXin Li     if (IvarDecl->isBitField()) {
3989*67e74705SXin Li       ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3990*67e74705SXin Li       GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3991*67e74705SXin Li     }
3992*67e74705SXin Li     else
3993*67e74705SXin Li       WriteInternalIvarName(CDecl, IvarDecl, Result);
3994*67e74705SXin Li     Result += ";";
3995*67e74705SXin Li   }
3996*67e74705SXin Li }
3997*67e74705SXin Li 
3998*67e74705SXin Li //===----------------------------------------------------------------------===//
3999*67e74705SXin Li // Meta Data Emission
4000*67e74705SXin Li //===----------------------------------------------------------------------===//
4001*67e74705SXin Li 
4002*67e74705SXin Li /// RewriteImplementations - This routine rewrites all method implementations
4003*67e74705SXin Li /// and emits meta-data.
4004*67e74705SXin Li 
RewriteImplementations()4005*67e74705SXin Li void RewriteModernObjC::RewriteImplementations() {
4006*67e74705SXin Li   int ClsDefCount = ClassImplementation.size();
4007*67e74705SXin Li   int CatDefCount = CategoryImplementation.size();
4008*67e74705SXin Li 
4009*67e74705SXin Li   // Rewrite implemented methods
4010*67e74705SXin Li   for (int i = 0; i < ClsDefCount; i++) {
4011*67e74705SXin Li     ObjCImplementationDecl *OIMP = ClassImplementation[i];
4012*67e74705SXin Li     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4013*67e74705SXin Li     if (CDecl->isImplicitInterfaceDecl())
4014*67e74705SXin Li       assert(false &&
4015*67e74705SXin Li              "Legacy implicit interface rewriting not supported in moder abi");
4016*67e74705SXin Li     RewriteImplementationDecl(OIMP);
4017*67e74705SXin Li   }
4018*67e74705SXin Li 
4019*67e74705SXin Li   for (int i = 0; i < CatDefCount; i++) {
4020*67e74705SXin Li     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4021*67e74705SXin Li     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4022*67e74705SXin Li     if (CDecl->isImplicitInterfaceDecl())
4023*67e74705SXin Li       assert(false &&
4024*67e74705SXin Li              "Legacy implicit interface rewriting not supported in moder abi");
4025*67e74705SXin Li     RewriteImplementationDecl(CIMP);
4026*67e74705SXin Li   }
4027*67e74705SXin Li }
4028*67e74705SXin Li 
RewriteByRefString(std::string & ResultStr,const std::string & Name,ValueDecl * VD,bool def)4029*67e74705SXin Li void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4030*67e74705SXin Li                                      const std::string &Name,
4031*67e74705SXin Li                                      ValueDecl *VD, bool def) {
4032*67e74705SXin Li   assert(BlockByRefDeclNo.count(VD) &&
4033*67e74705SXin Li          "RewriteByRefString: ByRef decl missing");
4034*67e74705SXin Li   if (def)
4035*67e74705SXin Li     ResultStr += "struct ";
4036*67e74705SXin Li   ResultStr += "__Block_byref_" + Name +
4037*67e74705SXin Li     "_" + utostr(BlockByRefDeclNo[VD]) ;
4038*67e74705SXin Li }
4039*67e74705SXin Li 
HasLocalVariableExternalStorage(ValueDecl * VD)4040*67e74705SXin Li static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4041*67e74705SXin Li   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4042*67e74705SXin Li     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4043*67e74705SXin Li   return false;
4044*67e74705SXin Li }
4045*67e74705SXin Li 
SynthesizeBlockFunc(BlockExpr * CE,int i,StringRef funcName,std::string Tag)4046*67e74705SXin Li std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4047*67e74705SXin Li                                                    StringRef funcName,
4048*67e74705SXin Li                                                    std::string Tag) {
4049*67e74705SXin Li   const FunctionType *AFT = CE->getFunctionType();
4050*67e74705SXin Li   QualType RT = AFT->getReturnType();
4051*67e74705SXin Li   std::string StructRef = "struct " + Tag;
4052*67e74705SXin Li   SourceLocation BlockLoc = CE->getExprLoc();
4053*67e74705SXin Li   std::string S;
4054*67e74705SXin Li   ConvertSourceLocationToLineDirective(BlockLoc, S);
4055*67e74705SXin Li 
4056*67e74705SXin Li   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4057*67e74705SXin Li          funcName.str() + "_block_func_" + utostr(i);
4058*67e74705SXin Li 
4059*67e74705SXin Li   BlockDecl *BD = CE->getBlockDecl();
4060*67e74705SXin Li 
4061*67e74705SXin Li   if (isa<FunctionNoProtoType>(AFT)) {
4062*67e74705SXin Li     // No user-supplied arguments. Still need to pass in a pointer to the
4063*67e74705SXin Li     // block (to reference imported block decl refs).
4064*67e74705SXin Li     S += "(" + StructRef + " *__cself)";
4065*67e74705SXin Li   } else if (BD->param_empty()) {
4066*67e74705SXin Li     S += "(" + StructRef + " *__cself)";
4067*67e74705SXin Li   } else {
4068*67e74705SXin Li     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4069*67e74705SXin Li     assert(FT && "SynthesizeBlockFunc: No function proto");
4070*67e74705SXin Li     S += '(';
4071*67e74705SXin Li     // first add the implicit argument.
4072*67e74705SXin Li     S += StructRef + " *__cself, ";
4073*67e74705SXin Li     std::string ParamStr;
4074*67e74705SXin Li     for (BlockDecl::param_iterator AI = BD->param_begin(),
4075*67e74705SXin Li          E = BD->param_end(); AI != E; ++AI) {
4076*67e74705SXin Li       if (AI != BD->param_begin()) S += ", ";
4077*67e74705SXin Li       ParamStr = (*AI)->getNameAsString();
4078*67e74705SXin Li       QualType QT = (*AI)->getType();
4079*67e74705SXin Li       (void)convertBlockPointerToFunctionPointer(QT);
4080*67e74705SXin Li       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4081*67e74705SXin Li       S += ParamStr;
4082*67e74705SXin Li     }
4083*67e74705SXin Li     if (FT->isVariadic()) {
4084*67e74705SXin Li       if (!BD->param_empty()) S += ", ";
4085*67e74705SXin Li       S += "...";
4086*67e74705SXin Li     }
4087*67e74705SXin Li     S += ')';
4088*67e74705SXin Li   }
4089*67e74705SXin Li   S += " {\n";
4090*67e74705SXin Li 
4091*67e74705SXin Li   // Create local declarations to avoid rewriting all closure decl ref exprs.
4092*67e74705SXin Li   // First, emit a declaration for all "by ref" decls.
4093*67e74705SXin Li   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4094*67e74705SXin Li        E = BlockByRefDecls.end(); I != E; ++I) {
4095*67e74705SXin Li     S += "  ";
4096*67e74705SXin Li     std::string Name = (*I)->getNameAsString();
4097*67e74705SXin Li     std::string TypeString;
4098*67e74705SXin Li     RewriteByRefString(TypeString, Name, (*I));
4099*67e74705SXin Li     TypeString += " *";
4100*67e74705SXin Li     Name = TypeString + Name;
4101*67e74705SXin Li     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4102*67e74705SXin Li   }
4103*67e74705SXin Li   // Next, emit a declaration for all "by copy" declarations.
4104*67e74705SXin Li   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4105*67e74705SXin Li        E = BlockByCopyDecls.end(); I != E; ++I) {
4106*67e74705SXin Li     S += "  ";
4107*67e74705SXin Li     // Handle nested closure invocation. For example:
4108*67e74705SXin Li     //
4109*67e74705SXin Li     //   void (^myImportedClosure)(void);
4110*67e74705SXin Li     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4111*67e74705SXin Li     //
4112*67e74705SXin Li     //   void (^anotherClosure)(void);
4113*67e74705SXin Li     //   anotherClosure = ^(void) {
4114*67e74705SXin Li     //     myImportedClosure(); // import and invoke the closure
4115*67e74705SXin Li     //   };
4116*67e74705SXin Li     //
4117*67e74705SXin Li     if (isTopLevelBlockPointerType((*I)->getType())) {
4118*67e74705SXin Li       RewriteBlockPointerTypeVariable(S, (*I));
4119*67e74705SXin Li       S += " = (";
4120*67e74705SXin Li       RewriteBlockPointerType(S, (*I)->getType());
4121*67e74705SXin Li       S += ")";
4122*67e74705SXin Li       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4123*67e74705SXin Li     }
4124*67e74705SXin Li     else {
4125*67e74705SXin Li       std::string Name = (*I)->getNameAsString();
4126*67e74705SXin Li       QualType QT = (*I)->getType();
4127*67e74705SXin Li       if (HasLocalVariableExternalStorage(*I))
4128*67e74705SXin Li         QT = Context->getPointerType(QT);
4129*67e74705SXin Li       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4130*67e74705SXin Li       S += Name + " = __cself->" +
4131*67e74705SXin Li                               (*I)->getNameAsString() + "; // bound by copy\n";
4132*67e74705SXin Li     }
4133*67e74705SXin Li   }
4134*67e74705SXin Li   std::string RewrittenStr = RewrittenBlockExprs[CE];
4135*67e74705SXin Li   const char *cstr = RewrittenStr.c_str();
4136*67e74705SXin Li   while (*cstr++ != '{') ;
4137*67e74705SXin Li   S += cstr;
4138*67e74705SXin Li   S += "\n";
4139*67e74705SXin Li   return S;
4140*67e74705SXin Li }
4141*67e74705SXin Li 
SynthesizeBlockHelperFuncs(BlockExpr * CE,int i,StringRef funcName,std::string Tag)4142*67e74705SXin Li std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4143*67e74705SXin Li                                                    StringRef funcName,
4144*67e74705SXin Li                                                    std::string Tag) {
4145*67e74705SXin Li   std::string StructRef = "struct " + Tag;
4146*67e74705SXin Li   std::string S = "static void __";
4147*67e74705SXin Li 
4148*67e74705SXin Li   S += funcName;
4149*67e74705SXin Li   S += "_block_copy_" + utostr(i);
4150*67e74705SXin Li   S += "(" + StructRef;
4151*67e74705SXin Li   S += "*dst, " + StructRef;
4152*67e74705SXin Li   S += "*src) {";
4153*67e74705SXin Li   for (ValueDecl *VD : ImportedBlockDecls) {
4154*67e74705SXin Li     S += "_Block_object_assign((void*)&dst->";
4155*67e74705SXin Li     S += VD->getNameAsString();
4156*67e74705SXin Li     S += ", (void*)src->";
4157*67e74705SXin Li     S += VD->getNameAsString();
4158*67e74705SXin Li     if (BlockByRefDeclsPtrSet.count(VD))
4159*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4160*67e74705SXin Li     else if (VD->getType()->isBlockPointerType())
4161*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4162*67e74705SXin Li     else
4163*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4164*67e74705SXin Li   }
4165*67e74705SXin Li   S += "}\n";
4166*67e74705SXin Li 
4167*67e74705SXin Li   S += "\nstatic void __";
4168*67e74705SXin Li   S += funcName;
4169*67e74705SXin Li   S += "_block_dispose_" + utostr(i);
4170*67e74705SXin Li   S += "(" + StructRef;
4171*67e74705SXin Li   S += "*src) {";
4172*67e74705SXin Li   for (ValueDecl *VD : ImportedBlockDecls) {
4173*67e74705SXin Li     S += "_Block_object_dispose((void*)src->";
4174*67e74705SXin Li     S += VD->getNameAsString();
4175*67e74705SXin Li     if (BlockByRefDeclsPtrSet.count(VD))
4176*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4177*67e74705SXin Li     else if (VD->getType()->isBlockPointerType())
4178*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4179*67e74705SXin Li     else
4180*67e74705SXin Li       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4181*67e74705SXin Li   }
4182*67e74705SXin Li   S += "}\n";
4183*67e74705SXin Li   return S;
4184*67e74705SXin Li }
4185*67e74705SXin Li 
SynthesizeBlockImpl(BlockExpr * CE,std::string Tag,std::string Desc)4186*67e74705SXin Li std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4187*67e74705SXin Li                                              std::string Desc) {
4188*67e74705SXin Li   std::string S = "\nstruct " + Tag;
4189*67e74705SXin Li   std::string Constructor = "  " + Tag;
4190*67e74705SXin Li 
4191*67e74705SXin Li   S += " {\n  struct __block_impl impl;\n";
4192*67e74705SXin Li   S += "  struct " + Desc;
4193*67e74705SXin Li   S += "* Desc;\n";
4194*67e74705SXin Li 
4195*67e74705SXin Li   Constructor += "(void *fp, "; // Invoke function pointer.
4196*67e74705SXin Li   Constructor += "struct " + Desc; // Descriptor pointer.
4197*67e74705SXin Li   Constructor += " *desc";
4198*67e74705SXin Li 
4199*67e74705SXin Li   if (BlockDeclRefs.size()) {
4200*67e74705SXin Li     // Output all "by copy" declarations.
4201*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4202*67e74705SXin Li          E = BlockByCopyDecls.end(); I != E; ++I) {
4203*67e74705SXin Li       S += "  ";
4204*67e74705SXin Li       std::string FieldName = (*I)->getNameAsString();
4205*67e74705SXin Li       std::string ArgName = "_" + FieldName;
4206*67e74705SXin Li       // Handle nested closure invocation. For example:
4207*67e74705SXin Li       //
4208*67e74705SXin Li       //   void (^myImportedBlock)(void);
4209*67e74705SXin Li       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4210*67e74705SXin Li       //
4211*67e74705SXin Li       //   void (^anotherBlock)(void);
4212*67e74705SXin Li       //   anotherBlock = ^(void) {
4213*67e74705SXin Li       //     myImportedBlock(); // import and invoke the closure
4214*67e74705SXin Li       //   };
4215*67e74705SXin Li       //
4216*67e74705SXin Li       if (isTopLevelBlockPointerType((*I)->getType())) {
4217*67e74705SXin Li         S += "struct __block_impl *";
4218*67e74705SXin Li         Constructor += ", void *" + ArgName;
4219*67e74705SXin Li       } else {
4220*67e74705SXin Li         QualType QT = (*I)->getType();
4221*67e74705SXin Li         if (HasLocalVariableExternalStorage(*I))
4222*67e74705SXin Li           QT = Context->getPointerType(QT);
4223*67e74705SXin Li         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4224*67e74705SXin Li         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4225*67e74705SXin Li         Constructor += ", " + ArgName;
4226*67e74705SXin Li       }
4227*67e74705SXin Li       S += FieldName + ";\n";
4228*67e74705SXin Li     }
4229*67e74705SXin Li     // Output all "by ref" declarations.
4230*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4231*67e74705SXin Li          E = BlockByRefDecls.end(); I != E; ++I) {
4232*67e74705SXin Li       S += "  ";
4233*67e74705SXin Li       std::string FieldName = (*I)->getNameAsString();
4234*67e74705SXin Li       std::string ArgName = "_" + FieldName;
4235*67e74705SXin Li       {
4236*67e74705SXin Li         std::string TypeString;
4237*67e74705SXin Li         RewriteByRefString(TypeString, FieldName, (*I));
4238*67e74705SXin Li         TypeString += " *";
4239*67e74705SXin Li         FieldName = TypeString + FieldName;
4240*67e74705SXin Li         ArgName = TypeString + ArgName;
4241*67e74705SXin Li         Constructor += ", " + ArgName;
4242*67e74705SXin Li       }
4243*67e74705SXin Li       S += FieldName + "; // by ref\n";
4244*67e74705SXin Li     }
4245*67e74705SXin Li     // Finish writing the constructor.
4246*67e74705SXin Li     Constructor += ", int flags=0)";
4247*67e74705SXin Li     // Initialize all "by copy" arguments.
4248*67e74705SXin Li     bool firsTime = true;
4249*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4250*67e74705SXin Li          E = BlockByCopyDecls.end(); I != E; ++I) {
4251*67e74705SXin Li       std::string Name = (*I)->getNameAsString();
4252*67e74705SXin Li         if (firsTime) {
4253*67e74705SXin Li           Constructor += " : ";
4254*67e74705SXin Li           firsTime = false;
4255*67e74705SXin Li         }
4256*67e74705SXin Li         else
4257*67e74705SXin Li           Constructor += ", ";
4258*67e74705SXin Li         if (isTopLevelBlockPointerType((*I)->getType()))
4259*67e74705SXin Li           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4260*67e74705SXin Li         else
4261*67e74705SXin Li           Constructor += Name + "(_" + Name + ")";
4262*67e74705SXin Li     }
4263*67e74705SXin Li     // Initialize all "by ref" arguments.
4264*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4265*67e74705SXin Li          E = BlockByRefDecls.end(); I != E; ++I) {
4266*67e74705SXin Li       std::string Name = (*I)->getNameAsString();
4267*67e74705SXin Li       if (firsTime) {
4268*67e74705SXin Li         Constructor += " : ";
4269*67e74705SXin Li         firsTime = false;
4270*67e74705SXin Li       }
4271*67e74705SXin Li       else
4272*67e74705SXin Li         Constructor += ", ";
4273*67e74705SXin Li       Constructor += Name + "(_" + Name + "->__forwarding)";
4274*67e74705SXin Li     }
4275*67e74705SXin Li 
4276*67e74705SXin Li     Constructor += " {\n";
4277*67e74705SXin Li     if (GlobalVarDecl)
4278*67e74705SXin Li       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4279*67e74705SXin Li     else
4280*67e74705SXin Li       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4281*67e74705SXin Li     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4282*67e74705SXin Li 
4283*67e74705SXin Li     Constructor += "    Desc = desc;\n";
4284*67e74705SXin Li   } else {
4285*67e74705SXin Li     // Finish writing the constructor.
4286*67e74705SXin Li     Constructor += ", int flags=0) {\n";
4287*67e74705SXin Li     if (GlobalVarDecl)
4288*67e74705SXin Li       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4289*67e74705SXin Li     else
4290*67e74705SXin Li       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4291*67e74705SXin Li     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4292*67e74705SXin Li     Constructor += "    Desc = desc;\n";
4293*67e74705SXin Li   }
4294*67e74705SXin Li   Constructor += "  ";
4295*67e74705SXin Li   Constructor += "}\n";
4296*67e74705SXin Li   S += Constructor;
4297*67e74705SXin Li   S += "};\n";
4298*67e74705SXin Li   return S;
4299*67e74705SXin Li }
4300*67e74705SXin Li 
SynthesizeBlockDescriptor(std::string DescTag,std::string ImplTag,int i,StringRef FunName,unsigned hasCopy)4301*67e74705SXin Li std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4302*67e74705SXin Li                                                    std::string ImplTag, int i,
4303*67e74705SXin Li                                                    StringRef FunName,
4304*67e74705SXin Li                                                    unsigned hasCopy) {
4305*67e74705SXin Li   std::string S = "\nstatic struct " + DescTag;
4306*67e74705SXin Li 
4307*67e74705SXin Li   S += " {\n  size_t reserved;\n";
4308*67e74705SXin Li   S += "  size_t Block_size;\n";
4309*67e74705SXin Li   if (hasCopy) {
4310*67e74705SXin Li     S += "  void (*copy)(struct ";
4311*67e74705SXin Li     S += ImplTag; S += "*, struct ";
4312*67e74705SXin Li     S += ImplTag; S += "*);\n";
4313*67e74705SXin Li 
4314*67e74705SXin Li     S += "  void (*dispose)(struct ";
4315*67e74705SXin Li     S += ImplTag; S += "*);\n";
4316*67e74705SXin Li   }
4317*67e74705SXin Li   S += "} ";
4318*67e74705SXin Li 
4319*67e74705SXin Li   S += DescTag + "_DATA = { 0, sizeof(struct ";
4320*67e74705SXin Li   S += ImplTag + ")";
4321*67e74705SXin Li   if (hasCopy) {
4322*67e74705SXin Li     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4323*67e74705SXin Li     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4324*67e74705SXin Li   }
4325*67e74705SXin Li   S += "};\n";
4326*67e74705SXin Li   return S;
4327*67e74705SXin Li }
4328*67e74705SXin Li 
SynthesizeBlockLiterals(SourceLocation FunLocStart,StringRef FunName)4329*67e74705SXin Li void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4330*67e74705SXin Li                                           StringRef FunName) {
4331*67e74705SXin Li   bool RewriteSC = (GlobalVarDecl &&
4332*67e74705SXin Li                     !Blocks.empty() &&
4333*67e74705SXin Li                     GlobalVarDecl->getStorageClass() == SC_Static &&
4334*67e74705SXin Li                     GlobalVarDecl->getType().getCVRQualifiers());
4335*67e74705SXin Li   if (RewriteSC) {
4336*67e74705SXin Li     std::string SC(" void __");
4337*67e74705SXin Li     SC += GlobalVarDecl->getNameAsString();
4338*67e74705SXin Li     SC += "() {}";
4339*67e74705SXin Li     InsertText(FunLocStart, SC);
4340*67e74705SXin Li   }
4341*67e74705SXin Li 
4342*67e74705SXin Li   // Insert closures that were part of the function.
4343*67e74705SXin Li   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4344*67e74705SXin Li     CollectBlockDeclRefInfo(Blocks[i]);
4345*67e74705SXin Li     // Need to copy-in the inner copied-in variables not actually used in this
4346*67e74705SXin Li     // block.
4347*67e74705SXin Li     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4348*67e74705SXin Li       DeclRefExpr *Exp = InnerDeclRefs[count++];
4349*67e74705SXin Li       ValueDecl *VD = Exp->getDecl();
4350*67e74705SXin Li       BlockDeclRefs.push_back(Exp);
4351*67e74705SXin Li       if (!VD->hasAttr<BlocksAttr>()) {
4352*67e74705SXin Li         if (!BlockByCopyDeclsPtrSet.count(VD)) {
4353*67e74705SXin Li           BlockByCopyDeclsPtrSet.insert(VD);
4354*67e74705SXin Li           BlockByCopyDecls.push_back(VD);
4355*67e74705SXin Li         }
4356*67e74705SXin Li         continue;
4357*67e74705SXin Li       }
4358*67e74705SXin Li 
4359*67e74705SXin Li       if (!BlockByRefDeclsPtrSet.count(VD)) {
4360*67e74705SXin Li         BlockByRefDeclsPtrSet.insert(VD);
4361*67e74705SXin Li         BlockByRefDecls.push_back(VD);
4362*67e74705SXin Li       }
4363*67e74705SXin Li 
4364*67e74705SXin Li       // imported objects in the inner blocks not used in the outer
4365*67e74705SXin Li       // blocks must be copied/disposed in the outer block as well.
4366*67e74705SXin Li       if (VD->getType()->isObjCObjectPointerType() ||
4367*67e74705SXin Li           VD->getType()->isBlockPointerType())
4368*67e74705SXin Li         ImportedBlockDecls.insert(VD);
4369*67e74705SXin Li     }
4370*67e74705SXin Li 
4371*67e74705SXin Li     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4372*67e74705SXin Li     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4373*67e74705SXin Li 
4374*67e74705SXin Li     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4375*67e74705SXin Li 
4376*67e74705SXin Li     InsertText(FunLocStart, CI);
4377*67e74705SXin Li 
4378*67e74705SXin Li     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4379*67e74705SXin Li 
4380*67e74705SXin Li     InsertText(FunLocStart, CF);
4381*67e74705SXin Li 
4382*67e74705SXin Li     if (ImportedBlockDecls.size()) {
4383*67e74705SXin Li       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4384*67e74705SXin Li       InsertText(FunLocStart, HF);
4385*67e74705SXin Li     }
4386*67e74705SXin Li     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4387*67e74705SXin Li                                                ImportedBlockDecls.size() > 0);
4388*67e74705SXin Li     InsertText(FunLocStart, BD);
4389*67e74705SXin Li 
4390*67e74705SXin Li     BlockDeclRefs.clear();
4391*67e74705SXin Li     BlockByRefDecls.clear();
4392*67e74705SXin Li     BlockByRefDeclsPtrSet.clear();
4393*67e74705SXin Li     BlockByCopyDecls.clear();
4394*67e74705SXin Li     BlockByCopyDeclsPtrSet.clear();
4395*67e74705SXin Li     ImportedBlockDecls.clear();
4396*67e74705SXin Li   }
4397*67e74705SXin Li   if (RewriteSC) {
4398*67e74705SXin Li     // Must insert any 'const/volatile/static here. Since it has been
4399*67e74705SXin Li     // removed as result of rewriting of block literals.
4400*67e74705SXin Li     std::string SC;
4401*67e74705SXin Li     if (GlobalVarDecl->getStorageClass() == SC_Static)
4402*67e74705SXin Li       SC = "static ";
4403*67e74705SXin Li     if (GlobalVarDecl->getType().isConstQualified())
4404*67e74705SXin Li       SC += "const ";
4405*67e74705SXin Li     if (GlobalVarDecl->getType().isVolatileQualified())
4406*67e74705SXin Li       SC += "volatile ";
4407*67e74705SXin Li     if (GlobalVarDecl->getType().isRestrictQualified())
4408*67e74705SXin Li       SC += "restrict ";
4409*67e74705SXin Li     InsertText(FunLocStart, SC);
4410*67e74705SXin Li   }
4411*67e74705SXin Li   if (GlobalConstructionExp) {
4412*67e74705SXin Li     // extra fancy dance for global literal expression.
4413*67e74705SXin Li 
4414*67e74705SXin Li     // Always the latest block expression on the block stack.
4415*67e74705SXin Li     std::string Tag = "__";
4416*67e74705SXin Li     Tag += FunName;
4417*67e74705SXin Li     Tag += "_block_impl_";
4418*67e74705SXin Li     Tag += utostr(Blocks.size()-1);
4419*67e74705SXin Li     std::string globalBuf = "static ";
4420*67e74705SXin Li     globalBuf += Tag; globalBuf += " ";
4421*67e74705SXin Li     std::string SStr;
4422*67e74705SXin Li 
4423*67e74705SXin Li     llvm::raw_string_ostream constructorExprBuf(SStr);
4424*67e74705SXin Li     GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4425*67e74705SXin Li                                        PrintingPolicy(LangOpts));
4426*67e74705SXin Li     globalBuf += constructorExprBuf.str();
4427*67e74705SXin Li     globalBuf += ";\n";
4428*67e74705SXin Li     InsertText(FunLocStart, globalBuf);
4429*67e74705SXin Li     GlobalConstructionExp = nullptr;
4430*67e74705SXin Li   }
4431*67e74705SXin Li 
4432*67e74705SXin Li   Blocks.clear();
4433*67e74705SXin Li   InnerDeclRefsCount.clear();
4434*67e74705SXin Li   InnerDeclRefs.clear();
4435*67e74705SXin Li   RewrittenBlockExprs.clear();
4436*67e74705SXin Li }
4437*67e74705SXin Li 
InsertBlockLiteralsWithinFunction(FunctionDecl * FD)4438*67e74705SXin Li void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4439*67e74705SXin Li   SourceLocation FunLocStart =
4440*67e74705SXin Li     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4441*67e74705SXin Li                       : FD->getTypeSpecStartLoc();
4442*67e74705SXin Li   StringRef FuncName = FD->getName();
4443*67e74705SXin Li 
4444*67e74705SXin Li   SynthesizeBlockLiterals(FunLocStart, FuncName);
4445*67e74705SXin Li }
4446*67e74705SXin Li 
BuildUniqueMethodName(std::string & Name,ObjCMethodDecl * MD)4447*67e74705SXin Li static void BuildUniqueMethodName(std::string &Name,
4448*67e74705SXin Li                                   ObjCMethodDecl *MD) {
4449*67e74705SXin Li   ObjCInterfaceDecl *IFace = MD->getClassInterface();
4450*67e74705SXin Li   Name = IFace->getName();
4451*67e74705SXin Li   Name += "__" + MD->getSelector().getAsString();
4452*67e74705SXin Li   // Convert colons to underscores.
4453*67e74705SXin Li   std::string::size_type loc = 0;
4454*67e74705SXin Li   while ((loc = Name.find(":", loc)) != std::string::npos)
4455*67e74705SXin Li     Name.replace(loc, 1, "_");
4456*67e74705SXin Li }
4457*67e74705SXin Li 
InsertBlockLiteralsWithinMethod(ObjCMethodDecl * MD)4458*67e74705SXin Li void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4459*67e74705SXin Li   //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4460*67e74705SXin Li   //SourceLocation FunLocStart = MD->getLocStart();
4461*67e74705SXin Li   SourceLocation FunLocStart = MD->getLocStart();
4462*67e74705SXin Li   std::string FuncName;
4463*67e74705SXin Li   BuildUniqueMethodName(FuncName, MD);
4464*67e74705SXin Li   SynthesizeBlockLiterals(FunLocStart, FuncName);
4465*67e74705SXin Li }
4466*67e74705SXin Li 
GetBlockDeclRefExprs(Stmt * S)4467*67e74705SXin Li void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4468*67e74705SXin Li   for (Stmt *SubStmt : S->children())
4469*67e74705SXin Li     if (SubStmt) {
4470*67e74705SXin Li       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4471*67e74705SXin Li         GetBlockDeclRefExprs(CBE->getBody());
4472*67e74705SXin Li       else
4473*67e74705SXin Li         GetBlockDeclRefExprs(SubStmt);
4474*67e74705SXin Li     }
4475*67e74705SXin Li   // Handle specific things.
4476*67e74705SXin Li   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4477*67e74705SXin Li     if (DRE->refersToEnclosingVariableOrCapture() ||
4478*67e74705SXin Li         HasLocalVariableExternalStorage(DRE->getDecl()))
4479*67e74705SXin Li       // FIXME: Handle enums.
4480*67e74705SXin Li       BlockDeclRefs.push_back(DRE);
4481*67e74705SXin Li }
4482*67e74705SXin Li 
GetInnerBlockDeclRefExprs(Stmt * S,SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs,llvm::SmallPtrSetImpl<const DeclContext * > & InnerContexts)4483*67e74705SXin Li void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4484*67e74705SXin Li                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4485*67e74705SXin Li                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4486*67e74705SXin Li   for (Stmt *SubStmt : S->children())
4487*67e74705SXin Li     if (SubStmt) {
4488*67e74705SXin Li       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4489*67e74705SXin Li         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4490*67e74705SXin Li         GetInnerBlockDeclRefExprs(CBE->getBody(),
4491*67e74705SXin Li                                   InnerBlockDeclRefs,
4492*67e74705SXin Li                                   InnerContexts);
4493*67e74705SXin Li       }
4494*67e74705SXin Li       else
4495*67e74705SXin Li         GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4496*67e74705SXin Li     }
4497*67e74705SXin Li   // Handle specific things.
4498*67e74705SXin Li   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4499*67e74705SXin Li     if (DRE->refersToEnclosingVariableOrCapture() ||
4500*67e74705SXin Li         HasLocalVariableExternalStorage(DRE->getDecl())) {
4501*67e74705SXin Li       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4502*67e74705SXin Li         InnerBlockDeclRefs.push_back(DRE);
4503*67e74705SXin Li       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4504*67e74705SXin Li         if (Var->isFunctionOrMethodVarDecl())
4505*67e74705SXin Li           ImportedLocalExternalDecls.insert(Var);
4506*67e74705SXin Li     }
4507*67e74705SXin Li   }
4508*67e74705SXin Li }
4509*67e74705SXin Li 
4510*67e74705SXin Li /// convertObjCTypeToCStyleType - This routine converts such objc types
4511*67e74705SXin Li /// as qualified objects, and blocks to their closest c/c++ types that
4512*67e74705SXin Li /// it can. It returns true if input type was modified.
convertObjCTypeToCStyleType(QualType & T)4513*67e74705SXin Li bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4514*67e74705SXin Li   QualType oldT = T;
4515*67e74705SXin Li   convertBlockPointerToFunctionPointer(T);
4516*67e74705SXin Li   if (T->isFunctionPointerType()) {
4517*67e74705SXin Li     QualType PointeeTy;
4518*67e74705SXin Li     if (const PointerType* PT = T->getAs<PointerType>()) {
4519*67e74705SXin Li       PointeeTy = PT->getPointeeType();
4520*67e74705SXin Li       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4521*67e74705SXin Li         T = convertFunctionTypeOfBlocks(FT);
4522*67e74705SXin Li         T = Context->getPointerType(T);
4523*67e74705SXin Li       }
4524*67e74705SXin Li     }
4525*67e74705SXin Li   }
4526*67e74705SXin Li 
4527*67e74705SXin Li   convertToUnqualifiedObjCType(T);
4528*67e74705SXin Li   return T != oldT;
4529*67e74705SXin Li }
4530*67e74705SXin Li 
4531*67e74705SXin Li /// convertFunctionTypeOfBlocks - This routine converts a function type
4532*67e74705SXin Li /// whose result type may be a block pointer or whose argument type(s)
4533*67e74705SXin Li /// might be block pointers to an equivalent function type replacing
4534*67e74705SXin Li /// all block pointers to function pointers.
convertFunctionTypeOfBlocks(const FunctionType * FT)4535*67e74705SXin Li QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4536*67e74705SXin Li   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4537*67e74705SXin Li   // FTP will be null for closures that don't take arguments.
4538*67e74705SXin Li   // Generate a funky cast.
4539*67e74705SXin Li   SmallVector<QualType, 8> ArgTypes;
4540*67e74705SXin Li   QualType Res = FT->getReturnType();
4541*67e74705SXin Li   bool modified = convertObjCTypeToCStyleType(Res);
4542*67e74705SXin Li 
4543*67e74705SXin Li   if (FTP) {
4544*67e74705SXin Li     for (auto &I : FTP->param_types()) {
4545*67e74705SXin Li       QualType t = I;
4546*67e74705SXin Li       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4547*67e74705SXin Li       if (convertObjCTypeToCStyleType(t))
4548*67e74705SXin Li         modified = true;
4549*67e74705SXin Li       ArgTypes.push_back(t);
4550*67e74705SXin Li     }
4551*67e74705SXin Li   }
4552*67e74705SXin Li   QualType FuncType;
4553*67e74705SXin Li   if (modified)
4554*67e74705SXin Li     FuncType = getSimpleFunctionType(Res, ArgTypes);
4555*67e74705SXin Li   else FuncType = QualType(FT, 0);
4556*67e74705SXin Li   return FuncType;
4557*67e74705SXin Li }
4558*67e74705SXin Li 
SynthesizeBlockCall(CallExpr * Exp,const Expr * BlockExp)4559*67e74705SXin Li Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4560*67e74705SXin Li   // Navigate to relevant type information.
4561*67e74705SXin Li   const BlockPointerType *CPT = nullptr;
4562*67e74705SXin Li 
4563*67e74705SXin Li   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4564*67e74705SXin Li     CPT = DRE->getType()->getAs<BlockPointerType>();
4565*67e74705SXin Li   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4566*67e74705SXin Li     CPT = MExpr->getType()->getAs<BlockPointerType>();
4567*67e74705SXin Li   }
4568*67e74705SXin Li   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4569*67e74705SXin Li     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4570*67e74705SXin Li   }
4571*67e74705SXin Li   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4572*67e74705SXin Li     CPT = IEXPR->getType()->getAs<BlockPointerType>();
4573*67e74705SXin Li   else if (const ConditionalOperator *CEXPR =
4574*67e74705SXin Li             dyn_cast<ConditionalOperator>(BlockExp)) {
4575*67e74705SXin Li     Expr *LHSExp = CEXPR->getLHS();
4576*67e74705SXin Li     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4577*67e74705SXin Li     Expr *RHSExp = CEXPR->getRHS();
4578*67e74705SXin Li     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4579*67e74705SXin Li     Expr *CONDExp = CEXPR->getCond();
4580*67e74705SXin Li     ConditionalOperator *CondExpr =
4581*67e74705SXin Li       new (Context) ConditionalOperator(CONDExp,
4582*67e74705SXin Li                                       SourceLocation(), cast<Expr>(LHSStmt),
4583*67e74705SXin Li                                       SourceLocation(), cast<Expr>(RHSStmt),
4584*67e74705SXin Li                                       Exp->getType(), VK_RValue, OK_Ordinary);
4585*67e74705SXin Li     return CondExpr;
4586*67e74705SXin Li   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4587*67e74705SXin Li     CPT = IRE->getType()->getAs<BlockPointerType>();
4588*67e74705SXin Li   } else if (const PseudoObjectExpr *POE
4589*67e74705SXin Li                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4590*67e74705SXin Li     CPT = POE->getType()->castAs<BlockPointerType>();
4591*67e74705SXin Li   } else {
4592*67e74705SXin Li     assert(false && "RewriteBlockClass: Bad type");
4593*67e74705SXin Li   }
4594*67e74705SXin Li   assert(CPT && "RewriteBlockClass: Bad type");
4595*67e74705SXin Li   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4596*67e74705SXin Li   assert(FT && "RewriteBlockClass: Bad type");
4597*67e74705SXin Li   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4598*67e74705SXin Li   // FTP will be null for closures that don't take arguments.
4599*67e74705SXin Li 
4600*67e74705SXin Li   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4601*67e74705SXin Li                                       SourceLocation(), SourceLocation(),
4602*67e74705SXin Li                                       &Context->Idents.get("__block_impl"));
4603*67e74705SXin Li   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4604*67e74705SXin Li 
4605*67e74705SXin Li   // Generate a funky cast.
4606*67e74705SXin Li   SmallVector<QualType, 8> ArgTypes;
4607*67e74705SXin Li 
4608*67e74705SXin Li   // Push the block argument type.
4609*67e74705SXin Li   ArgTypes.push_back(PtrBlock);
4610*67e74705SXin Li   if (FTP) {
4611*67e74705SXin Li     for (auto &I : FTP->param_types()) {
4612*67e74705SXin Li       QualType t = I;
4613*67e74705SXin Li       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4614*67e74705SXin Li       if (!convertBlockPointerToFunctionPointer(t))
4615*67e74705SXin Li         convertToUnqualifiedObjCType(t);
4616*67e74705SXin Li       ArgTypes.push_back(t);
4617*67e74705SXin Li     }
4618*67e74705SXin Li   }
4619*67e74705SXin Li   // Now do the pointer to function cast.
4620*67e74705SXin Li   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4621*67e74705SXin Li 
4622*67e74705SXin Li   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4623*67e74705SXin Li 
4624*67e74705SXin Li   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4625*67e74705SXin Li                                                CK_BitCast,
4626*67e74705SXin Li                                                const_cast<Expr*>(BlockExp));
4627*67e74705SXin Li   // Don't forget the parens to enforce the proper binding.
4628*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4629*67e74705SXin Li                                           BlkCast);
4630*67e74705SXin Li   //PE->dump();
4631*67e74705SXin Li 
4632*67e74705SXin Li   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4633*67e74705SXin Li                                     SourceLocation(),
4634*67e74705SXin Li                                     &Context->Idents.get("FuncPtr"),
4635*67e74705SXin Li                                     Context->VoidPtrTy, nullptr,
4636*67e74705SXin Li                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4637*67e74705SXin Li                                     ICIS_NoInit);
4638*67e74705SXin Li   MemberExpr *ME =
4639*67e74705SXin Li       new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4640*67e74705SXin Li                                FD->getType(), VK_LValue, OK_Ordinary);
4641*67e74705SXin Li 
4642*67e74705SXin Li   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4643*67e74705SXin Li                                                 CK_BitCast, ME);
4644*67e74705SXin Li   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4645*67e74705SXin Li 
4646*67e74705SXin Li   SmallVector<Expr*, 8> BlkExprs;
4647*67e74705SXin Li   // Add the implicit argument.
4648*67e74705SXin Li   BlkExprs.push_back(BlkCast);
4649*67e74705SXin Li   // Add the user arguments.
4650*67e74705SXin Li   for (CallExpr::arg_iterator I = Exp->arg_begin(),
4651*67e74705SXin Li        E = Exp->arg_end(); I != E; ++I) {
4652*67e74705SXin Li     BlkExprs.push_back(*I);
4653*67e74705SXin Li   }
4654*67e74705SXin Li   CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4655*67e74705SXin Li                                         Exp->getType(), VK_RValue,
4656*67e74705SXin Li                                         SourceLocation());
4657*67e74705SXin Li   return CE;
4658*67e74705SXin Li }
4659*67e74705SXin Li 
4660*67e74705SXin Li // We need to return the rewritten expression to handle cases where the
4661*67e74705SXin Li // DeclRefExpr is embedded in another expression being rewritten.
4662*67e74705SXin Li // For example:
4663*67e74705SXin Li //
4664*67e74705SXin Li // int main() {
4665*67e74705SXin Li //    __block Foo *f;
4666*67e74705SXin Li //    __block int i;
4667*67e74705SXin Li //
4668*67e74705SXin Li //    void (^myblock)() = ^() {
4669*67e74705SXin Li //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4670*67e74705SXin Li //        i = 77;
4671*67e74705SXin Li //    };
4672*67e74705SXin Li //}
RewriteBlockDeclRefExpr(DeclRefExpr * DeclRefExp)4673*67e74705SXin Li Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4674*67e74705SXin Li   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4675*67e74705SXin Li   // for each DeclRefExp where BYREFVAR is name of the variable.
4676*67e74705SXin Li   ValueDecl *VD = DeclRefExp->getDecl();
4677*67e74705SXin Li   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4678*67e74705SXin Li                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4679*67e74705SXin Li 
4680*67e74705SXin Li   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4681*67e74705SXin Li                                     SourceLocation(),
4682*67e74705SXin Li                                     &Context->Idents.get("__forwarding"),
4683*67e74705SXin Li                                     Context->VoidPtrTy, nullptr,
4684*67e74705SXin Li                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4685*67e74705SXin Li                                     ICIS_NoInit);
4686*67e74705SXin Li   MemberExpr *ME = new (Context)
4687*67e74705SXin Li       MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4688*67e74705SXin Li                  FD->getType(), VK_LValue, OK_Ordinary);
4689*67e74705SXin Li 
4690*67e74705SXin Li   StringRef Name = VD->getName();
4691*67e74705SXin Li   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4692*67e74705SXin Li                          &Context->Idents.get(Name),
4693*67e74705SXin Li                          Context->VoidPtrTy, nullptr,
4694*67e74705SXin Li                          /*BitWidth=*/nullptr, /*Mutable=*/true,
4695*67e74705SXin Li                          ICIS_NoInit);
4696*67e74705SXin Li   ME =
4697*67e74705SXin Li       new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4698*67e74705SXin Li                                DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4699*67e74705SXin Li 
4700*67e74705SXin Li   // Need parens to enforce precedence.
4701*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4702*67e74705SXin Li                                           DeclRefExp->getExprLoc(),
4703*67e74705SXin Li                                           ME);
4704*67e74705SXin Li   ReplaceStmt(DeclRefExp, PE);
4705*67e74705SXin Li   return PE;
4706*67e74705SXin Li }
4707*67e74705SXin Li 
4708*67e74705SXin Li // Rewrites the imported local variable V with external storage
4709*67e74705SXin Li // (static, extern, etc.) as *V
4710*67e74705SXin Li //
RewriteLocalVariableExternalStorage(DeclRefExpr * DRE)4711*67e74705SXin Li Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4712*67e74705SXin Li   ValueDecl *VD = DRE->getDecl();
4713*67e74705SXin Li   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4714*67e74705SXin Li     if (!ImportedLocalExternalDecls.count(Var))
4715*67e74705SXin Li       return DRE;
4716*67e74705SXin Li   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4717*67e74705SXin Li                                           VK_LValue, OK_Ordinary,
4718*67e74705SXin Li                                           DRE->getLocation());
4719*67e74705SXin Li   // Need parens to enforce precedence.
4720*67e74705SXin Li   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4721*67e74705SXin Li                                           Exp);
4722*67e74705SXin Li   ReplaceStmt(DRE, PE);
4723*67e74705SXin Li   return PE;
4724*67e74705SXin Li }
4725*67e74705SXin Li 
RewriteCastExpr(CStyleCastExpr * CE)4726*67e74705SXin Li void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4727*67e74705SXin Li   SourceLocation LocStart = CE->getLParenLoc();
4728*67e74705SXin Li   SourceLocation LocEnd = CE->getRParenLoc();
4729*67e74705SXin Li 
4730*67e74705SXin Li   // Need to avoid trying to rewrite synthesized casts.
4731*67e74705SXin Li   if (LocStart.isInvalid())
4732*67e74705SXin Li     return;
4733*67e74705SXin Li   // Need to avoid trying to rewrite casts contained in macros.
4734*67e74705SXin Li   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4735*67e74705SXin Li     return;
4736*67e74705SXin Li 
4737*67e74705SXin Li   const char *startBuf = SM->getCharacterData(LocStart);
4738*67e74705SXin Li   const char *endBuf = SM->getCharacterData(LocEnd);
4739*67e74705SXin Li   QualType QT = CE->getType();
4740*67e74705SXin Li   const Type* TypePtr = QT->getAs<Type>();
4741*67e74705SXin Li   if (isa<TypeOfExprType>(TypePtr)) {
4742*67e74705SXin Li     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4743*67e74705SXin Li     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4744*67e74705SXin Li     std::string TypeAsString = "(";
4745*67e74705SXin Li     RewriteBlockPointerType(TypeAsString, QT);
4746*67e74705SXin Li     TypeAsString += ")";
4747*67e74705SXin Li     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4748*67e74705SXin Li     return;
4749*67e74705SXin Li   }
4750*67e74705SXin Li   // advance the location to startArgList.
4751*67e74705SXin Li   const char *argPtr = startBuf;
4752*67e74705SXin Li 
4753*67e74705SXin Li   while (*argPtr++ && (argPtr < endBuf)) {
4754*67e74705SXin Li     switch (*argPtr) {
4755*67e74705SXin Li     case '^':
4756*67e74705SXin Li       // Replace the '^' with '*'.
4757*67e74705SXin Li       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4758*67e74705SXin Li       ReplaceText(LocStart, 1, "*");
4759*67e74705SXin Li       break;
4760*67e74705SXin Li     }
4761*67e74705SXin Li   }
4762*67e74705SXin Li }
4763*67e74705SXin Li 
RewriteImplicitCastObjCExpr(CastExpr * IC)4764*67e74705SXin Li void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4765*67e74705SXin Li   CastKind CastKind = IC->getCastKind();
4766*67e74705SXin Li   if (CastKind != CK_BlockPointerToObjCPointerCast &&
4767*67e74705SXin Li       CastKind != CK_AnyPointerToBlockPointerCast)
4768*67e74705SXin Li     return;
4769*67e74705SXin Li 
4770*67e74705SXin Li   QualType QT = IC->getType();
4771*67e74705SXin Li   (void)convertBlockPointerToFunctionPointer(QT);
4772*67e74705SXin Li   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4773*67e74705SXin Li   std::string Str = "(";
4774*67e74705SXin Li   Str += TypeString;
4775*67e74705SXin Li   Str += ")";
4776*67e74705SXin Li   InsertText(IC->getSubExpr()->getLocStart(), Str);
4777*67e74705SXin Li }
4778*67e74705SXin Li 
RewriteBlockPointerFunctionArgs(FunctionDecl * FD)4779*67e74705SXin Li void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4780*67e74705SXin Li   SourceLocation DeclLoc = FD->getLocation();
4781*67e74705SXin Li   unsigned parenCount = 0;
4782*67e74705SXin Li 
4783*67e74705SXin Li   // We have 1 or more arguments that have closure pointers.
4784*67e74705SXin Li   const char *startBuf = SM->getCharacterData(DeclLoc);
4785*67e74705SXin Li   const char *startArgList = strchr(startBuf, '(');
4786*67e74705SXin Li 
4787*67e74705SXin Li   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4788*67e74705SXin Li 
4789*67e74705SXin Li   parenCount++;
4790*67e74705SXin Li   // advance the location to startArgList.
4791*67e74705SXin Li   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4792*67e74705SXin Li   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4793*67e74705SXin Li 
4794*67e74705SXin Li   const char *argPtr = startArgList;
4795*67e74705SXin Li 
4796*67e74705SXin Li   while (*argPtr++ && parenCount) {
4797*67e74705SXin Li     switch (*argPtr) {
4798*67e74705SXin Li     case '^':
4799*67e74705SXin Li       // Replace the '^' with '*'.
4800*67e74705SXin Li       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4801*67e74705SXin Li       ReplaceText(DeclLoc, 1, "*");
4802*67e74705SXin Li       break;
4803*67e74705SXin Li     case '(':
4804*67e74705SXin Li       parenCount++;
4805*67e74705SXin Li       break;
4806*67e74705SXin Li     case ')':
4807*67e74705SXin Li       parenCount--;
4808*67e74705SXin Li       break;
4809*67e74705SXin Li     }
4810*67e74705SXin Li   }
4811*67e74705SXin Li }
4812*67e74705SXin Li 
PointerTypeTakesAnyBlockArguments(QualType QT)4813*67e74705SXin Li bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4814*67e74705SXin Li   const FunctionProtoType *FTP;
4815*67e74705SXin Li   const PointerType *PT = QT->getAs<PointerType>();
4816*67e74705SXin Li   if (PT) {
4817*67e74705SXin Li     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4818*67e74705SXin Li   } else {
4819*67e74705SXin Li     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4820*67e74705SXin Li     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4821*67e74705SXin Li     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4822*67e74705SXin Li   }
4823*67e74705SXin Li   if (FTP) {
4824*67e74705SXin Li     for (const auto &I : FTP->param_types())
4825*67e74705SXin Li       if (isTopLevelBlockPointerType(I))
4826*67e74705SXin Li         return true;
4827*67e74705SXin Li   }
4828*67e74705SXin Li   return false;
4829*67e74705SXin Li }
4830*67e74705SXin Li 
PointerTypeTakesAnyObjCQualifiedType(QualType QT)4831*67e74705SXin Li bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4832*67e74705SXin Li   const FunctionProtoType *FTP;
4833*67e74705SXin Li   const PointerType *PT = QT->getAs<PointerType>();
4834*67e74705SXin Li   if (PT) {
4835*67e74705SXin Li     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4836*67e74705SXin Li   } else {
4837*67e74705SXin Li     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4838*67e74705SXin Li     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4839*67e74705SXin Li     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4840*67e74705SXin Li   }
4841*67e74705SXin Li   if (FTP) {
4842*67e74705SXin Li     for (const auto &I : FTP->param_types()) {
4843*67e74705SXin Li       if (I->isObjCQualifiedIdType())
4844*67e74705SXin Li         return true;
4845*67e74705SXin Li       if (I->isObjCObjectPointerType() &&
4846*67e74705SXin Li           I->getPointeeType()->isObjCQualifiedInterfaceType())
4847*67e74705SXin Li         return true;
4848*67e74705SXin Li     }
4849*67e74705SXin Li 
4850*67e74705SXin Li   }
4851*67e74705SXin Li   return false;
4852*67e74705SXin Li }
4853*67e74705SXin Li 
GetExtentOfArgList(const char * Name,const char * & LParen,const char * & RParen)4854*67e74705SXin Li void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4855*67e74705SXin Li                                      const char *&RParen) {
4856*67e74705SXin Li   const char *argPtr = strchr(Name, '(');
4857*67e74705SXin Li   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4858*67e74705SXin Li 
4859*67e74705SXin Li   LParen = argPtr; // output the start.
4860*67e74705SXin Li   argPtr++; // skip past the left paren.
4861*67e74705SXin Li   unsigned parenCount = 1;
4862*67e74705SXin Li 
4863*67e74705SXin Li   while (*argPtr && parenCount) {
4864*67e74705SXin Li     switch (*argPtr) {
4865*67e74705SXin Li     case '(': parenCount++; break;
4866*67e74705SXin Li     case ')': parenCount--; break;
4867*67e74705SXin Li     default: break;
4868*67e74705SXin Li     }
4869*67e74705SXin Li     if (parenCount) argPtr++;
4870*67e74705SXin Li   }
4871*67e74705SXin Li   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4872*67e74705SXin Li   RParen = argPtr; // output the end
4873*67e74705SXin Li }
4874*67e74705SXin Li 
RewriteBlockPointerDecl(NamedDecl * ND)4875*67e74705SXin Li void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4876*67e74705SXin Li   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4877*67e74705SXin Li     RewriteBlockPointerFunctionArgs(FD);
4878*67e74705SXin Li     return;
4879*67e74705SXin Li   }
4880*67e74705SXin Li   // Handle Variables and Typedefs.
4881*67e74705SXin Li   SourceLocation DeclLoc = ND->getLocation();
4882*67e74705SXin Li   QualType DeclT;
4883*67e74705SXin Li   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4884*67e74705SXin Li     DeclT = VD->getType();
4885*67e74705SXin Li   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4886*67e74705SXin Li     DeclT = TDD->getUnderlyingType();
4887*67e74705SXin Li   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4888*67e74705SXin Li     DeclT = FD->getType();
4889*67e74705SXin Li   else
4890*67e74705SXin Li     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4891*67e74705SXin Li 
4892*67e74705SXin Li   const char *startBuf = SM->getCharacterData(DeclLoc);
4893*67e74705SXin Li   const char *endBuf = startBuf;
4894*67e74705SXin Li   // scan backward (from the decl location) for the end of the previous decl.
4895*67e74705SXin Li   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4896*67e74705SXin Li     startBuf--;
4897*67e74705SXin Li   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4898*67e74705SXin Li   std::string buf;
4899*67e74705SXin Li   unsigned OrigLength=0;
4900*67e74705SXin Li   // *startBuf != '^' if we are dealing with a pointer to function that
4901*67e74705SXin Li   // may take block argument types (which will be handled below).
4902*67e74705SXin Li   if (*startBuf == '^') {
4903*67e74705SXin Li     // Replace the '^' with '*', computing a negative offset.
4904*67e74705SXin Li     buf = '*';
4905*67e74705SXin Li     startBuf++;
4906*67e74705SXin Li     OrigLength++;
4907*67e74705SXin Li   }
4908*67e74705SXin Li   while (*startBuf != ')') {
4909*67e74705SXin Li     buf += *startBuf;
4910*67e74705SXin Li     startBuf++;
4911*67e74705SXin Li     OrigLength++;
4912*67e74705SXin Li   }
4913*67e74705SXin Li   buf += ')';
4914*67e74705SXin Li   OrigLength++;
4915*67e74705SXin Li 
4916*67e74705SXin Li   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4917*67e74705SXin Li       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4918*67e74705SXin Li     // Replace the '^' with '*' for arguments.
4919*67e74705SXin Li     // Replace id<P> with id/*<>*/
4920*67e74705SXin Li     DeclLoc = ND->getLocation();
4921*67e74705SXin Li     startBuf = SM->getCharacterData(DeclLoc);
4922*67e74705SXin Li     const char *argListBegin, *argListEnd;
4923*67e74705SXin Li     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4924*67e74705SXin Li     while (argListBegin < argListEnd) {
4925*67e74705SXin Li       if (*argListBegin == '^')
4926*67e74705SXin Li         buf += '*';
4927*67e74705SXin Li       else if (*argListBegin ==  '<') {
4928*67e74705SXin Li         buf += "/*";
4929*67e74705SXin Li         buf += *argListBegin++;
4930*67e74705SXin Li         OrigLength++;
4931*67e74705SXin Li         while (*argListBegin != '>') {
4932*67e74705SXin Li           buf += *argListBegin++;
4933*67e74705SXin Li           OrigLength++;
4934*67e74705SXin Li         }
4935*67e74705SXin Li         buf += *argListBegin;
4936*67e74705SXin Li         buf += "*/";
4937*67e74705SXin Li       }
4938*67e74705SXin Li       else
4939*67e74705SXin Li         buf += *argListBegin;
4940*67e74705SXin Li       argListBegin++;
4941*67e74705SXin Li       OrigLength++;
4942*67e74705SXin Li     }
4943*67e74705SXin Li     buf += ')';
4944*67e74705SXin Li     OrigLength++;
4945*67e74705SXin Li   }
4946*67e74705SXin Li   ReplaceText(Start, OrigLength, buf);
4947*67e74705SXin Li }
4948*67e74705SXin Li 
4949*67e74705SXin Li /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4950*67e74705SXin Li /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4951*67e74705SXin Li ///                    struct Block_byref_id_object *src) {
4952*67e74705SXin Li ///  _Block_object_assign (&_dest->object, _src->object,
4953*67e74705SXin Li ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4954*67e74705SXin Li ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4955*67e74705SXin Li ///  _Block_object_assign(&_dest->object, _src->object,
4956*67e74705SXin Li ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4957*67e74705SXin Li ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4958*67e74705SXin Li /// }
4959*67e74705SXin Li /// And:
4960*67e74705SXin Li /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4961*67e74705SXin Li ///  _Block_object_dispose(_src->object,
4962*67e74705SXin Li ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4963*67e74705SXin Li ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4964*67e74705SXin Li ///  _Block_object_dispose(_src->object,
4965*67e74705SXin Li ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4966*67e74705SXin Li ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4967*67e74705SXin Li /// }
4968*67e74705SXin Li 
SynthesizeByrefCopyDestroyHelper(VarDecl * VD,int flag)4969*67e74705SXin Li std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4970*67e74705SXin Li                                                           int flag) {
4971*67e74705SXin Li   std::string S;
4972*67e74705SXin Li   if (CopyDestroyCache.count(flag))
4973*67e74705SXin Li     return S;
4974*67e74705SXin Li   CopyDestroyCache.insert(flag);
4975*67e74705SXin Li   S = "static void __Block_byref_id_object_copy_";
4976*67e74705SXin Li   S += utostr(flag);
4977*67e74705SXin Li   S += "(void *dst, void *src) {\n";
4978*67e74705SXin Li 
4979*67e74705SXin Li   // offset into the object pointer is computed as:
4980*67e74705SXin Li   // void * + void* + int + int + void* + void *
4981*67e74705SXin Li   unsigned IntSize =
4982*67e74705SXin Li   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4983*67e74705SXin Li   unsigned VoidPtrSize =
4984*67e74705SXin Li   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4985*67e74705SXin Li 
4986*67e74705SXin Li   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4987*67e74705SXin Li   S += " _Block_object_assign((char*)dst + ";
4988*67e74705SXin Li   S += utostr(offset);
4989*67e74705SXin Li   S += ", *(void * *) ((char*)src + ";
4990*67e74705SXin Li   S += utostr(offset);
4991*67e74705SXin Li   S += "), ";
4992*67e74705SXin Li   S += utostr(flag);
4993*67e74705SXin Li   S += ");\n}\n";
4994*67e74705SXin Li 
4995*67e74705SXin Li   S += "static void __Block_byref_id_object_dispose_";
4996*67e74705SXin Li   S += utostr(flag);
4997*67e74705SXin Li   S += "(void *src) {\n";
4998*67e74705SXin Li   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4999*67e74705SXin Li   S += utostr(offset);
5000*67e74705SXin Li   S += "), ";
5001*67e74705SXin Li   S += utostr(flag);
5002*67e74705SXin Li   S += ");\n}\n";
5003*67e74705SXin Li   return S;
5004*67e74705SXin Li }
5005*67e74705SXin Li 
5006*67e74705SXin Li /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5007*67e74705SXin Li /// the declaration into:
5008*67e74705SXin Li /// struct __Block_byref_ND {
5009*67e74705SXin Li /// void *__isa;                  // NULL for everything except __weak pointers
5010*67e74705SXin Li /// struct __Block_byref_ND *__forwarding;
5011*67e74705SXin Li /// int32_t __flags;
5012*67e74705SXin Li /// int32_t __size;
5013*67e74705SXin Li /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5014*67e74705SXin Li /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5015*67e74705SXin Li /// typex ND;
5016*67e74705SXin Li /// };
5017*67e74705SXin Li ///
5018*67e74705SXin Li /// It then replaces declaration of ND variable with:
5019*67e74705SXin Li /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5020*67e74705SXin Li ///                               __size=sizeof(struct __Block_byref_ND),
5021*67e74705SXin Li ///                               ND=initializer-if-any};
5022*67e74705SXin Li ///
5023*67e74705SXin Li ///
RewriteByRefVar(VarDecl * ND,bool firstDecl,bool lastDecl)5024*67e74705SXin Li void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5025*67e74705SXin Li                                         bool lastDecl) {
5026*67e74705SXin Li   int flag = 0;
5027*67e74705SXin Li   int isa = 0;
5028*67e74705SXin Li   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5029*67e74705SXin Li   if (DeclLoc.isInvalid())
5030*67e74705SXin Li     // If type location is missing, it is because of missing type (a warning).
5031*67e74705SXin Li     // Use variable's location which is good for this case.
5032*67e74705SXin Li     DeclLoc = ND->getLocation();
5033*67e74705SXin Li   const char *startBuf = SM->getCharacterData(DeclLoc);
5034*67e74705SXin Li   SourceLocation X = ND->getLocEnd();
5035*67e74705SXin Li   X = SM->getExpansionLoc(X);
5036*67e74705SXin Li   const char *endBuf = SM->getCharacterData(X);
5037*67e74705SXin Li   std::string Name(ND->getNameAsString());
5038*67e74705SXin Li   std::string ByrefType;
5039*67e74705SXin Li   RewriteByRefString(ByrefType, Name, ND, true);
5040*67e74705SXin Li   ByrefType += " {\n";
5041*67e74705SXin Li   ByrefType += "  void *__isa;\n";
5042*67e74705SXin Li   RewriteByRefString(ByrefType, Name, ND);
5043*67e74705SXin Li   ByrefType += " *__forwarding;\n";
5044*67e74705SXin Li   ByrefType += " int __flags;\n";
5045*67e74705SXin Li   ByrefType += " int __size;\n";
5046*67e74705SXin Li   // Add void *__Block_byref_id_object_copy;
5047*67e74705SXin Li   // void *__Block_byref_id_object_dispose; if needed.
5048*67e74705SXin Li   QualType Ty = ND->getType();
5049*67e74705SXin Li   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5050*67e74705SXin Li   if (HasCopyAndDispose) {
5051*67e74705SXin Li     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5052*67e74705SXin Li     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5053*67e74705SXin Li   }
5054*67e74705SXin Li 
5055*67e74705SXin Li   QualType T = Ty;
5056*67e74705SXin Li   (void)convertBlockPointerToFunctionPointer(T);
5057*67e74705SXin Li   T.getAsStringInternal(Name, Context->getPrintingPolicy());
5058*67e74705SXin Li 
5059*67e74705SXin Li   ByrefType += " " + Name + ";\n";
5060*67e74705SXin Li   ByrefType += "};\n";
5061*67e74705SXin Li   // Insert this type in global scope. It is needed by helper function.
5062*67e74705SXin Li   SourceLocation FunLocStart;
5063*67e74705SXin Li   if (CurFunctionDef)
5064*67e74705SXin Li      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5065*67e74705SXin Li   else {
5066*67e74705SXin Li     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5067*67e74705SXin Li     FunLocStart = CurMethodDef->getLocStart();
5068*67e74705SXin Li   }
5069*67e74705SXin Li   InsertText(FunLocStart, ByrefType);
5070*67e74705SXin Li 
5071*67e74705SXin Li   if (Ty.isObjCGCWeak()) {
5072*67e74705SXin Li     flag |= BLOCK_FIELD_IS_WEAK;
5073*67e74705SXin Li     isa = 1;
5074*67e74705SXin Li   }
5075*67e74705SXin Li   if (HasCopyAndDispose) {
5076*67e74705SXin Li     flag = BLOCK_BYREF_CALLER;
5077*67e74705SXin Li     QualType Ty = ND->getType();
5078*67e74705SXin Li     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5079*67e74705SXin Li     if (Ty->isBlockPointerType())
5080*67e74705SXin Li       flag |= BLOCK_FIELD_IS_BLOCK;
5081*67e74705SXin Li     else
5082*67e74705SXin Li       flag |= BLOCK_FIELD_IS_OBJECT;
5083*67e74705SXin Li     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5084*67e74705SXin Li     if (!HF.empty())
5085*67e74705SXin Li       Preamble += HF;
5086*67e74705SXin Li   }
5087*67e74705SXin Li 
5088*67e74705SXin Li   // struct __Block_byref_ND ND =
5089*67e74705SXin Li   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5090*67e74705SXin Li   //  initializer-if-any};
5091*67e74705SXin Li   bool hasInit = (ND->getInit() != nullptr);
5092*67e74705SXin Li   // FIXME. rewriter does not support __block c++ objects which
5093*67e74705SXin Li   // require construction.
5094*67e74705SXin Li   if (hasInit)
5095*67e74705SXin Li     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5096*67e74705SXin Li       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5097*67e74705SXin Li       if (CXXDecl && CXXDecl->isDefaultConstructor())
5098*67e74705SXin Li         hasInit = false;
5099*67e74705SXin Li     }
5100*67e74705SXin Li 
5101*67e74705SXin Li   unsigned flags = 0;
5102*67e74705SXin Li   if (HasCopyAndDispose)
5103*67e74705SXin Li     flags |= BLOCK_HAS_COPY_DISPOSE;
5104*67e74705SXin Li   Name = ND->getNameAsString();
5105*67e74705SXin Li   ByrefType.clear();
5106*67e74705SXin Li   RewriteByRefString(ByrefType, Name, ND);
5107*67e74705SXin Li   std::string ForwardingCastType("(");
5108*67e74705SXin Li   ForwardingCastType += ByrefType + " *)";
5109*67e74705SXin Li   ByrefType += " " + Name + " = {(void*)";
5110*67e74705SXin Li   ByrefType += utostr(isa);
5111*67e74705SXin Li   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5112*67e74705SXin Li   ByrefType += utostr(flags);
5113*67e74705SXin Li   ByrefType += ", ";
5114*67e74705SXin Li   ByrefType += "sizeof(";
5115*67e74705SXin Li   RewriteByRefString(ByrefType, Name, ND);
5116*67e74705SXin Li   ByrefType += ")";
5117*67e74705SXin Li   if (HasCopyAndDispose) {
5118*67e74705SXin Li     ByrefType += ", __Block_byref_id_object_copy_";
5119*67e74705SXin Li     ByrefType += utostr(flag);
5120*67e74705SXin Li     ByrefType += ", __Block_byref_id_object_dispose_";
5121*67e74705SXin Li     ByrefType += utostr(flag);
5122*67e74705SXin Li   }
5123*67e74705SXin Li 
5124*67e74705SXin Li   if (!firstDecl) {
5125*67e74705SXin Li     // In multiple __block declarations, and for all but 1st declaration,
5126*67e74705SXin Li     // find location of the separating comma. This would be start location
5127*67e74705SXin Li     // where new text is to be inserted.
5128*67e74705SXin Li     DeclLoc = ND->getLocation();
5129*67e74705SXin Li     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5130*67e74705SXin Li     const char *commaBuf = startDeclBuf;
5131*67e74705SXin Li     while (*commaBuf != ',')
5132*67e74705SXin Li       commaBuf--;
5133*67e74705SXin Li     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5134*67e74705SXin Li     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5135*67e74705SXin Li     startBuf = commaBuf;
5136*67e74705SXin Li   }
5137*67e74705SXin Li 
5138*67e74705SXin Li   if (!hasInit) {
5139*67e74705SXin Li     ByrefType += "};\n";
5140*67e74705SXin Li     unsigned nameSize = Name.size();
5141*67e74705SXin Li     // for block or function pointer declaration. Name is aleady
5142*67e74705SXin Li     // part of the declaration.
5143*67e74705SXin Li     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5144*67e74705SXin Li       nameSize = 1;
5145*67e74705SXin Li     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5146*67e74705SXin Li   }
5147*67e74705SXin Li   else {
5148*67e74705SXin Li     ByrefType += ", ";
5149*67e74705SXin Li     SourceLocation startLoc;
5150*67e74705SXin Li     Expr *E = ND->getInit();
5151*67e74705SXin Li     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5152*67e74705SXin Li       startLoc = ECE->getLParenLoc();
5153*67e74705SXin Li     else
5154*67e74705SXin Li       startLoc = E->getLocStart();
5155*67e74705SXin Li     startLoc = SM->getExpansionLoc(startLoc);
5156*67e74705SXin Li     endBuf = SM->getCharacterData(startLoc);
5157*67e74705SXin Li     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5158*67e74705SXin Li 
5159*67e74705SXin Li     const char separator = lastDecl ? ';' : ',';
5160*67e74705SXin Li     const char *startInitializerBuf = SM->getCharacterData(startLoc);
5161*67e74705SXin Li     const char *separatorBuf = strchr(startInitializerBuf, separator);
5162*67e74705SXin Li     assert((*separatorBuf == separator) &&
5163*67e74705SXin Li            "RewriteByRefVar: can't find ';' or ','");
5164*67e74705SXin Li     SourceLocation separatorLoc =
5165*67e74705SXin Li       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5166*67e74705SXin Li 
5167*67e74705SXin Li     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5168*67e74705SXin Li   }
5169*67e74705SXin Li }
5170*67e74705SXin Li 
CollectBlockDeclRefInfo(BlockExpr * Exp)5171*67e74705SXin Li void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5172*67e74705SXin Li   // Add initializers for any closure decl refs.
5173*67e74705SXin Li   GetBlockDeclRefExprs(Exp->getBody());
5174*67e74705SXin Li   if (BlockDeclRefs.size()) {
5175*67e74705SXin Li     // Unique all "by copy" declarations.
5176*67e74705SXin Li     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5177*67e74705SXin Li       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5178*67e74705SXin Li         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5179*67e74705SXin Li           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5180*67e74705SXin Li           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5181*67e74705SXin Li         }
5182*67e74705SXin Li       }
5183*67e74705SXin Li     // Unique all "by ref" declarations.
5184*67e74705SXin Li     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5185*67e74705SXin Li       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5186*67e74705SXin Li         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5187*67e74705SXin Li           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5188*67e74705SXin Li           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5189*67e74705SXin Li         }
5190*67e74705SXin Li       }
5191*67e74705SXin Li     // Find any imported blocks...they will need special attention.
5192*67e74705SXin Li     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5193*67e74705SXin Li       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5194*67e74705SXin Li           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5195*67e74705SXin Li           BlockDeclRefs[i]->getType()->isBlockPointerType())
5196*67e74705SXin Li         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5197*67e74705SXin Li   }
5198*67e74705SXin Li }
5199*67e74705SXin Li 
SynthBlockInitFunctionDecl(StringRef name)5200*67e74705SXin Li FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5201*67e74705SXin Li   IdentifierInfo *ID = &Context->Idents.get(name);
5202*67e74705SXin Li   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5203*67e74705SXin Li   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5204*67e74705SXin Li                               SourceLocation(), ID, FType, nullptr, SC_Extern,
5205*67e74705SXin Li                               false, false);
5206*67e74705SXin Li }
5207*67e74705SXin Li 
SynthBlockInitExpr(BlockExpr * Exp,const SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs)5208*67e74705SXin Li Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5209*67e74705SXin Li                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5210*67e74705SXin Li   const BlockDecl *block = Exp->getBlockDecl();
5211*67e74705SXin Li 
5212*67e74705SXin Li   Blocks.push_back(Exp);
5213*67e74705SXin Li 
5214*67e74705SXin Li   CollectBlockDeclRefInfo(Exp);
5215*67e74705SXin Li 
5216*67e74705SXin Li   // Add inner imported variables now used in current block.
5217*67e74705SXin Li   int countOfInnerDecls = 0;
5218*67e74705SXin Li   if (!InnerBlockDeclRefs.empty()) {
5219*67e74705SXin Li     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5220*67e74705SXin Li       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5221*67e74705SXin Li       ValueDecl *VD = Exp->getDecl();
5222*67e74705SXin Li       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5223*67e74705SXin Li       // We need to save the copied-in variables in nested
5224*67e74705SXin Li       // blocks because it is needed at the end for some of the API generations.
5225*67e74705SXin Li       // See SynthesizeBlockLiterals routine.
5226*67e74705SXin Li         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5227*67e74705SXin Li         BlockDeclRefs.push_back(Exp);
5228*67e74705SXin Li         BlockByCopyDeclsPtrSet.insert(VD);
5229*67e74705SXin Li         BlockByCopyDecls.push_back(VD);
5230*67e74705SXin Li       }
5231*67e74705SXin Li       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5232*67e74705SXin Li         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5233*67e74705SXin Li         BlockDeclRefs.push_back(Exp);
5234*67e74705SXin Li         BlockByRefDeclsPtrSet.insert(VD);
5235*67e74705SXin Li         BlockByRefDecls.push_back(VD);
5236*67e74705SXin Li       }
5237*67e74705SXin Li     }
5238*67e74705SXin Li     // Find any imported blocks...they will need special attention.
5239*67e74705SXin Li     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5240*67e74705SXin Li       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5241*67e74705SXin Li           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5242*67e74705SXin Li           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5243*67e74705SXin Li         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5244*67e74705SXin Li   }
5245*67e74705SXin Li   InnerDeclRefsCount.push_back(countOfInnerDecls);
5246*67e74705SXin Li 
5247*67e74705SXin Li   std::string FuncName;
5248*67e74705SXin Li 
5249*67e74705SXin Li   if (CurFunctionDef)
5250*67e74705SXin Li     FuncName = CurFunctionDef->getNameAsString();
5251*67e74705SXin Li   else if (CurMethodDef)
5252*67e74705SXin Li     BuildUniqueMethodName(FuncName, CurMethodDef);
5253*67e74705SXin Li   else if (GlobalVarDecl)
5254*67e74705SXin Li     FuncName = std::string(GlobalVarDecl->getNameAsString());
5255*67e74705SXin Li 
5256*67e74705SXin Li   bool GlobalBlockExpr =
5257*67e74705SXin Li     block->getDeclContext()->getRedeclContext()->isFileContext();
5258*67e74705SXin Li 
5259*67e74705SXin Li   if (GlobalBlockExpr && !GlobalVarDecl) {
5260*67e74705SXin Li     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5261*67e74705SXin Li     GlobalBlockExpr = false;
5262*67e74705SXin Li   }
5263*67e74705SXin Li 
5264*67e74705SXin Li   std::string BlockNumber = utostr(Blocks.size()-1);
5265*67e74705SXin Li 
5266*67e74705SXin Li   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5267*67e74705SXin Li 
5268*67e74705SXin Li   // Get a pointer to the function type so we can cast appropriately.
5269*67e74705SXin Li   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5270*67e74705SXin Li   QualType FType = Context->getPointerType(BFT);
5271*67e74705SXin Li 
5272*67e74705SXin Li   FunctionDecl *FD;
5273*67e74705SXin Li   Expr *NewRep;
5274*67e74705SXin Li 
5275*67e74705SXin Li   // Simulate a constructor call...
5276*67e74705SXin Li   std::string Tag;
5277*67e74705SXin Li 
5278*67e74705SXin Li   if (GlobalBlockExpr)
5279*67e74705SXin Li     Tag = "__global_";
5280*67e74705SXin Li   else
5281*67e74705SXin Li     Tag = "__";
5282*67e74705SXin Li   Tag += FuncName + "_block_impl_" + BlockNumber;
5283*67e74705SXin Li 
5284*67e74705SXin Li   FD = SynthBlockInitFunctionDecl(Tag);
5285*67e74705SXin Li   DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5286*67e74705SXin Li                                                SourceLocation());
5287*67e74705SXin Li 
5288*67e74705SXin Li   SmallVector<Expr*, 4> InitExprs;
5289*67e74705SXin Li 
5290*67e74705SXin Li   // Initialize the block function.
5291*67e74705SXin Li   FD = SynthBlockInitFunctionDecl(Func);
5292*67e74705SXin Li   DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5293*67e74705SXin Li                                                VK_LValue, SourceLocation());
5294*67e74705SXin Li   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5295*67e74705SXin Li                                                 CK_BitCast, Arg);
5296*67e74705SXin Li   InitExprs.push_back(castExpr);
5297*67e74705SXin Li 
5298*67e74705SXin Li   // Initialize the block descriptor.
5299*67e74705SXin Li   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5300*67e74705SXin Li 
5301*67e74705SXin Li   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5302*67e74705SXin Li                                    SourceLocation(), SourceLocation(),
5303*67e74705SXin Li                                    &Context->Idents.get(DescData.c_str()),
5304*67e74705SXin Li                                    Context->VoidPtrTy, nullptr,
5305*67e74705SXin Li                                    SC_Static);
5306*67e74705SXin Li   UnaryOperator *DescRefExpr =
5307*67e74705SXin Li     new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5308*67e74705SXin Li                                                           Context->VoidPtrTy,
5309*67e74705SXin Li                                                           VK_LValue,
5310*67e74705SXin Li                                                           SourceLocation()),
5311*67e74705SXin Li                                 UO_AddrOf,
5312*67e74705SXin Li                                 Context->getPointerType(Context->VoidPtrTy),
5313*67e74705SXin Li                                 VK_RValue, OK_Ordinary,
5314*67e74705SXin Li                                 SourceLocation());
5315*67e74705SXin Li   InitExprs.push_back(DescRefExpr);
5316*67e74705SXin Li 
5317*67e74705SXin Li   // Add initializers for any closure decl refs.
5318*67e74705SXin Li   if (BlockDeclRefs.size()) {
5319*67e74705SXin Li     Expr *Exp;
5320*67e74705SXin Li     // Output all "by copy" declarations.
5321*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5322*67e74705SXin Li          E = BlockByCopyDecls.end(); I != E; ++I) {
5323*67e74705SXin Li       if (isObjCType((*I)->getType())) {
5324*67e74705SXin Li         // FIXME: Conform to ABI ([[obj retain] autorelease]).
5325*67e74705SXin Li         FD = SynthBlockInitFunctionDecl((*I)->getName());
5326*67e74705SXin Li         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5327*67e74705SXin Li                                         VK_LValue, SourceLocation());
5328*67e74705SXin Li         if (HasLocalVariableExternalStorage(*I)) {
5329*67e74705SXin Li           QualType QT = (*I)->getType();
5330*67e74705SXin Li           QT = Context->getPointerType(QT);
5331*67e74705SXin Li           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5332*67e74705SXin Li                                             OK_Ordinary, SourceLocation());
5333*67e74705SXin Li         }
5334*67e74705SXin Li       } else if (isTopLevelBlockPointerType((*I)->getType())) {
5335*67e74705SXin Li         FD = SynthBlockInitFunctionDecl((*I)->getName());
5336*67e74705SXin Li         Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5337*67e74705SXin Li                                         VK_LValue, SourceLocation());
5338*67e74705SXin Li         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5339*67e74705SXin Li                                        CK_BitCast, Arg);
5340*67e74705SXin Li       } else {
5341*67e74705SXin Li         FD = SynthBlockInitFunctionDecl((*I)->getName());
5342*67e74705SXin Li         Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5343*67e74705SXin Li                                         VK_LValue, SourceLocation());
5344*67e74705SXin Li         if (HasLocalVariableExternalStorage(*I)) {
5345*67e74705SXin Li           QualType QT = (*I)->getType();
5346*67e74705SXin Li           QT = Context->getPointerType(QT);
5347*67e74705SXin Li           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5348*67e74705SXin Li                                             OK_Ordinary, SourceLocation());
5349*67e74705SXin Li         }
5350*67e74705SXin Li 
5351*67e74705SXin Li       }
5352*67e74705SXin Li       InitExprs.push_back(Exp);
5353*67e74705SXin Li     }
5354*67e74705SXin Li     // Output all "by ref" declarations.
5355*67e74705SXin Li     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5356*67e74705SXin Li          E = BlockByRefDecls.end(); I != E; ++I) {
5357*67e74705SXin Li       ValueDecl *ND = (*I);
5358*67e74705SXin Li       std::string Name(ND->getNameAsString());
5359*67e74705SXin Li       std::string RecName;
5360*67e74705SXin Li       RewriteByRefString(RecName, Name, ND, true);
5361*67e74705SXin Li       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5362*67e74705SXin Li                                                 + sizeof("struct"));
5363*67e74705SXin Li       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5364*67e74705SXin Li                                           SourceLocation(), SourceLocation(),
5365*67e74705SXin Li                                           II);
5366*67e74705SXin Li       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5367*67e74705SXin Li       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5368*67e74705SXin Li 
5369*67e74705SXin Li       FD = SynthBlockInitFunctionDecl((*I)->getName());
5370*67e74705SXin Li       Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5371*67e74705SXin Li                                       SourceLocation());
5372*67e74705SXin Li       bool isNestedCapturedVar = false;
5373*67e74705SXin Li       if (block)
5374*67e74705SXin Li         for (const auto &CI : block->captures()) {
5375*67e74705SXin Li           const VarDecl *variable = CI.getVariable();
5376*67e74705SXin Li           if (variable == ND && CI.isNested()) {
5377*67e74705SXin Li             assert (CI.isByRef() &&
5378*67e74705SXin Li                     "SynthBlockInitExpr - captured block variable is not byref");
5379*67e74705SXin Li             isNestedCapturedVar = true;
5380*67e74705SXin Li             break;
5381*67e74705SXin Li           }
5382*67e74705SXin Li         }
5383*67e74705SXin Li       // captured nested byref variable has its address passed. Do not take
5384*67e74705SXin Li       // its address again.
5385*67e74705SXin Li       if (!isNestedCapturedVar)
5386*67e74705SXin Li           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5387*67e74705SXin Li                                      Context->getPointerType(Exp->getType()),
5388*67e74705SXin Li                                      VK_RValue, OK_Ordinary, SourceLocation());
5389*67e74705SXin Li       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5390*67e74705SXin Li       InitExprs.push_back(Exp);
5391*67e74705SXin Li     }
5392*67e74705SXin Li   }
5393*67e74705SXin Li   if (ImportedBlockDecls.size()) {
5394*67e74705SXin Li     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5395*67e74705SXin Li     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5396*67e74705SXin Li     unsigned IntSize =
5397*67e74705SXin Li       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5398*67e74705SXin Li     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5399*67e74705SXin Li                                            Context->IntTy, SourceLocation());
5400*67e74705SXin Li     InitExprs.push_back(FlagExp);
5401*67e74705SXin Li   }
5402*67e74705SXin Li   NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5403*67e74705SXin Li                                   FType, VK_LValue, SourceLocation());
5404*67e74705SXin Li 
5405*67e74705SXin Li   if (GlobalBlockExpr) {
5406*67e74705SXin Li     assert (!GlobalConstructionExp &&
5407*67e74705SXin Li             "SynthBlockInitExpr - GlobalConstructionExp must be null");
5408*67e74705SXin Li     GlobalConstructionExp = NewRep;
5409*67e74705SXin Li     NewRep = DRE;
5410*67e74705SXin Li   }
5411*67e74705SXin Li 
5412*67e74705SXin Li   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5413*67e74705SXin Li                              Context->getPointerType(NewRep->getType()),
5414*67e74705SXin Li                              VK_RValue, OK_Ordinary, SourceLocation());
5415*67e74705SXin Li   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5416*67e74705SXin Li                                     NewRep);
5417*67e74705SXin Li   // Put Paren around the call.
5418*67e74705SXin Li   NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5419*67e74705SXin Li                                    NewRep);
5420*67e74705SXin Li 
5421*67e74705SXin Li   BlockDeclRefs.clear();
5422*67e74705SXin Li   BlockByRefDecls.clear();
5423*67e74705SXin Li   BlockByRefDeclsPtrSet.clear();
5424*67e74705SXin Li   BlockByCopyDecls.clear();
5425*67e74705SXin Li   BlockByCopyDeclsPtrSet.clear();
5426*67e74705SXin Li   ImportedBlockDecls.clear();
5427*67e74705SXin Li   return NewRep;
5428*67e74705SXin Li }
5429*67e74705SXin Li 
IsDeclStmtInForeachHeader(DeclStmt * DS)5430*67e74705SXin Li bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5431*67e74705SXin Li   if (const ObjCForCollectionStmt * CS =
5432*67e74705SXin Li       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5433*67e74705SXin Li         return CS->getElement() == DS;
5434*67e74705SXin Li   return false;
5435*67e74705SXin Li }
5436*67e74705SXin Li 
5437*67e74705SXin Li //===----------------------------------------------------------------------===//
5438*67e74705SXin Li // Function Body / Expression rewriting
5439*67e74705SXin Li //===----------------------------------------------------------------------===//
5440*67e74705SXin Li 
RewriteFunctionBodyOrGlobalInitializer(Stmt * S)5441*67e74705SXin Li Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5442*67e74705SXin Li   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5443*67e74705SXin Li       isa<DoStmt>(S) || isa<ForStmt>(S))
5444*67e74705SXin Li     Stmts.push_back(S);
5445*67e74705SXin Li   else if (isa<ObjCForCollectionStmt>(S)) {
5446*67e74705SXin Li     Stmts.push_back(S);
5447*67e74705SXin Li     ObjCBcLabelNo.push_back(++BcLabelCount);
5448*67e74705SXin Li   }
5449*67e74705SXin Li 
5450*67e74705SXin Li   // Pseudo-object operations and ivar references need special
5451*67e74705SXin Li   // treatment because we're going to recursively rewrite them.
5452*67e74705SXin Li   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5453*67e74705SXin Li     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5454*67e74705SXin Li       return RewritePropertyOrImplicitSetter(PseudoOp);
5455*67e74705SXin Li     } else {
5456*67e74705SXin Li       return RewritePropertyOrImplicitGetter(PseudoOp);
5457*67e74705SXin Li     }
5458*67e74705SXin Li   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5459*67e74705SXin Li     return RewriteObjCIvarRefExpr(IvarRefExpr);
5460*67e74705SXin Li   }
5461*67e74705SXin Li   else if (isa<OpaqueValueExpr>(S))
5462*67e74705SXin Li     S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5463*67e74705SXin Li 
5464*67e74705SXin Li   SourceRange OrigStmtRange = S->getSourceRange();
5465*67e74705SXin Li 
5466*67e74705SXin Li   // Perform a bottom up rewrite of all children.
5467*67e74705SXin Li   for (Stmt *&childStmt : S->children())
5468*67e74705SXin Li     if (childStmt) {
5469*67e74705SXin Li       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5470*67e74705SXin Li       if (newStmt) {
5471*67e74705SXin Li         childStmt = newStmt;
5472*67e74705SXin Li       }
5473*67e74705SXin Li     }
5474*67e74705SXin Li 
5475*67e74705SXin Li   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5476*67e74705SXin Li     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5477*67e74705SXin Li     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5478*67e74705SXin Li     InnerContexts.insert(BE->getBlockDecl());
5479*67e74705SXin Li     ImportedLocalExternalDecls.clear();
5480*67e74705SXin Li     GetInnerBlockDeclRefExprs(BE->getBody(),
5481*67e74705SXin Li                               InnerBlockDeclRefs, InnerContexts);
5482*67e74705SXin Li     // Rewrite the block body in place.
5483*67e74705SXin Li     Stmt *SaveCurrentBody = CurrentBody;
5484*67e74705SXin Li     CurrentBody = BE->getBody();
5485*67e74705SXin Li     PropParentMap = nullptr;
5486*67e74705SXin Li     // block literal on rhs of a property-dot-sytax assignment
5487*67e74705SXin Li     // must be replaced by its synthesize ast so getRewrittenText
5488*67e74705SXin Li     // works as expected. In this case, what actually ends up on RHS
5489*67e74705SXin Li     // is the blockTranscribed which is the helper function for the
5490*67e74705SXin Li     // block literal; as in: self.c = ^() {[ace ARR];};
5491*67e74705SXin Li     bool saveDisableReplaceStmt = DisableReplaceStmt;
5492*67e74705SXin Li     DisableReplaceStmt = false;
5493*67e74705SXin Li     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5494*67e74705SXin Li     DisableReplaceStmt = saveDisableReplaceStmt;
5495*67e74705SXin Li     CurrentBody = SaveCurrentBody;
5496*67e74705SXin Li     PropParentMap = nullptr;
5497*67e74705SXin Li     ImportedLocalExternalDecls.clear();
5498*67e74705SXin Li     // Now we snarf the rewritten text and stash it away for later use.
5499*67e74705SXin Li     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5500*67e74705SXin Li     RewrittenBlockExprs[BE] = Str;
5501*67e74705SXin Li 
5502*67e74705SXin Li     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5503*67e74705SXin Li 
5504*67e74705SXin Li     //blockTranscribed->dump();
5505*67e74705SXin Li     ReplaceStmt(S, blockTranscribed);
5506*67e74705SXin Li     return blockTranscribed;
5507*67e74705SXin Li   }
5508*67e74705SXin Li   // Handle specific things.
5509*67e74705SXin Li   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5510*67e74705SXin Li     return RewriteAtEncode(AtEncode);
5511*67e74705SXin Li 
5512*67e74705SXin Li   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5513*67e74705SXin Li     return RewriteAtSelector(AtSelector);
5514*67e74705SXin Li 
5515*67e74705SXin Li   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5516*67e74705SXin Li     return RewriteObjCStringLiteral(AtString);
5517*67e74705SXin Li 
5518*67e74705SXin Li   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5519*67e74705SXin Li     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5520*67e74705SXin Li 
5521*67e74705SXin Li   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5522*67e74705SXin Li     return RewriteObjCBoxedExpr(BoxedExpr);
5523*67e74705SXin Li 
5524*67e74705SXin Li   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5525*67e74705SXin Li     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5526*67e74705SXin Li 
5527*67e74705SXin Li   if (ObjCDictionaryLiteral *DictionaryLitExpr =
5528*67e74705SXin Li         dyn_cast<ObjCDictionaryLiteral>(S))
5529*67e74705SXin Li     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5530*67e74705SXin Li 
5531*67e74705SXin Li   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5532*67e74705SXin Li #if 0
5533*67e74705SXin Li     // Before we rewrite it, put the original message expression in a comment.
5534*67e74705SXin Li     SourceLocation startLoc = MessExpr->getLocStart();
5535*67e74705SXin Li     SourceLocation endLoc = MessExpr->getLocEnd();
5536*67e74705SXin Li 
5537*67e74705SXin Li     const char *startBuf = SM->getCharacterData(startLoc);
5538*67e74705SXin Li     const char *endBuf = SM->getCharacterData(endLoc);
5539*67e74705SXin Li 
5540*67e74705SXin Li     std::string messString;
5541*67e74705SXin Li     messString += "// ";
5542*67e74705SXin Li     messString.append(startBuf, endBuf-startBuf+1);
5543*67e74705SXin Li     messString += "\n";
5544*67e74705SXin Li 
5545*67e74705SXin Li     // FIXME: Missing definition of
5546*67e74705SXin Li     // InsertText(clang::SourceLocation, char const*, unsigned int).
5547*67e74705SXin Li     // InsertText(startLoc, messString);
5548*67e74705SXin Li     // Tried this, but it didn't work either...
5549*67e74705SXin Li     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5550*67e74705SXin Li #endif
5551*67e74705SXin Li     return RewriteMessageExpr(MessExpr);
5552*67e74705SXin Li   }
5553*67e74705SXin Li 
5554*67e74705SXin Li   if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5555*67e74705SXin Li         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5556*67e74705SXin Li     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5557*67e74705SXin Li   }
5558*67e74705SXin Li 
5559*67e74705SXin Li   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5560*67e74705SXin Li     return RewriteObjCTryStmt(StmtTry);
5561*67e74705SXin Li 
5562*67e74705SXin Li   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5563*67e74705SXin Li     return RewriteObjCSynchronizedStmt(StmtTry);
5564*67e74705SXin Li 
5565*67e74705SXin Li   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5566*67e74705SXin Li     return RewriteObjCThrowStmt(StmtThrow);
5567*67e74705SXin Li 
5568*67e74705SXin Li   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5569*67e74705SXin Li     return RewriteObjCProtocolExpr(ProtocolExp);
5570*67e74705SXin Li 
5571*67e74705SXin Li   if (ObjCForCollectionStmt *StmtForCollection =
5572*67e74705SXin Li         dyn_cast<ObjCForCollectionStmt>(S))
5573*67e74705SXin Li     return RewriteObjCForCollectionStmt(StmtForCollection,
5574*67e74705SXin Li                                         OrigStmtRange.getEnd());
5575*67e74705SXin Li   if (BreakStmt *StmtBreakStmt =
5576*67e74705SXin Li       dyn_cast<BreakStmt>(S))
5577*67e74705SXin Li     return RewriteBreakStmt(StmtBreakStmt);
5578*67e74705SXin Li   if (ContinueStmt *StmtContinueStmt =
5579*67e74705SXin Li       dyn_cast<ContinueStmt>(S))
5580*67e74705SXin Li     return RewriteContinueStmt(StmtContinueStmt);
5581*67e74705SXin Li 
5582*67e74705SXin Li   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5583*67e74705SXin Li   // and cast exprs.
5584*67e74705SXin Li   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5585*67e74705SXin Li     // FIXME: What we're doing here is modifying the type-specifier that
5586*67e74705SXin Li     // precedes the first Decl.  In the future the DeclGroup should have
5587*67e74705SXin Li     // a separate type-specifier that we can rewrite.
5588*67e74705SXin Li     // NOTE: We need to avoid rewriting the DeclStmt if it is within
5589*67e74705SXin Li     // the context of an ObjCForCollectionStmt. For example:
5590*67e74705SXin Li     //   NSArray *someArray;
5591*67e74705SXin Li     //   for (id <FooProtocol> index in someArray) ;
5592*67e74705SXin Li     // This is because RewriteObjCForCollectionStmt() does textual rewriting
5593*67e74705SXin Li     // and it depends on the original text locations/positions.
5594*67e74705SXin Li     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5595*67e74705SXin Li       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5596*67e74705SXin Li 
5597*67e74705SXin Li     // Blocks rewrite rules.
5598*67e74705SXin Li     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5599*67e74705SXin Li          DI != DE; ++DI) {
5600*67e74705SXin Li       Decl *SD = *DI;
5601*67e74705SXin Li       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5602*67e74705SXin Li         if (isTopLevelBlockPointerType(ND->getType()))
5603*67e74705SXin Li           RewriteBlockPointerDecl(ND);
5604*67e74705SXin Li         else if (ND->getType()->isFunctionPointerType())
5605*67e74705SXin Li           CheckFunctionPointerDecl(ND->getType(), ND);
5606*67e74705SXin Li         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5607*67e74705SXin Li           if (VD->hasAttr<BlocksAttr>()) {
5608*67e74705SXin Li             static unsigned uniqueByrefDeclCount = 0;
5609*67e74705SXin Li             assert(!BlockByRefDeclNo.count(ND) &&
5610*67e74705SXin Li               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5611*67e74705SXin Li             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5612*67e74705SXin Li             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5613*67e74705SXin Li           }
5614*67e74705SXin Li           else
5615*67e74705SXin Li             RewriteTypeOfDecl(VD);
5616*67e74705SXin Li         }
5617*67e74705SXin Li       }
5618*67e74705SXin Li       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5619*67e74705SXin Li         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5620*67e74705SXin Li           RewriteBlockPointerDecl(TD);
5621*67e74705SXin Li         else if (TD->getUnderlyingType()->isFunctionPointerType())
5622*67e74705SXin Li           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5623*67e74705SXin Li       }
5624*67e74705SXin Li     }
5625*67e74705SXin Li   }
5626*67e74705SXin Li 
5627*67e74705SXin Li   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5628*67e74705SXin Li     RewriteObjCQualifiedInterfaceTypes(CE);
5629*67e74705SXin Li 
5630*67e74705SXin Li   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5631*67e74705SXin Li       isa<DoStmt>(S) || isa<ForStmt>(S)) {
5632*67e74705SXin Li     assert(!Stmts.empty() && "Statement stack is empty");
5633*67e74705SXin Li     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5634*67e74705SXin Li              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5635*67e74705SXin Li             && "Statement stack mismatch");
5636*67e74705SXin Li     Stmts.pop_back();
5637*67e74705SXin Li   }
5638*67e74705SXin Li   // Handle blocks rewriting.
5639*67e74705SXin Li   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5640*67e74705SXin Li     ValueDecl *VD = DRE->getDecl();
5641*67e74705SXin Li     if (VD->hasAttr<BlocksAttr>())
5642*67e74705SXin Li       return RewriteBlockDeclRefExpr(DRE);
5643*67e74705SXin Li     if (HasLocalVariableExternalStorage(VD))
5644*67e74705SXin Li       return RewriteLocalVariableExternalStorage(DRE);
5645*67e74705SXin Li   }
5646*67e74705SXin Li 
5647*67e74705SXin Li   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5648*67e74705SXin Li     if (CE->getCallee()->getType()->isBlockPointerType()) {
5649*67e74705SXin Li       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5650*67e74705SXin Li       ReplaceStmt(S, BlockCall);
5651*67e74705SXin Li       return BlockCall;
5652*67e74705SXin Li     }
5653*67e74705SXin Li   }
5654*67e74705SXin Li   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5655*67e74705SXin Li     RewriteCastExpr(CE);
5656*67e74705SXin Li   }
5657*67e74705SXin Li   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5658*67e74705SXin Li     RewriteImplicitCastObjCExpr(ICE);
5659*67e74705SXin Li   }
5660*67e74705SXin Li #if 0
5661*67e74705SXin Li 
5662*67e74705SXin Li   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5663*67e74705SXin Li     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5664*67e74705SXin Li                                                    ICE->getSubExpr(),
5665*67e74705SXin Li                                                    SourceLocation());
5666*67e74705SXin Li     // Get the new text.
5667*67e74705SXin Li     std::string SStr;
5668*67e74705SXin Li     llvm::raw_string_ostream Buf(SStr);
5669*67e74705SXin Li     Replacement->printPretty(Buf);
5670*67e74705SXin Li     const std::string &Str = Buf.str();
5671*67e74705SXin Li 
5672*67e74705SXin Li     printf("CAST = %s\n", &Str[0]);
5673*67e74705SXin Li     InsertText(ICE->getSubExpr()->getLocStart(), Str);
5674*67e74705SXin Li     delete S;
5675*67e74705SXin Li     return Replacement;
5676*67e74705SXin Li   }
5677*67e74705SXin Li #endif
5678*67e74705SXin Li   // Return this stmt unmodified.
5679*67e74705SXin Li   return S;
5680*67e74705SXin Li }
5681*67e74705SXin Li 
RewriteRecordBody(RecordDecl * RD)5682*67e74705SXin Li void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5683*67e74705SXin Li   for (auto *FD : RD->fields()) {
5684*67e74705SXin Li     if (isTopLevelBlockPointerType(FD->getType()))
5685*67e74705SXin Li       RewriteBlockPointerDecl(FD);
5686*67e74705SXin Li     if (FD->getType()->isObjCQualifiedIdType() ||
5687*67e74705SXin Li         FD->getType()->isObjCQualifiedInterfaceType())
5688*67e74705SXin Li       RewriteObjCQualifiedInterfaceTypes(FD);
5689*67e74705SXin Li   }
5690*67e74705SXin Li }
5691*67e74705SXin Li 
5692*67e74705SXin Li /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5693*67e74705SXin Li /// main file of the input.
HandleDeclInMainFile(Decl * D)5694*67e74705SXin Li void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5695*67e74705SXin Li   switch (D->getKind()) {
5696*67e74705SXin Li     case Decl::Function: {
5697*67e74705SXin Li       FunctionDecl *FD = cast<FunctionDecl>(D);
5698*67e74705SXin Li       if (FD->isOverloadedOperator())
5699*67e74705SXin Li         return;
5700*67e74705SXin Li 
5701*67e74705SXin Li       // Since function prototypes don't have ParmDecl's, we check the function
5702*67e74705SXin Li       // prototype. This enables us to rewrite function declarations and
5703*67e74705SXin Li       // definitions using the same code.
5704*67e74705SXin Li       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5705*67e74705SXin Li 
5706*67e74705SXin Li       if (!FD->isThisDeclarationADefinition())
5707*67e74705SXin Li         break;
5708*67e74705SXin Li 
5709*67e74705SXin Li       // FIXME: If this should support Obj-C++, support CXXTryStmt
5710*67e74705SXin Li       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5711*67e74705SXin Li         CurFunctionDef = FD;
5712*67e74705SXin Li         CurrentBody = Body;
5713*67e74705SXin Li         Body =
5714*67e74705SXin Li         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5715*67e74705SXin Li         FD->setBody(Body);
5716*67e74705SXin Li         CurrentBody = nullptr;
5717*67e74705SXin Li         if (PropParentMap) {
5718*67e74705SXin Li           delete PropParentMap;
5719*67e74705SXin Li           PropParentMap = nullptr;
5720*67e74705SXin Li         }
5721*67e74705SXin Li         // This synthesizes and inserts the block "impl" struct, invoke function,
5722*67e74705SXin Li         // and any copy/dispose helper functions.
5723*67e74705SXin Li         InsertBlockLiteralsWithinFunction(FD);
5724*67e74705SXin Li         RewriteLineDirective(D);
5725*67e74705SXin Li         CurFunctionDef = nullptr;
5726*67e74705SXin Li       }
5727*67e74705SXin Li       break;
5728*67e74705SXin Li     }
5729*67e74705SXin Li     case Decl::ObjCMethod: {
5730*67e74705SXin Li       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5731*67e74705SXin Li       if (CompoundStmt *Body = MD->getCompoundBody()) {
5732*67e74705SXin Li         CurMethodDef = MD;
5733*67e74705SXin Li         CurrentBody = Body;
5734*67e74705SXin Li         Body =
5735*67e74705SXin Li           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5736*67e74705SXin Li         MD->setBody(Body);
5737*67e74705SXin Li         CurrentBody = nullptr;
5738*67e74705SXin Li         if (PropParentMap) {
5739*67e74705SXin Li           delete PropParentMap;
5740*67e74705SXin Li           PropParentMap = nullptr;
5741*67e74705SXin Li         }
5742*67e74705SXin Li         InsertBlockLiteralsWithinMethod(MD);
5743*67e74705SXin Li         RewriteLineDirective(D);
5744*67e74705SXin Li         CurMethodDef = nullptr;
5745*67e74705SXin Li       }
5746*67e74705SXin Li       break;
5747*67e74705SXin Li     }
5748*67e74705SXin Li     case Decl::ObjCImplementation: {
5749*67e74705SXin Li       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5750*67e74705SXin Li       ClassImplementation.push_back(CI);
5751*67e74705SXin Li       break;
5752*67e74705SXin Li     }
5753*67e74705SXin Li     case Decl::ObjCCategoryImpl: {
5754*67e74705SXin Li       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5755*67e74705SXin Li       CategoryImplementation.push_back(CI);
5756*67e74705SXin Li       break;
5757*67e74705SXin Li     }
5758*67e74705SXin Li     case Decl::Var: {
5759*67e74705SXin Li       VarDecl *VD = cast<VarDecl>(D);
5760*67e74705SXin Li       RewriteObjCQualifiedInterfaceTypes(VD);
5761*67e74705SXin Li       if (isTopLevelBlockPointerType(VD->getType()))
5762*67e74705SXin Li         RewriteBlockPointerDecl(VD);
5763*67e74705SXin Li       else if (VD->getType()->isFunctionPointerType()) {
5764*67e74705SXin Li         CheckFunctionPointerDecl(VD->getType(), VD);
5765*67e74705SXin Li         if (VD->getInit()) {
5766*67e74705SXin Li           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5767*67e74705SXin Li             RewriteCastExpr(CE);
5768*67e74705SXin Li           }
5769*67e74705SXin Li         }
5770*67e74705SXin Li       } else if (VD->getType()->isRecordType()) {
5771*67e74705SXin Li         RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5772*67e74705SXin Li         if (RD->isCompleteDefinition())
5773*67e74705SXin Li           RewriteRecordBody(RD);
5774*67e74705SXin Li       }
5775*67e74705SXin Li       if (VD->getInit()) {
5776*67e74705SXin Li         GlobalVarDecl = VD;
5777*67e74705SXin Li         CurrentBody = VD->getInit();
5778*67e74705SXin Li         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5779*67e74705SXin Li         CurrentBody = nullptr;
5780*67e74705SXin Li         if (PropParentMap) {
5781*67e74705SXin Li           delete PropParentMap;
5782*67e74705SXin Li           PropParentMap = nullptr;
5783*67e74705SXin Li         }
5784*67e74705SXin Li         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5785*67e74705SXin Li         GlobalVarDecl = nullptr;
5786*67e74705SXin Li 
5787*67e74705SXin Li         // This is needed for blocks.
5788*67e74705SXin Li         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5789*67e74705SXin Li             RewriteCastExpr(CE);
5790*67e74705SXin Li         }
5791*67e74705SXin Li       }
5792*67e74705SXin Li       break;
5793*67e74705SXin Li     }
5794*67e74705SXin Li     case Decl::TypeAlias:
5795*67e74705SXin Li     case Decl::Typedef: {
5796*67e74705SXin Li       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5797*67e74705SXin Li         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5798*67e74705SXin Li           RewriteBlockPointerDecl(TD);
5799*67e74705SXin Li         else if (TD->getUnderlyingType()->isFunctionPointerType())
5800*67e74705SXin Li           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5801*67e74705SXin Li         else
5802*67e74705SXin Li           RewriteObjCQualifiedInterfaceTypes(TD);
5803*67e74705SXin Li       }
5804*67e74705SXin Li       break;
5805*67e74705SXin Li     }
5806*67e74705SXin Li     case Decl::CXXRecord:
5807*67e74705SXin Li     case Decl::Record: {
5808*67e74705SXin Li       RecordDecl *RD = cast<RecordDecl>(D);
5809*67e74705SXin Li       if (RD->isCompleteDefinition())
5810*67e74705SXin Li         RewriteRecordBody(RD);
5811*67e74705SXin Li       break;
5812*67e74705SXin Li     }
5813*67e74705SXin Li     default:
5814*67e74705SXin Li       break;
5815*67e74705SXin Li   }
5816*67e74705SXin Li   // Nothing yet.
5817*67e74705SXin Li }
5818*67e74705SXin Li 
5819*67e74705SXin Li /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5820*67e74705SXin Li /// protocol reference symbols in the for of:
5821*67e74705SXin Li /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
Write_ProtocolExprReferencedMetadata(ASTContext * Context,ObjCProtocolDecl * PDecl,std::string & Result)5822*67e74705SXin Li static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5823*67e74705SXin Li                                                  ObjCProtocolDecl *PDecl,
5824*67e74705SXin Li                                                  std::string &Result) {
5825*67e74705SXin Li   // Also output .objc_protorefs$B section and its meta-data.
5826*67e74705SXin Li   if (Context->getLangOpts().MicrosoftExt)
5827*67e74705SXin Li     Result += "static ";
5828*67e74705SXin Li   Result += "struct _protocol_t *";
5829*67e74705SXin Li   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5830*67e74705SXin Li   Result += PDecl->getNameAsString();
5831*67e74705SXin Li   Result += " = &";
5832*67e74705SXin Li   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5833*67e74705SXin Li   Result += ";\n";
5834*67e74705SXin Li }
5835*67e74705SXin Li 
HandleTranslationUnit(ASTContext & C)5836*67e74705SXin Li void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5837*67e74705SXin Li   if (Diags.hasErrorOccurred())
5838*67e74705SXin Li     return;
5839*67e74705SXin Li 
5840*67e74705SXin Li   RewriteInclude();
5841*67e74705SXin Li 
5842*67e74705SXin Li   for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5843*67e74705SXin Li     // translation of function bodies were postponed until all class and
5844*67e74705SXin Li     // their extensions and implementations are seen. This is because, we
5845*67e74705SXin Li     // cannot build grouping structs for bitfields until they are all seen.
5846*67e74705SXin Li     FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5847*67e74705SXin Li     HandleTopLevelSingleDecl(FDecl);
5848*67e74705SXin Li   }
5849*67e74705SXin Li 
5850*67e74705SXin Li   // Here's a great place to add any extra declarations that may be needed.
5851*67e74705SXin Li   // Write out meta data for each @protocol(<expr>).
5852*67e74705SXin Li   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5853*67e74705SXin Li     RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5854*67e74705SXin Li     Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5855*67e74705SXin Li   }
5856*67e74705SXin Li 
5857*67e74705SXin Li   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5858*67e74705SXin Li 
5859*67e74705SXin Li   if (ClassImplementation.size() || CategoryImplementation.size())
5860*67e74705SXin Li     RewriteImplementations();
5861*67e74705SXin Li 
5862*67e74705SXin Li   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5863*67e74705SXin Li     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5864*67e74705SXin Li     // Write struct declaration for the class matching its ivar declarations.
5865*67e74705SXin Li     // Note that for modern abi, this is postponed until the end of TU
5866*67e74705SXin Li     // because class extensions and the implementation might declare their own
5867*67e74705SXin Li     // private ivars.
5868*67e74705SXin Li     RewriteInterfaceDecl(CDecl);
5869*67e74705SXin Li   }
5870*67e74705SXin Li 
5871*67e74705SXin Li   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5872*67e74705SXin Li   // we are done.
5873*67e74705SXin Li   if (const RewriteBuffer *RewriteBuf =
5874*67e74705SXin Li       Rewrite.getRewriteBufferFor(MainFileID)) {
5875*67e74705SXin Li     //printf("Changed:\n");
5876*67e74705SXin Li     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5877*67e74705SXin Li   } else {
5878*67e74705SXin Li     llvm::errs() << "No changes\n";
5879*67e74705SXin Li   }
5880*67e74705SXin Li 
5881*67e74705SXin Li   if (ClassImplementation.size() || CategoryImplementation.size() ||
5882*67e74705SXin Li       ProtocolExprDecls.size()) {
5883*67e74705SXin Li     // Rewrite Objective-c meta data*
5884*67e74705SXin Li     std::string ResultStr;
5885*67e74705SXin Li     RewriteMetaDataIntoBuffer(ResultStr);
5886*67e74705SXin Li     // Emit metadata.
5887*67e74705SXin Li     *OutFile << ResultStr;
5888*67e74705SXin Li   }
5889*67e74705SXin Li   // Emit ImageInfo;
5890*67e74705SXin Li   {
5891*67e74705SXin Li     std::string ResultStr;
5892*67e74705SXin Li     WriteImageInfo(ResultStr);
5893*67e74705SXin Li     *OutFile << ResultStr;
5894*67e74705SXin Li   }
5895*67e74705SXin Li   OutFile->flush();
5896*67e74705SXin Li }
5897*67e74705SXin Li 
Initialize(ASTContext & context)5898*67e74705SXin Li void RewriteModernObjC::Initialize(ASTContext &context) {
5899*67e74705SXin Li   InitializeCommon(context);
5900*67e74705SXin Li 
5901*67e74705SXin Li   Preamble += "#ifndef __OBJC2__\n";
5902*67e74705SXin Li   Preamble += "#define __OBJC2__\n";
5903*67e74705SXin Li   Preamble += "#endif\n";
5904*67e74705SXin Li 
5905*67e74705SXin Li   // declaring objc_selector outside the parameter list removes a silly
5906*67e74705SXin Li   // scope related warning...
5907*67e74705SXin Li   if (IsHeader)
5908*67e74705SXin Li     Preamble = "#pragma once\n";
5909*67e74705SXin Li   Preamble += "struct objc_selector; struct objc_class;\n";
5910*67e74705SXin Li   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5911*67e74705SXin Li   Preamble += "\n\tstruct objc_object *superClass; ";
5912*67e74705SXin Li   // Add a constructor for creating temporary objects.
5913*67e74705SXin Li   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5914*67e74705SXin Li   Preamble += ": object(o), superClass(s) {} ";
5915*67e74705SXin Li   Preamble += "\n};\n";
5916*67e74705SXin Li 
5917*67e74705SXin Li   if (LangOpts.MicrosoftExt) {
5918*67e74705SXin Li     // Define all sections using syntax that makes sense.
5919*67e74705SXin Li     // These are currently generated.
5920*67e74705SXin Li     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5921*67e74705SXin Li     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5922*67e74705SXin Li     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5923*67e74705SXin Li     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5924*67e74705SXin Li     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5925*67e74705SXin Li     // These are generated but not necessary for functionality.
5926*67e74705SXin Li     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5927*67e74705SXin Li     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5928*67e74705SXin Li     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5929*67e74705SXin Li     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5930*67e74705SXin Li 
5931*67e74705SXin Li     // These need be generated for performance. Currently they are not,
5932*67e74705SXin Li     // using API calls instead.
5933*67e74705SXin Li     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5934*67e74705SXin Li     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5935*67e74705SXin Li     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5936*67e74705SXin Li 
5937*67e74705SXin Li   }
5938*67e74705SXin Li   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5939*67e74705SXin Li   Preamble += "typedef struct objc_object Protocol;\n";
5940*67e74705SXin Li   Preamble += "#define _REWRITER_typedef_Protocol\n";
5941*67e74705SXin Li   Preamble += "#endif\n";
5942*67e74705SXin Li   if (LangOpts.MicrosoftExt) {
5943*67e74705SXin Li     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5944*67e74705SXin Li     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5945*67e74705SXin Li   }
5946*67e74705SXin Li   else
5947*67e74705SXin Li     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5948*67e74705SXin Li 
5949*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5950*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5951*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5952*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5953*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5954*67e74705SXin Li 
5955*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5956*67e74705SXin Li   Preamble += "(const char *);\n";
5957*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5958*67e74705SXin Li   Preamble += "(struct objc_class *);\n";
5959*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5960*67e74705SXin Li   Preamble += "(const char *);\n";
5961*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5962*67e74705SXin Li   // @synchronized hooks.
5963*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5964*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5965*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5966*67e74705SXin Li   Preamble += "#ifdef _WIN64\n";
5967*67e74705SXin Li   Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
5968*67e74705SXin Li   Preamble += "#else\n";
5969*67e74705SXin Li   Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5970*67e74705SXin Li   Preamble += "#endif\n";
5971*67e74705SXin Li   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5972*67e74705SXin Li   Preamble += "struct __objcFastEnumerationState {\n\t";
5973*67e74705SXin Li   Preamble += "unsigned long state;\n\t";
5974*67e74705SXin Li   Preamble += "void **itemsPtr;\n\t";
5975*67e74705SXin Li   Preamble += "unsigned long *mutationsPtr;\n\t";
5976*67e74705SXin Li   Preamble += "unsigned long extra[5];\n};\n";
5977*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5978*67e74705SXin Li   Preamble += "#define __FASTENUMERATIONSTATE\n";
5979*67e74705SXin Li   Preamble += "#endif\n";
5980*67e74705SXin Li   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5981*67e74705SXin Li   Preamble += "struct __NSConstantStringImpl {\n";
5982*67e74705SXin Li   Preamble += "  int *isa;\n";
5983*67e74705SXin Li   Preamble += "  int flags;\n";
5984*67e74705SXin Li   Preamble += "  char *str;\n";
5985*67e74705SXin Li   Preamble += "#if _WIN64\n";
5986*67e74705SXin Li   Preamble += "  long long length;\n";
5987*67e74705SXin Li   Preamble += "#else\n";
5988*67e74705SXin Li   Preamble += "  long length;\n";
5989*67e74705SXin Li   Preamble += "#endif\n";
5990*67e74705SXin Li   Preamble += "};\n";
5991*67e74705SXin Li   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5992*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5993*67e74705SXin Li   Preamble += "#else\n";
5994*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5995*67e74705SXin Li   Preamble += "#endif\n";
5996*67e74705SXin Li   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5997*67e74705SXin Li   Preamble += "#endif\n";
5998*67e74705SXin Li   // Blocks preamble.
5999*67e74705SXin Li   Preamble += "#ifndef BLOCK_IMPL\n";
6000*67e74705SXin Li   Preamble += "#define BLOCK_IMPL\n";
6001*67e74705SXin Li   Preamble += "struct __block_impl {\n";
6002*67e74705SXin Li   Preamble += "  void *isa;\n";
6003*67e74705SXin Li   Preamble += "  int Flags;\n";
6004*67e74705SXin Li   Preamble += "  int Reserved;\n";
6005*67e74705SXin Li   Preamble += "  void *FuncPtr;\n";
6006*67e74705SXin Li   Preamble += "};\n";
6007*67e74705SXin Li   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6008*67e74705SXin Li   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6009*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllexport) "
6010*67e74705SXin Li   "void _Block_object_assign(void *, const void *, const int);\n";
6011*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6012*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6013*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6014*67e74705SXin Li   Preamble += "#else\n";
6015*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6016*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6017*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6018*67e74705SXin Li   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6019*67e74705SXin Li   Preamble += "#endif\n";
6020*67e74705SXin Li   Preamble += "#endif\n";
6021*67e74705SXin Li   if (LangOpts.MicrosoftExt) {
6022*67e74705SXin Li     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6023*67e74705SXin Li     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6024*67e74705SXin Li     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
6025*67e74705SXin Li     Preamble += "#define __attribute__(X)\n";
6026*67e74705SXin Li     Preamble += "#endif\n";
6027*67e74705SXin Li     Preamble += "#ifndef __weak\n";
6028*67e74705SXin Li     Preamble += "#define __weak\n";
6029*67e74705SXin Li     Preamble += "#endif\n";
6030*67e74705SXin Li     Preamble += "#ifndef __block\n";
6031*67e74705SXin Li     Preamble += "#define __block\n";
6032*67e74705SXin Li     Preamble += "#endif\n";
6033*67e74705SXin Li   }
6034*67e74705SXin Li   else {
6035*67e74705SXin Li     Preamble += "#define __block\n";
6036*67e74705SXin Li     Preamble += "#define __weak\n";
6037*67e74705SXin Li   }
6038*67e74705SXin Li 
6039*67e74705SXin Li   // Declarations required for modern objective-c array and dictionary literals.
6040*67e74705SXin Li   Preamble += "\n#include <stdarg.h>\n";
6041*67e74705SXin Li   Preamble += "struct __NSContainer_literal {\n";
6042*67e74705SXin Li   Preamble += "  void * *arr;\n";
6043*67e74705SXin Li   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
6044*67e74705SXin Li   Preamble += "\tva_list marker;\n";
6045*67e74705SXin Li   Preamble += "\tva_start(marker, count);\n";
6046*67e74705SXin Li   Preamble += "\tarr = new void *[count];\n";
6047*67e74705SXin Li   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6048*67e74705SXin Li   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6049*67e74705SXin Li   Preamble += "\tva_end( marker );\n";
6050*67e74705SXin Li   Preamble += "  };\n";
6051*67e74705SXin Li   Preamble += "  ~__NSContainer_literal() {\n";
6052*67e74705SXin Li   Preamble += "\tdelete[] arr;\n";
6053*67e74705SXin Li   Preamble += "  }\n";
6054*67e74705SXin Li   Preamble += "};\n";
6055*67e74705SXin Li 
6056*67e74705SXin Li   // Declaration required for implementation of @autoreleasepool statement.
6057*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6058*67e74705SXin Li   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6059*67e74705SXin Li   Preamble += "struct __AtAutoreleasePool {\n";
6060*67e74705SXin Li   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6061*67e74705SXin Li   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6062*67e74705SXin Li   Preamble += "  void * atautoreleasepoolobj;\n";
6063*67e74705SXin Li   Preamble += "};\n";
6064*67e74705SXin Li 
6065*67e74705SXin Li   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6066*67e74705SXin Li   // as this avoids warning in any 64bit/32bit compilation model.
6067*67e74705SXin Li   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6068*67e74705SXin Li }
6069*67e74705SXin Li 
6070*67e74705SXin Li /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6071*67e74705SXin Li /// ivar offset.
RewriteIvarOffsetComputation(ObjCIvarDecl * ivar,std::string & Result)6072*67e74705SXin Li void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6073*67e74705SXin Li                                                          std::string &Result) {
6074*67e74705SXin Li   Result += "__OFFSETOFIVAR__(struct ";
6075*67e74705SXin Li   Result += ivar->getContainingInterface()->getNameAsString();
6076*67e74705SXin Li   if (LangOpts.MicrosoftExt)
6077*67e74705SXin Li     Result += "_IMPL";
6078*67e74705SXin Li   Result += ", ";
6079*67e74705SXin Li   if (ivar->isBitField())
6080*67e74705SXin Li     ObjCIvarBitfieldGroupDecl(ivar, Result);
6081*67e74705SXin Li   else
6082*67e74705SXin Li     Result += ivar->getNameAsString();
6083*67e74705SXin Li   Result += ")";
6084*67e74705SXin Li }
6085*67e74705SXin Li 
6086*67e74705SXin Li /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6087*67e74705SXin Li /// struct _prop_t {
6088*67e74705SXin Li ///   const char *name;
6089*67e74705SXin Li ///   char *attributes;
6090*67e74705SXin Li /// }
6091*67e74705SXin Li 
6092*67e74705SXin Li /// struct _prop_list_t {
6093*67e74705SXin Li ///   uint32_t entsize;      // sizeof(struct _prop_t)
6094*67e74705SXin Li ///   uint32_t count_of_properties;
6095*67e74705SXin Li ///   struct _prop_t prop_list[count_of_properties];
6096*67e74705SXin Li /// }
6097*67e74705SXin Li 
6098*67e74705SXin Li /// struct _protocol_t;
6099*67e74705SXin Li 
6100*67e74705SXin Li /// struct _protocol_list_t {
6101*67e74705SXin Li ///   long protocol_count;   // Note, this is 32/64 bit
6102*67e74705SXin Li ///   struct _protocol_t * protocol_list[protocol_count];
6103*67e74705SXin Li /// }
6104*67e74705SXin Li 
6105*67e74705SXin Li /// struct _objc_method {
6106*67e74705SXin Li ///   SEL _cmd;
6107*67e74705SXin Li ///   const char *method_type;
6108*67e74705SXin Li ///   char *_imp;
6109*67e74705SXin Li /// }
6110*67e74705SXin Li 
6111*67e74705SXin Li /// struct _method_list_t {
6112*67e74705SXin Li ///   uint32_t entsize;  // sizeof(struct _objc_method)
6113*67e74705SXin Li ///   uint32_t method_count;
6114*67e74705SXin Li ///   struct _objc_method method_list[method_count];
6115*67e74705SXin Li /// }
6116*67e74705SXin Li 
6117*67e74705SXin Li /// struct _protocol_t {
6118*67e74705SXin Li ///   id isa;  // NULL
6119*67e74705SXin Li ///   const char *protocol_name;
6120*67e74705SXin Li ///   const struct _protocol_list_t * protocol_list; // super protocols
6121*67e74705SXin Li ///   const struct method_list_t *instance_methods;
6122*67e74705SXin Li ///   const struct method_list_t *class_methods;
6123*67e74705SXin Li ///   const struct method_list_t *optionalInstanceMethods;
6124*67e74705SXin Li ///   const struct method_list_t *optionalClassMethods;
6125*67e74705SXin Li ///   const struct _prop_list_t * properties;
6126*67e74705SXin Li ///   const uint32_t size;  // sizeof(struct _protocol_t)
6127*67e74705SXin Li ///   const uint32_t flags;  // = 0
6128*67e74705SXin Li ///   const char ** extendedMethodTypes;
6129*67e74705SXin Li /// }
6130*67e74705SXin Li 
6131*67e74705SXin Li /// struct _ivar_t {
6132*67e74705SXin Li ///   unsigned long int *offset;  // pointer to ivar offset location
6133*67e74705SXin Li ///   const char *name;
6134*67e74705SXin Li ///   const char *type;
6135*67e74705SXin Li ///   uint32_t alignment;
6136*67e74705SXin Li ///   uint32_t size;
6137*67e74705SXin Li /// }
6138*67e74705SXin Li 
6139*67e74705SXin Li /// struct _ivar_list_t {
6140*67e74705SXin Li ///   uint32 entsize;  // sizeof(struct _ivar_t)
6141*67e74705SXin Li ///   uint32 count;
6142*67e74705SXin Li ///   struct _ivar_t list[count];
6143*67e74705SXin Li /// }
6144*67e74705SXin Li 
6145*67e74705SXin Li /// struct _class_ro_t {
6146*67e74705SXin Li ///   uint32_t flags;
6147*67e74705SXin Li ///   uint32_t instanceStart;
6148*67e74705SXin Li ///   uint32_t instanceSize;
6149*67e74705SXin Li ///   uint32_t reserved;  // only when building for 64bit targets
6150*67e74705SXin Li ///   const uint8_t *ivarLayout;
6151*67e74705SXin Li ///   const char *name;
6152*67e74705SXin Li ///   const struct _method_list_t *baseMethods;
6153*67e74705SXin Li ///   const struct _protocol_list_t *baseProtocols;
6154*67e74705SXin Li ///   const struct _ivar_list_t *ivars;
6155*67e74705SXin Li ///   const uint8_t *weakIvarLayout;
6156*67e74705SXin Li ///   const struct _prop_list_t *properties;
6157*67e74705SXin Li /// }
6158*67e74705SXin Li 
6159*67e74705SXin Li /// struct _class_t {
6160*67e74705SXin Li ///   struct _class_t *isa;
6161*67e74705SXin Li ///   struct _class_t *superclass;
6162*67e74705SXin Li ///   void *cache;
6163*67e74705SXin Li ///   IMP *vtable;
6164*67e74705SXin Li ///   struct _class_ro_t *ro;
6165*67e74705SXin Li /// }
6166*67e74705SXin Li 
6167*67e74705SXin Li /// struct _category_t {
6168*67e74705SXin Li ///   const char *name;
6169*67e74705SXin Li ///   struct _class_t *cls;
6170*67e74705SXin Li ///   const struct _method_list_t *instance_methods;
6171*67e74705SXin Li ///   const struct _method_list_t *class_methods;
6172*67e74705SXin Li ///   const struct _protocol_list_t *protocols;
6173*67e74705SXin Li ///   const struct _prop_list_t *properties;
6174*67e74705SXin Li /// }
6175*67e74705SXin Li 
6176*67e74705SXin Li /// MessageRefTy - LLVM for:
6177*67e74705SXin Li /// struct _message_ref_t {
6178*67e74705SXin Li ///   IMP messenger;
6179*67e74705SXin Li ///   SEL name;
6180*67e74705SXin Li /// };
6181*67e74705SXin Li 
6182*67e74705SXin Li /// SuperMessageRefTy - LLVM for:
6183*67e74705SXin Li /// struct _super_message_ref_t {
6184*67e74705SXin Li ///   SUPER_IMP messenger;
6185*67e74705SXin Li ///   SEL name;
6186*67e74705SXin Li /// };
6187*67e74705SXin Li 
WriteModernMetadataDeclarations(ASTContext * Context,std::string & Result)6188*67e74705SXin Li static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6189*67e74705SXin Li   static bool meta_data_declared = false;
6190*67e74705SXin Li   if (meta_data_declared)
6191*67e74705SXin Li     return;
6192*67e74705SXin Li 
6193*67e74705SXin Li   Result += "\nstruct _prop_t {\n";
6194*67e74705SXin Li   Result += "\tconst char *name;\n";
6195*67e74705SXin Li   Result += "\tconst char *attributes;\n";
6196*67e74705SXin Li   Result += "};\n";
6197*67e74705SXin Li 
6198*67e74705SXin Li   Result += "\nstruct _protocol_t;\n";
6199*67e74705SXin Li 
6200*67e74705SXin Li   Result += "\nstruct _objc_method {\n";
6201*67e74705SXin Li   Result += "\tstruct objc_selector * _cmd;\n";
6202*67e74705SXin Li   Result += "\tconst char *method_type;\n";
6203*67e74705SXin Li   Result += "\tvoid  *_imp;\n";
6204*67e74705SXin Li   Result += "};\n";
6205*67e74705SXin Li 
6206*67e74705SXin Li   Result += "\nstruct _protocol_t {\n";
6207*67e74705SXin Li   Result += "\tvoid * isa;  // NULL\n";
6208*67e74705SXin Li   Result += "\tconst char *protocol_name;\n";
6209*67e74705SXin Li   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6210*67e74705SXin Li   Result += "\tconst struct method_list_t *instance_methods;\n";
6211*67e74705SXin Li   Result += "\tconst struct method_list_t *class_methods;\n";
6212*67e74705SXin Li   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6213*67e74705SXin Li   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6214*67e74705SXin Li   Result += "\tconst struct _prop_list_t * properties;\n";
6215*67e74705SXin Li   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6216*67e74705SXin Li   Result += "\tconst unsigned int flags;  // = 0\n";
6217*67e74705SXin Li   Result += "\tconst char ** extendedMethodTypes;\n";
6218*67e74705SXin Li   Result += "};\n";
6219*67e74705SXin Li 
6220*67e74705SXin Li   Result += "\nstruct _ivar_t {\n";
6221*67e74705SXin Li   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6222*67e74705SXin Li   Result += "\tconst char *name;\n";
6223*67e74705SXin Li   Result += "\tconst char *type;\n";
6224*67e74705SXin Li   Result += "\tunsigned int alignment;\n";
6225*67e74705SXin Li   Result += "\tunsigned int  size;\n";
6226*67e74705SXin Li   Result += "};\n";
6227*67e74705SXin Li 
6228*67e74705SXin Li   Result += "\nstruct _class_ro_t {\n";
6229*67e74705SXin Li   Result += "\tunsigned int flags;\n";
6230*67e74705SXin Li   Result += "\tunsigned int instanceStart;\n";
6231*67e74705SXin Li   Result += "\tunsigned int instanceSize;\n";
6232*67e74705SXin Li   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6233*67e74705SXin Li   if (Triple.getArch() == llvm::Triple::x86_64)
6234*67e74705SXin Li     Result += "\tunsigned int reserved;\n";
6235*67e74705SXin Li   Result += "\tconst unsigned char *ivarLayout;\n";
6236*67e74705SXin Li   Result += "\tconst char *name;\n";
6237*67e74705SXin Li   Result += "\tconst struct _method_list_t *baseMethods;\n";
6238*67e74705SXin Li   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6239*67e74705SXin Li   Result += "\tconst struct _ivar_list_t *ivars;\n";
6240*67e74705SXin Li   Result += "\tconst unsigned char *weakIvarLayout;\n";
6241*67e74705SXin Li   Result += "\tconst struct _prop_list_t *properties;\n";
6242*67e74705SXin Li   Result += "};\n";
6243*67e74705SXin Li 
6244*67e74705SXin Li   Result += "\nstruct _class_t {\n";
6245*67e74705SXin Li   Result += "\tstruct _class_t *isa;\n";
6246*67e74705SXin Li   Result += "\tstruct _class_t *superclass;\n";
6247*67e74705SXin Li   Result += "\tvoid *cache;\n";
6248*67e74705SXin Li   Result += "\tvoid *vtable;\n";
6249*67e74705SXin Li   Result += "\tstruct _class_ro_t *ro;\n";
6250*67e74705SXin Li   Result += "};\n";
6251*67e74705SXin Li 
6252*67e74705SXin Li   Result += "\nstruct _category_t {\n";
6253*67e74705SXin Li   Result += "\tconst char *name;\n";
6254*67e74705SXin Li   Result += "\tstruct _class_t *cls;\n";
6255*67e74705SXin Li   Result += "\tconst struct _method_list_t *instance_methods;\n";
6256*67e74705SXin Li   Result += "\tconst struct _method_list_t *class_methods;\n";
6257*67e74705SXin Li   Result += "\tconst struct _protocol_list_t *protocols;\n";
6258*67e74705SXin Li   Result += "\tconst struct _prop_list_t *properties;\n";
6259*67e74705SXin Li   Result += "};\n";
6260*67e74705SXin Li 
6261*67e74705SXin Li   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6262*67e74705SXin Li   Result += "#pragma warning(disable:4273)\n";
6263*67e74705SXin Li   meta_data_declared = true;
6264*67e74705SXin Li }
6265*67e74705SXin Li 
Write_protocol_list_t_TypeDecl(std::string & Result,long super_protocol_count)6266*67e74705SXin Li static void Write_protocol_list_t_TypeDecl(std::string &Result,
6267*67e74705SXin Li                                            long super_protocol_count) {
6268*67e74705SXin Li   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6269*67e74705SXin Li   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6270*67e74705SXin Li   Result += "\tstruct _protocol_t *super_protocols[";
6271*67e74705SXin Li   Result += utostr(super_protocol_count); Result += "];\n";
6272*67e74705SXin Li   Result += "}";
6273*67e74705SXin Li }
6274*67e74705SXin Li 
Write_method_list_t_TypeDecl(std::string & Result,unsigned int method_count)6275*67e74705SXin Li static void Write_method_list_t_TypeDecl(std::string &Result,
6276*67e74705SXin Li                                          unsigned int method_count) {
6277*67e74705SXin Li   Result += "struct /*_method_list_t*/"; Result += " {\n";
6278*67e74705SXin Li   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6279*67e74705SXin Li   Result += "\tunsigned int method_count;\n";
6280*67e74705SXin Li   Result += "\tstruct _objc_method method_list[";
6281*67e74705SXin Li   Result += utostr(method_count); Result += "];\n";
6282*67e74705SXin Li   Result += "}";
6283*67e74705SXin Li }
6284*67e74705SXin Li 
Write__prop_list_t_TypeDecl(std::string & Result,unsigned int property_count)6285*67e74705SXin Li static void Write__prop_list_t_TypeDecl(std::string &Result,
6286*67e74705SXin Li                                         unsigned int property_count) {
6287*67e74705SXin Li   Result += "struct /*_prop_list_t*/"; Result += " {\n";
6288*67e74705SXin Li   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6289*67e74705SXin Li   Result += "\tunsigned int count_of_properties;\n";
6290*67e74705SXin Li   Result += "\tstruct _prop_t prop_list[";
6291*67e74705SXin Li   Result += utostr(property_count); Result += "];\n";
6292*67e74705SXin Li   Result += "}";
6293*67e74705SXin Li }
6294*67e74705SXin Li 
Write__ivar_list_t_TypeDecl(std::string & Result,unsigned int ivar_count)6295*67e74705SXin Li static void Write__ivar_list_t_TypeDecl(std::string &Result,
6296*67e74705SXin Li                                         unsigned int ivar_count) {
6297*67e74705SXin Li   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6298*67e74705SXin Li   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6299*67e74705SXin Li   Result += "\tunsigned int count;\n";
6300*67e74705SXin Li   Result += "\tstruct _ivar_t ivar_list[";
6301*67e74705SXin Li   Result += utostr(ivar_count); Result += "];\n";
6302*67e74705SXin Li   Result += "}";
6303*67e74705SXin Li }
6304*67e74705SXin Li 
Write_protocol_list_initializer(ASTContext * Context,std::string & Result,ArrayRef<ObjCProtocolDecl * > SuperProtocols,StringRef VarName,StringRef ProtocolName)6305*67e74705SXin Li static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6306*67e74705SXin Li                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6307*67e74705SXin Li                                             StringRef VarName,
6308*67e74705SXin Li                                             StringRef ProtocolName) {
6309*67e74705SXin Li   if (SuperProtocols.size() > 0) {
6310*67e74705SXin Li     Result += "\nstatic ";
6311*67e74705SXin Li     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6312*67e74705SXin Li     Result += " "; Result += VarName;
6313*67e74705SXin Li     Result += ProtocolName;
6314*67e74705SXin Li     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6315*67e74705SXin Li     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6316*67e74705SXin Li     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6317*67e74705SXin Li       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6318*67e74705SXin Li       Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6319*67e74705SXin Li       Result += SuperPD->getNameAsString();
6320*67e74705SXin Li       if (i == e-1)
6321*67e74705SXin Li         Result += "\n};\n";
6322*67e74705SXin Li       else
6323*67e74705SXin Li         Result += ",\n";
6324*67e74705SXin Li     }
6325*67e74705SXin Li   }
6326*67e74705SXin Li }
6327*67e74705SXin Li 
Write_method_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCMethodDecl * > Methods,StringRef VarName,StringRef TopLevelDeclName,bool MethodImpl)6328*67e74705SXin Li static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6329*67e74705SXin Li                                             ASTContext *Context, std::string &Result,
6330*67e74705SXin Li                                             ArrayRef<ObjCMethodDecl *> Methods,
6331*67e74705SXin Li                                             StringRef VarName,
6332*67e74705SXin Li                                             StringRef TopLevelDeclName,
6333*67e74705SXin Li                                             bool MethodImpl) {
6334*67e74705SXin Li   if (Methods.size() > 0) {
6335*67e74705SXin Li     Result += "\nstatic ";
6336*67e74705SXin Li     Write_method_list_t_TypeDecl(Result, Methods.size());
6337*67e74705SXin Li     Result += " "; Result += VarName;
6338*67e74705SXin Li     Result += TopLevelDeclName;
6339*67e74705SXin Li     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6340*67e74705SXin Li     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6341*67e74705SXin Li     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6342*67e74705SXin Li     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6343*67e74705SXin Li       ObjCMethodDecl *MD = Methods[i];
6344*67e74705SXin Li       if (i == 0)
6345*67e74705SXin Li         Result += "\t{{(struct objc_selector *)\"";
6346*67e74705SXin Li       else
6347*67e74705SXin Li         Result += "\t{(struct objc_selector *)\"";
6348*67e74705SXin Li       Result += (MD)->getSelector().getAsString(); Result += "\"";
6349*67e74705SXin Li       Result += ", ";
6350*67e74705SXin Li       std::string MethodTypeString;
6351*67e74705SXin Li       Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6352*67e74705SXin Li       Result += "\""; Result += MethodTypeString; Result += "\"";
6353*67e74705SXin Li       Result += ", ";
6354*67e74705SXin Li       if (!MethodImpl)
6355*67e74705SXin Li         Result += "0";
6356*67e74705SXin Li       else {
6357*67e74705SXin Li         Result += "(void *)";
6358*67e74705SXin Li         Result += RewriteObj.MethodInternalNames[MD];
6359*67e74705SXin Li       }
6360*67e74705SXin Li       if (i  == e-1)
6361*67e74705SXin Li         Result += "}}\n";
6362*67e74705SXin Li       else
6363*67e74705SXin Li         Result += "},\n";
6364*67e74705SXin Li     }
6365*67e74705SXin Li     Result += "};\n";
6366*67e74705SXin Li   }
6367*67e74705SXin Li }
6368*67e74705SXin Li 
Write_prop_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCPropertyDecl * > Properties,const Decl * Container,StringRef VarName,StringRef ProtocolName)6369*67e74705SXin Li static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6370*67e74705SXin Li                                            ASTContext *Context, std::string &Result,
6371*67e74705SXin Li                                            ArrayRef<ObjCPropertyDecl *> Properties,
6372*67e74705SXin Li                                            const Decl *Container,
6373*67e74705SXin Li                                            StringRef VarName,
6374*67e74705SXin Li                                            StringRef ProtocolName) {
6375*67e74705SXin Li   if (Properties.size() > 0) {
6376*67e74705SXin Li     Result += "\nstatic ";
6377*67e74705SXin Li     Write__prop_list_t_TypeDecl(Result, Properties.size());
6378*67e74705SXin Li     Result += " "; Result += VarName;
6379*67e74705SXin Li     Result += ProtocolName;
6380*67e74705SXin Li     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6381*67e74705SXin Li     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6382*67e74705SXin Li     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6383*67e74705SXin Li     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6384*67e74705SXin Li       ObjCPropertyDecl *PropDecl = Properties[i];
6385*67e74705SXin Li       if (i == 0)
6386*67e74705SXin Li         Result += "\t{{\"";
6387*67e74705SXin Li       else
6388*67e74705SXin Li         Result += "\t{\"";
6389*67e74705SXin Li       Result += PropDecl->getName(); Result += "\",";
6390*67e74705SXin Li       std::string PropertyTypeString, QuotePropertyTypeString;
6391*67e74705SXin Li       Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6392*67e74705SXin Li       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6393*67e74705SXin Li       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6394*67e74705SXin Li       if (i  == e-1)
6395*67e74705SXin Li         Result += "}}\n";
6396*67e74705SXin Li       else
6397*67e74705SXin Li         Result += "},\n";
6398*67e74705SXin Li     }
6399*67e74705SXin Li     Result += "};\n";
6400*67e74705SXin Li   }
6401*67e74705SXin Li }
6402*67e74705SXin Li 
6403*67e74705SXin Li // Metadata flags
6404*67e74705SXin Li enum MetaDataDlags {
6405*67e74705SXin Li   CLS = 0x0,
6406*67e74705SXin Li   CLS_META = 0x1,
6407*67e74705SXin Li   CLS_ROOT = 0x2,
6408*67e74705SXin Li   OBJC2_CLS_HIDDEN = 0x10,
6409*67e74705SXin Li   CLS_EXCEPTION = 0x20,
6410*67e74705SXin Li 
6411*67e74705SXin Li   /// (Obsolete) ARC-specific: this class has a .release_ivars method
6412*67e74705SXin Li   CLS_HAS_IVAR_RELEASER = 0x40,
6413*67e74705SXin Li   /// class was compiled with -fobjc-arr
6414*67e74705SXin Li   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6415*67e74705SXin Li };
6416*67e74705SXin Li 
Write__class_ro_t_initializer(ASTContext * Context,std::string & Result,unsigned int flags,const std::string & InstanceStart,const std::string & InstanceSize,ArrayRef<ObjCMethodDecl * > baseMethods,ArrayRef<ObjCProtocolDecl * > baseProtocols,ArrayRef<ObjCIvarDecl * > ivars,ArrayRef<ObjCPropertyDecl * > Properties,StringRef VarName,StringRef ClassName)6417*67e74705SXin Li static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6418*67e74705SXin Li                                           unsigned int flags,
6419*67e74705SXin Li                                           const std::string &InstanceStart,
6420*67e74705SXin Li                                           const std::string &InstanceSize,
6421*67e74705SXin Li                                           ArrayRef<ObjCMethodDecl *>baseMethods,
6422*67e74705SXin Li                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
6423*67e74705SXin Li                                           ArrayRef<ObjCIvarDecl *>ivars,
6424*67e74705SXin Li                                           ArrayRef<ObjCPropertyDecl *>Properties,
6425*67e74705SXin Li                                           StringRef VarName,
6426*67e74705SXin Li                                           StringRef ClassName) {
6427*67e74705SXin Li   Result += "\nstatic struct _class_ro_t ";
6428*67e74705SXin Li   Result += VarName; Result += ClassName;
6429*67e74705SXin Li   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6430*67e74705SXin Li   Result += "\t";
6431*67e74705SXin Li   Result += llvm::utostr(flags); Result += ", ";
6432*67e74705SXin Li   Result += InstanceStart; Result += ", ";
6433*67e74705SXin Li   Result += InstanceSize; Result += ", \n";
6434*67e74705SXin Li   Result += "\t";
6435*67e74705SXin Li   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6436*67e74705SXin Li   if (Triple.getArch() == llvm::Triple::x86_64)
6437*67e74705SXin Li     // uint32_t const reserved; // only when building for 64bit targets
6438*67e74705SXin Li     Result += "(unsigned int)0, \n\t";
6439*67e74705SXin Li   // const uint8_t * const ivarLayout;
6440*67e74705SXin Li   Result += "0, \n\t";
6441*67e74705SXin Li   Result += "\""; Result += ClassName; Result += "\",\n\t";
6442*67e74705SXin Li   bool metaclass = ((flags & CLS_META) != 0);
6443*67e74705SXin Li   if (baseMethods.size() > 0) {
6444*67e74705SXin Li     Result += "(const struct _method_list_t *)&";
6445*67e74705SXin Li     if (metaclass)
6446*67e74705SXin Li       Result += "_OBJC_$_CLASS_METHODS_";
6447*67e74705SXin Li     else
6448*67e74705SXin Li       Result += "_OBJC_$_INSTANCE_METHODS_";
6449*67e74705SXin Li     Result += ClassName;
6450*67e74705SXin Li     Result += ",\n\t";
6451*67e74705SXin Li   }
6452*67e74705SXin Li   else
6453*67e74705SXin Li     Result += "0, \n\t";
6454*67e74705SXin Li 
6455*67e74705SXin Li   if (!metaclass && baseProtocols.size() > 0) {
6456*67e74705SXin Li     Result += "(const struct _objc_protocol_list *)&";
6457*67e74705SXin Li     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6458*67e74705SXin Li     Result += ",\n\t";
6459*67e74705SXin Li   }
6460*67e74705SXin Li   else
6461*67e74705SXin Li     Result += "0, \n\t";
6462*67e74705SXin Li 
6463*67e74705SXin Li   if (!metaclass && ivars.size() > 0) {
6464*67e74705SXin Li     Result += "(const struct _ivar_list_t *)&";
6465*67e74705SXin Li     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6466*67e74705SXin Li     Result += ",\n\t";
6467*67e74705SXin Li   }
6468*67e74705SXin Li   else
6469*67e74705SXin Li     Result += "0, \n\t";
6470*67e74705SXin Li 
6471*67e74705SXin Li   // weakIvarLayout
6472*67e74705SXin Li   Result += "0, \n\t";
6473*67e74705SXin Li   if (!metaclass && Properties.size() > 0) {
6474*67e74705SXin Li     Result += "(const struct _prop_list_t *)&";
6475*67e74705SXin Li     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6476*67e74705SXin Li     Result += ",\n";
6477*67e74705SXin Li   }
6478*67e74705SXin Li   else
6479*67e74705SXin Li     Result += "0, \n";
6480*67e74705SXin Li 
6481*67e74705SXin Li   Result += "};\n";
6482*67e74705SXin Li }
6483*67e74705SXin Li 
Write_class_t(ASTContext * Context,std::string & Result,StringRef VarName,const ObjCInterfaceDecl * CDecl,bool metaclass)6484*67e74705SXin Li static void Write_class_t(ASTContext *Context, std::string &Result,
6485*67e74705SXin Li                           StringRef VarName,
6486*67e74705SXin Li                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
6487*67e74705SXin Li   bool rootClass = (!CDecl->getSuperClass());
6488*67e74705SXin Li   const ObjCInterfaceDecl *RootClass = CDecl;
6489*67e74705SXin Li 
6490*67e74705SXin Li   if (!rootClass) {
6491*67e74705SXin Li     // Find the Root class
6492*67e74705SXin Li     RootClass = CDecl->getSuperClass();
6493*67e74705SXin Li     while (RootClass->getSuperClass()) {
6494*67e74705SXin Li       RootClass = RootClass->getSuperClass();
6495*67e74705SXin Li     }
6496*67e74705SXin Li   }
6497*67e74705SXin Li 
6498*67e74705SXin Li   if (metaclass && rootClass) {
6499*67e74705SXin Li     // Need to handle a case of use of forward declaration.
6500*67e74705SXin Li     Result += "\n";
6501*67e74705SXin Li     Result += "extern \"C\" ";
6502*67e74705SXin Li     if (CDecl->getImplementation())
6503*67e74705SXin Li       Result += "__declspec(dllexport) ";
6504*67e74705SXin Li     else
6505*67e74705SXin Li       Result += "__declspec(dllimport) ";
6506*67e74705SXin Li 
6507*67e74705SXin Li     Result += "struct _class_t OBJC_CLASS_$_";
6508*67e74705SXin Li     Result += CDecl->getNameAsString();
6509*67e74705SXin Li     Result += ";\n";
6510*67e74705SXin Li   }
6511*67e74705SXin Li   // Also, for possibility of 'super' metadata class not having been defined yet.
6512*67e74705SXin Li   if (!rootClass) {
6513*67e74705SXin Li     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6514*67e74705SXin Li     Result += "\n";
6515*67e74705SXin Li     Result += "extern \"C\" ";
6516*67e74705SXin Li     if (SuperClass->getImplementation())
6517*67e74705SXin Li       Result += "__declspec(dllexport) ";
6518*67e74705SXin Li     else
6519*67e74705SXin Li       Result += "__declspec(dllimport) ";
6520*67e74705SXin Li 
6521*67e74705SXin Li     Result += "struct _class_t ";
6522*67e74705SXin Li     Result += VarName;
6523*67e74705SXin Li     Result += SuperClass->getNameAsString();
6524*67e74705SXin Li     Result += ";\n";
6525*67e74705SXin Li 
6526*67e74705SXin Li     if (metaclass && RootClass != SuperClass) {
6527*67e74705SXin Li       Result += "extern \"C\" ";
6528*67e74705SXin Li       if (RootClass->getImplementation())
6529*67e74705SXin Li         Result += "__declspec(dllexport) ";
6530*67e74705SXin Li       else
6531*67e74705SXin Li         Result += "__declspec(dllimport) ";
6532*67e74705SXin Li 
6533*67e74705SXin Li       Result += "struct _class_t ";
6534*67e74705SXin Li       Result += VarName;
6535*67e74705SXin Li       Result += RootClass->getNameAsString();
6536*67e74705SXin Li       Result += ";\n";
6537*67e74705SXin Li     }
6538*67e74705SXin Li   }
6539*67e74705SXin Li 
6540*67e74705SXin Li   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6541*67e74705SXin Li   Result += VarName; Result += CDecl->getNameAsString();
6542*67e74705SXin Li   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6543*67e74705SXin Li   Result += "\t";
6544*67e74705SXin Li   if (metaclass) {
6545*67e74705SXin Li     if (!rootClass) {
6546*67e74705SXin Li       Result += "0, // &"; Result += VarName;
6547*67e74705SXin Li       Result += RootClass->getNameAsString();
6548*67e74705SXin Li       Result += ",\n\t";
6549*67e74705SXin Li       Result += "0, // &"; Result += VarName;
6550*67e74705SXin Li       Result += CDecl->getSuperClass()->getNameAsString();
6551*67e74705SXin Li       Result += ",\n\t";
6552*67e74705SXin Li     }
6553*67e74705SXin Li     else {
6554*67e74705SXin Li       Result += "0, // &"; Result += VarName;
6555*67e74705SXin Li       Result += CDecl->getNameAsString();
6556*67e74705SXin Li       Result += ",\n\t";
6557*67e74705SXin Li       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6558*67e74705SXin Li       Result += ",\n\t";
6559*67e74705SXin Li     }
6560*67e74705SXin Li   }
6561*67e74705SXin Li   else {
6562*67e74705SXin Li     Result += "0, // &OBJC_METACLASS_$_";
6563*67e74705SXin Li     Result += CDecl->getNameAsString();
6564*67e74705SXin Li     Result += ",\n\t";
6565*67e74705SXin Li     if (!rootClass) {
6566*67e74705SXin Li       Result += "0, // &"; Result += VarName;
6567*67e74705SXin Li       Result += CDecl->getSuperClass()->getNameAsString();
6568*67e74705SXin Li       Result += ",\n\t";
6569*67e74705SXin Li     }
6570*67e74705SXin Li     else
6571*67e74705SXin Li       Result += "0,\n\t";
6572*67e74705SXin Li   }
6573*67e74705SXin Li   Result += "0, // (void *)&_objc_empty_cache,\n\t";
6574*67e74705SXin Li   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6575*67e74705SXin Li   if (metaclass)
6576*67e74705SXin Li     Result += "&_OBJC_METACLASS_RO_$_";
6577*67e74705SXin Li   else
6578*67e74705SXin Li     Result += "&_OBJC_CLASS_RO_$_";
6579*67e74705SXin Li   Result += CDecl->getNameAsString();
6580*67e74705SXin Li   Result += ",\n};\n";
6581*67e74705SXin Li 
6582*67e74705SXin Li   // Add static function to initialize some of the meta-data fields.
6583*67e74705SXin Li   // avoid doing it twice.
6584*67e74705SXin Li   if (metaclass)
6585*67e74705SXin Li     return;
6586*67e74705SXin Li 
6587*67e74705SXin Li   const ObjCInterfaceDecl *SuperClass =
6588*67e74705SXin Li     rootClass ? CDecl : CDecl->getSuperClass();
6589*67e74705SXin Li 
6590*67e74705SXin Li   Result += "static void OBJC_CLASS_SETUP_$_";
6591*67e74705SXin Li   Result += CDecl->getNameAsString();
6592*67e74705SXin Li   Result += "(void ) {\n";
6593*67e74705SXin Li   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6594*67e74705SXin Li   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6595*67e74705SXin Li   Result += RootClass->getNameAsString(); Result += ";\n";
6596*67e74705SXin Li 
6597*67e74705SXin Li   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6598*67e74705SXin Li   Result += ".superclass = ";
6599*67e74705SXin Li   if (rootClass)
6600*67e74705SXin Li     Result += "&OBJC_CLASS_$_";
6601*67e74705SXin Li   else
6602*67e74705SXin Li      Result += "&OBJC_METACLASS_$_";
6603*67e74705SXin Li 
6604*67e74705SXin Li   Result += SuperClass->getNameAsString(); Result += ";\n";
6605*67e74705SXin Li 
6606*67e74705SXin Li   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6607*67e74705SXin Li   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6608*67e74705SXin Li 
6609*67e74705SXin Li   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6610*67e74705SXin Li   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6611*67e74705SXin Li   Result += CDecl->getNameAsString(); Result += ";\n";
6612*67e74705SXin Li 
6613*67e74705SXin Li   if (!rootClass) {
6614*67e74705SXin Li     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6615*67e74705SXin Li     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6616*67e74705SXin Li     Result += SuperClass->getNameAsString(); Result += ";\n";
6617*67e74705SXin Li   }
6618*67e74705SXin Li 
6619*67e74705SXin Li   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6620*67e74705SXin Li   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6621*67e74705SXin Li   Result += "}\n";
6622*67e74705SXin Li }
6623*67e74705SXin Li 
Write_category_t(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ObjCCategoryDecl * CatDecl,ObjCInterfaceDecl * ClassDecl,ArrayRef<ObjCMethodDecl * > InstanceMethods,ArrayRef<ObjCMethodDecl * > ClassMethods,ArrayRef<ObjCProtocolDecl * > RefedProtocols,ArrayRef<ObjCPropertyDecl * > ClassProperties)6624*67e74705SXin Li static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6625*67e74705SXin Li                              std::string &Result,
6626*67e74705SXin Li                              ObjCCategoryDecl *CatDecl,
6627*67e74705SXin Li                              ObjCInterfaceDecl *ClassDecl,
6628*67e74705SXin Li                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
6629*67e74705SXin Li                              ArrayRef<ObjCMethodDecl *> ClassMethods,
6630*67e74705SXin Li                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6631*67e74705SXin Li                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6632*67e74705SXin Li   StringRef CatName = CatDecl->getName();
6633*67e74705SXin Li   StringRef ClassName = ClassDecl->getName();
6634*67e74705SXin Li   // must declare an extern class object in case this class is not implemented
6635*67e74705SXin Li   // in this TU.
6636*67e74705SXin Li   Result += "\n";
6637*67e74705SXin Li   Result += "extern \"C\" ";
6638*67e74705SXin Li   if (ClassDecl->getImplementation())
6639*67e74705SXin Li     Result += "__declspec(dllexport) ";
6640*67e74705SXin Li   else
6641*67e74705SXin Li     Result += "__declspec(dllimport) ";
6642*67e74705SXin Li 
6643*67e74705SXin Li   Result += "struct _class_t ";
6644*67e74705SXin Li   Result += "OBJC_CLASS_$_"; Result += ClassName;
6645*67e74705SXin Li   Result += ";\n";
6646*67e74705SXin Li 
6647*67e74705SXin Li   Result += "\nstatic struct _category_t ";
6648*67e74705SXin Li   Result += "_OBJC_$_CATEGORY_";
6649*67e74705SXin Li   Result += ClassName; Result += "_$_"; Result += CatName;
6650*67e74705SXin Li   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6651*67e74705SXin Li   Result += "{\n";
6652*67e74705SXin Li   Result += "\t\""; Result += ClassName; Result += "\",\n";
6653*67e74705SXin Li   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6654*67e74705SXin Li   Result += ",\n";
6655*67e74705SXin Li   if (InstanceMethods.size() > 0) {
6656*67e74705SXin Li     Result += "\t(const struct _method_list_t *)&";
6657*67e74705SXin Li     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6658*67e74705SXin Li     Result += ClassName; Result += "_$_"; Result += CatName;
6659*67e74705SXin Li     Result += ",\n";
6660*67e74705SXin Li   }
6661*67e74705SXin Li   else
6662*67e74705SXin Li     Result += "\t0,\n";
6663*67e74705SXin Li 
6664*67e74705SXin Li   if (ClassMethods.size() > 0) {
6665*67e74705SXin Li     Result += "\t(const struct _method_list_t *)&";
6666*67e74705SXin Li     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6667*67e74705SXin Li     Result += ClassName; Result += "_$_"; Result += CatName;
6668*67e74705SXin Li     Result += ",\n";
6669*67e74705SXin Li   }
6670*67e74705SXin Li   else
6671*67e74705SXin Li     Result += "\t0,\n";
6672*67e74705SXin Li 
6673*67e74705SXin Li   if (RefedProtocols.size() > 0) {
6674*67e74705SXin Li     Result += "\t(const struct _protocol_list_t *)&";
6675*67e74705SXin Li     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6676*67e74705SXin Li     Result += ClassName; Result += "_$_"; Result += CatName;
6677*67e74705SXin Li     Result += ",\n";
6678*67e74705SXin Li   }
6679*67e74705SXin Li   else
6680*67e74705SXin Li     Result += "\t0,\n";
6681*67e74705SXin Li 
6682*67e74705SXin Li   if (ClassProperties.size() > 0) {
6683*67e74705SXin Li     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6684*67e74705SXin Li     Result += ClassName; Result += "_$_"; Result += CatName;
6685*67e74705SXin Li     Result += ",\n";
6686*67e74705SXin Li   }
6687*67e74705SXin Li   else
6688*67e74705SXin Li     Result += "\t0,\n";
6689*67e74705SXin Li 
6690*67e74705SXin Li   Result += "};\n";
6691*67e74705SXin Li 
6692*67e74705SXin Li   // Add static function to initialize the class pointer in the category structure.
6693*67e74705SXin Li   Result += "static void OBJC_CATEGORY_SETUP_$_";
6694*67e74705SXin Li   Result += ClassDecl->getNameAsString();
6695*67e74705SXin Li   Result += "_$_";
6696*67e74705SXin Li   Result += CatName;
6697*67e74705SXin Li   Result += "(void ) {\n";
6698*67e74705SXin Li   Result += "\t_OBJC_$_CATEGORY_";
6699*67e74705SXin Li   Result += ClassDecl->getNameAsString();
6700*67e74705SXin Li   Result += "_$_";
6701*67e74705SXin Li   Result += CatName;
6702*67e74705SXin Li   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6703*67e74705SXin Li   Result += ";\n}\n";
6704*67e74705SXin Li }
6705*67e74705SXin Li 
Write__extendedMethodTypes_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCMethodDecl * > Methods,StringRef VarName,StringRef ProtocolName)6706*67e74705SXin Li static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6707*67e74705SXin Li                                            ASTContext *Context, std::string &Result,
6708*67e74705SXin Li                                            ArrayRef<ObjCMethodDecl *> Methods,
6709*67e74705SXin Li                                            StringRef VarName,
6710*67e74705SXin Li                                            StringRef ProtocolName) {
6711*67e74705SXin Li   if (Methods.size() == 0)
6712*67e74705SXin Li     return;
6713*67e74705SXin Li 
6714*67e74705SXin Li   Result += "\nstatic const char *";
6715*67e74705SXin Li   Result += VarName; Result += ProtocolName;
6716*67e74705SXin Li   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6717*67e74705SXin Li   Result += "{\n";
6718*67e74705SXin Li   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6719*67e74705SXin Li     ObjCMethodDecl *MD = Methods[i];
6720*67e74705SXin Li     std::string MethodTypeString, QuoteMethodTypeString;
6721*67e74705SXin Li     Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6722*67e74705SXin Li     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6723*67e74705SXin Li     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6724*67e74705SXin Li     if (i == e-1)
6725*67e74705SXin Li       Result += "\n};\n";
6726*67e74705SXin Li     else {
6727*67e74705SXin Li       Result += ",\n";
6728*67e74705SXin Li     }
6729*67e74705SXin Li   }
6730*67e74705SXin Li }
6731*67e74705SXin Li 
Write_IvarOffsetVar(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCIvarDecl * > Ivars,ObjCInterfaceDecl * CDecl)6732*67e74705SXin Li static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6733*67e74705SXin Li                                 ASTContext *Context,
6734*67e74705SXin Li                                 std::string &Result,
6735*67e74705SXin Li                                 ArrayRef<ObjCIvarDecl *> Ivars,
6736*67e74705SXin Li                                 ObjCInterfaceDecl *CDecl) {
6737*67e74705SXin Li   // FIXME. visibilty of offset symbols may have to be set; for Darwin
6738*67e74705SXin Li   // this is what happens:
6739*67e74705SXin Li   /**
6740*67e74705SXin Li    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6741*67e74705SXin Li        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6742*67e74705SXin Li        Class->getVisibility() == HiddenVisibility)
6743*67e74705SXin Li      Visibility shoud be: HiddenVisibility;
6744*67e74705SXin Li    else
6745*67e74705SXin Li      Visibility shoud be: DefaultVisibility;
6746*67e74705SXin Li   */
6747*67e74705SXin Li 
6748*67e74705SXin Li   Result += "\n";
6749*67e74705SXin Li   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6750*67e74705SXin Li     ObjCIvarDecl *IvarDecl = Ivars[i];
6751*67e74705SXin Li     if (Context->getLangOpts().MicrosoftExt)
6752*67e74705SXin Li       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6753*67e74705SXin Li 
6754*67e74705SXin Li     if (!Context->getLangOpts().MicrosoftExt ||
6755*67e74705SXin Li         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6756*67e74705SXin Li         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6757*67e74705SXin Li       Result += "extern \"C\" unsigned long int ";
6758*67e74705SXin Li     else
6759*67e74705SXin Li       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6760*67e74705SXin Li     if (Ivars[i]->isBitField())
6761*67e74705SXin Li       RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6762*67e74705SXin Li     else
6763*67e74705SXin Li       WriteInternalIvarName(CDecl, IvarDecl, Result);
6764*67e74705SXin Li     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6765*67e74705SXin Li     Result += " = ";
6766*67e74705SXin Li     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6767*67e74705SXin Li     Result += ";\n";
6768*67e74705SXin Li     if (Ivars[i]->isBitField()) {
6769*67e74705SXin Li       // skip over rest of the ivar bitfields.
6770*67e74705SXin Li       SKIP_BITFIELDS(i , e, Ivars);
6771*67e74705SXin Li     }
6772*67e74705SXin Li   }
6773*67e74705SXin Li }
6774*67e74705SXin Li 
Write__ivar_list_t_initializer(RewriteModernObjC & RewriteObj,ASTContext * Context,std::string & Result,ArrayRef<ObjCIvarDecl * > OriginalIvars,StringRef VarName,ObjCInterfaceDecl * CDecl)6775*67e74705SXin Li static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6776*67e74705SXin Li                                            ASTContext *Context, std::string &Result,
6777*67e74705SXin Li                                            ArrayRef<ObjCIvarDecl *> OriginalIvars,
6778*67e74705SXin Li                                            StringRef VarName,
6779*67e74705SXin Li                                            ObjCInterfaceDecl *CDecl) {
6780*67e74705SXin Li   if (OriginalIvars.size() > 0) {
6781*67e74705SXin Li     Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6782*67e74705SXin Li     SmallVector<ObjCIvarDecl *, 8> Ivars;
6783*67e74705SXin Li     // strip off all but the first ivar bitfield from each group of ivars.
6784*67e74705SXin Li     // Such ivars in the ivar list table will be replaced by their grouping struct
6785*67e74705SXin Li     // 'ivar'.
6786*67e74705SXin Li     for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6787*67e74705SXin Li       if (OriginalIvars[i]->isBitField()) {
6788*67e74705SXin Li         Ivars.push_back(OriginalIvars[i]);
6789*67e74705SXin Li         // skip over rest of the ivar bitfields.
6790*67e74705SXin Li         SKIP_BITFIELDS(i , e, OriginalIvars);
6791*67e74705SXin Li       }
6792*67e74705SXin Li       else
6793*67e74705SXin Li         Ivars.push_back(OriginalIvars[i]);
6794*67e74705SXin Li     }
6795*67e74705SXin Li 
6796*67e74705SXin Li     Result += "\nstatic ";
6797*67e74705SXin Li     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6798*67e74705SXin Li     Result += " "; Result += VarName;
6799*67e74705SXin Li     Result += CDecl->getNameAsString();
6800*67e74705SXin Li     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6801*67e74705SXin Li     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6802*67e74705SXin Li     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6803*67e74705SXin Li     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6804*67e74705SXin Li       ObjCIvarDecl *IvarDecl = Ivars[i];
6805*67e74705SXin Li       if (i == 0)
6806*67e74705SXin Li         Result += "\t{{";
6807*67e74705SXin Li       else
6808*67e74705SXin Li         Result += "\t {";
6809*67e74705SXin Li       Result += "(unsigned long int *)&";
6810*67e74705SXin Li       if (Ivars[i]->isBitField())
6811*67e74705SXin Li         RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6812*67e74705SXin Li       else
6813*67e74705SXin Li         WriteInternalIvarName(CDecl, IvarDecl, Result);
6814*67e74705SXin Li       Result += ", ";
6815*67e74705SXin Li 
6816*67e74705SXin Li       Result += "\"";
6817*67e74705SXin Li       if (Ivars[i]->isBitField())
6818*67e74705SXin Li         RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6819*67e74705SXin Li       else
6820*67e74705SXin Li         Result += IvarDecl->getName();
6821*67e74705SXin Li       Result += "\", ";
6822*67e74705SXin Li 
6823*67e74705SXin Li       QualType IVQT = IvarDecl->getType();
6824*67e74705SXin Li       if (IvarDecl->isBitField())
6825*67e74705SXin Li         IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6826*67e74705SXin Li 
6827*67e74705SXin Li       std::string IvarTypeString, QuoteIvarTypeString;
6828*67e74705SXin Li       Context->getObjCEncodingForType(IVQT, IvarTypeString,
6829*67e74705SXin Li                                       IvarDecl);
6830*67e74705SXin Li       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6831*67e74705SXin Li       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6832*67e74705SXin Li 
6833*67e74705SXin Li       // FIXME. this alignment represents the host alignment and need be changed to
6834*67e74705SXin Li       // represent the target alignment.
6835*67e74705SXin Li       unsigned Align = Context->getTypeAlign(IVQT)/8;
6836*67e74705SXin Li       Align = llvm::Log2_32(Align);
6837*67e74705SXin Li       Result += llvm::utostr(Align); Result += ", ";
6838*67e74705SXin Li       CharUnits Size = Context->getTypeSizeInChars(IVQT);
6839*67e74705SXin Li       Result += llvm::utostr(Size.getQuantity());
6840*67e74705SXin Li       if (i  == e-1)
6841*67e74705SXin Li         Result += "}}\n";
6842*67e74705SXin Li       else
6843*67e74705SXin Li         Result += "},\n";
6844*67e74705SXin Li     }
6845*67e74705SXin Li     Result += "};\n";
6846*67e74705SXin Li   }
6847*67e74705SXin Li }
6848*67e74705SXin Li 
6849*67e74705SXin Li /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
RewriteObjCProtocolMetaData(ObjCProtocolDecl * PDecl,std::string & Result)6850*67e74705SXin Li void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6851*67e74705SXin Li                                                     std::string &Result) {
6852*67e74705SXin Li 
6853*67e74705SXin Li   // Do not synthesize the protocol more than once.
6854*67e74705SXin Li   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6855*67e74705SXin Li     return;
6856*67e74705SXin Li   WriteModernMetadataDeclarations(Context, Result);
6857*67e74705SXin Li 
6858*67e74705SXin Li   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6859*67e74705SXin Li     PDecl = Def;
6860*67e74705SXin Li   // Must write out all protocol definitions in current qualifier list,
6861*67e74705SXin Li   // and in their nested qualifiers before writing out current definition.
6862*67e74705SXin Li   for (auto *I : PDecl->protocols())
6863*67e74705SXin Li     RewriteObjCProtocolMetaData(I, Result);
6864*67e74705SXin Li 
6865*67e74705SXin Li   // Construct method lists.
6866*67e74705SXin Li   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6867*67e74705SXin Li   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6868*67e74705SXin Li   for (auto *MD : PDecl->instance_methods()) {
6869*67e74705SXin Li     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6870*67e74705SXin Li       OptInstanceMethods.push_back(MD);
6871*67e74705SXin Li     } else {
6872*67e74705SXin Li       InstanceMethods.push_back(MD);
6873*67e74705SXin Li     }
6874*67e74705SXin Li   }
6875*67e74705SXin Li 
6876*67e74705SXin Li   for (auto *MD : PDecl->class_methods()) {
6877*67e74705SXin Li     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6878*67e74705SXin Li       OptClassMethods.push_back(MD);
6879*67e74705SXin Li     } else {
6880*67e74705SXin Li       ClassMethods.push_back(MD);
6881*67e74705SXin Li     }
6882*67e74705SXin Li   }
6883*67e74705SXin Li   std::vector<ObjCMethodDecl *> AllMethods;
6884*67e74705SXin Li   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6885*67e74705SXin Li     AllMethods.push_back(InstanceMethods[i]);
6886*67e74705SXin Li   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6887*67e74705SXin Li     AllMethods.push_back(ClassMethods[i]);
6888*67e74705SXin Li   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6889*67e74705SXin Li     AllMethods.push_back(OptInstanceMethods[i]);
6890*67e74705SXin Li   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6891*67e74705SXin Li     AllMethods.push_back(OptClassMethods[i]);
6892*67e74705SXin Li 
6893*67e74705SXin Li   Write__extendedMethodTypes_initializer(*this, Context, Result,
6894*67e74705SXin Li                                          AllMethods,
6895*67e74705SXin Li                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
6896*67e74705SXin Li                                          PDecl->getNameAsString());
6897*67e74705SXin Li   // Protocol's super protocol list
6898*67e74705SXin Li   SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6899*67e74705SXin Li   Write_protocol_list_initializer(Context, Result, SuperProtocols,
6900*67e74705SXin Li                                   "_OBJC_PROTOCOL_REFS_",
6901*67e74705SXin Li                                   PDecl->getNameAsString());
6902*67e74705SXin Li 
6903*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6904*67e74705SXin Li                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6905*67e74705SXin Li                                   PDecl->getNameAsString(), false);
6906*67e74705SXin Li 
6907*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6908*67e74705SXin Li                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
6909*67e74705SXin Li                                   PDecl->getNameAsString(), false);
6910*67e74705SXin Li 
6911*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6912*67e74705SXin Li                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6913*67e74705SXin Li                                   PDecl->getNameAsString(), false);
6914*67e74705SXin Li 
6915*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6916*67e74705SXin Li                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6917*67e74705SXin Li                                   PDecl->getNameAsString(), false);
6918*67e74705SXin Li 
6919*67e74705SXin Li   // Protocol's property metadata.
6920*67e74705SXin Li   SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6921*67e74705SXin Li       PDecl->instance_properties());
6922*67e74705SXin Li   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6923*67e74705SXin Li                                  /* Container */nullptr,
6924*67e74705SXin Li                                  "_OBJC_PROTOCOL_PROPERTIES_",
6925*67e74705SXin Li                                  PDecl->getNameAsString());
6926*67e74705SXin Li 
6927*67e74705SXin Li   // Writer out root metadata for current protocol: struct _protocol_t
6928*67e74705SXin Li   Result += "\n";
6929*67e74705SXin Li   if (LangOpts.MicrosoftExt)
6930*67e74705SXin Li     Result += "static ";
6931*67e74705SXin Li   Result += "struct _protocol_t _OBJC_PROTOCOL_";
6932*67e74705SXin Li   Result += PDecl->getNameAsString();
6933*67e74705SXin Li   Result += " __attribute__ ((used)) = {\n";
6934*67e74705SXin Li   Result += "\t0,\n"; // id is; is null
6935*67e74705SXin Li   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6936*67e74705SXin Li   if (SuperProtocols.size() > 0) {
6937*67e74705SXin Li     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6938*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6939*67e74705SXin Li   }
6940*67e74705SXin Li   else
6941*67e74705SXin Li     Result += "\t0,\n";
6942*67e74705SXin Li   if (InstanceMethods.size() > 0) {
6943*67e74705SXin Li     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6944*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6945*67e74705SXin Li   }
6946*67e74705SXin Li   else
6947*67e74705SXin Li     Result += "\t0,\n";
6948*67e74705SXin Li 
6949*67e74705SXin Li   if (ClassMethods.size() > 0) {
6950*67e74705SXin Li     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6951*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6952*67e74705SXin Li   }
6953*67e74705SXin Li   else
6954*67e74705SXin Li     Result += "\t0,\n";
6955*67e74705SXin Li 
6956*67e74705SXin Li   if (OptInstanceMethods.size() > 0) {
6957*67e74705SXin Li     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6958*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6959*67e74705SXin Li   }
6960*67e74705SXin Li   else
6961*67e74705SXin Li     Result += "\t0,\n";
6962*67e74705SXin Li 
6963*67e74705SXin Li   if (OptClassMethods.size() > 0) {
6964*67e74705SXin Li     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6965*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6966*67e74705SXin Li   }
6967*67e74705SXin Li   else
6968*67e74705SXin Li     Result += "\t0,\n";
6969*67e74705SXin Li 
6970*67e74705SXin Li   if (ProtocolProperties.size() > 0) {
6971*67e74705SXin Li     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6972*67e74705SXin Li     Result += PDecl->getNameAsString(); Result += ",\n";
6973*67e74705SXin Li   }
6974*67e74705SXin Li   else
6975*67e74705SXin Li     Result += "\t0,\n";
6976*67e74705SXin Li 
6977*67e74705SXin Li   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6978*67e74705SXin Li   Result += "\t0,\n";
6979*67e74705SXin Li 
6980*67e74705SXin Li   if (AllMethods.size() > 0) {
6981*67e74705SXin Li     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6982*67e74705SXin Li     Result += PDecl->getNameAsString();
6983*67e74705SXin Li     Result += "\n};\n";
6984*67e74705SXin Li   }
6985*67e74705SXin Li   else
6986*67e74705SXin Li     Result += "\t0\n};\n";
6987*67e74705SXin Li 
6988*67e74705SXin Li   if (LangOpts.MicrosoftExt)
6989*67e74705SXin Li     Result += "static ";
6990*67e74705SXin Li   Result += "struct _protocol_t *";
6991*67e74705SXin Li   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6992*67e74705SXin Li   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6993*67e74705SXin Li   Result += ";\n";
6994*67e74705SXin Li 
6995*67e74705SXin Li   // Mark this protocol as having been generated.
6996*67e74705SXin Li   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6997*67e74705SXin Li     llvm_unreachable("protocol already synthesized");
6998*67e74705SXin Li }
6999*67e74705SXin Li 
7000*67e74705SXin Li /// hasObjCExceptionAttribute - Return true if this class or any super
7001*67e74705SXin Li /// class has the __objc_exception__ attribute.
7002*67e74705SXin Li /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
hasObjCExceptionAttribute(ASTContext & Context,const ObjCInterfaceDecl * OID)7003*67e74705SXin Li static bool hasObjCExceptionAttribute(ASTContext &Context,
7004*67e74705SXin Li                                       const ObjCInterfaceDecl *OID) {
7005*67e74705SXin Li   if (OID->hasAttr<ObjCExceptionAttr>())
7006*67e74705SXin Li     return true;
7007*67e74705SXin Li   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7008*67e74705SXin Li     return hasObjCExceptionAttribute(Context, Super);
7009*67e74705SXin Li   return false;
7010*67e74705SXin Li }
7011*67e74705SXin Li 
RewriteObjCClassMetaData(ObjCImplementationDecl * IDecl,std::string & Result)7012*67e74705SXin Li void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7013*67e74705SXin Li                                            std::string &Result) {
7014*67e74705SXin Li   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7015*67e74705SXin Li 
7016*67e74705SXin Li   // Explicitly declared @interface's are already synthesized.
7017*67e74705SXin Li   if (CDecl->isImplicitInterfaceDecl())
7018*67e74705SXin Li     assert(false &&
7019*67e74705SXin Li            "Legacy implicit interface rewriting not supported in moder abi");
7020*67e74705SXin Li 
7021*67e74705SXin Li   WriteModernMetadataDeclarations(Context, Result);
7022*67e74705SXin Li   SmallVector<ObjCIvarDecl *, 8> IVars;
7023*67e74705SXin Li 
7024*67e74705SXin Li   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7025*67e74705SXin Li       IVD; IVD = IVD->getNextIvar()) {
7026*67e74705SXin Li     // Ignore unnamed bit-fields.
7027*67e74705SXin Li     if (!IVD->getDeclName())
7028*67e74705SXin Li       continue;
7029*67e74705SXin Li     IVars.push_back(IVD);
7030*67e74705SXin Li   }
7031*67e74705SXin Li 
7032*67e74705SXin Li   Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7033*67e74705SXin Li                                  "_OBJC_$_INSTANCE_VARIABLES_",
7034*67e74705SXin Li                                  CDecl);
7035*67e74705SXin Li 
7036*67e74705SXin Li   // Build _objc_method_list for class's instance methods if needed
7037*67e74705SXin Li   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7038*67e74705SXin Li 
7039*67e74705SXin Li   // If any of our property implementations have associated getters or
7040*67e74705SXin Li   // setters, produce metadata for them as well.
7041*67e74705SXin Li   for (const auto *Prop : IDecl->property_impls()) {
7042*67e74705SXin Li     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7043*67e74705SXin Li       continue;
7044*67e74705SXin Li     if (!Prop->getPropertyIvarDecl())
7045*67e74705SXin Li       continue;
7046*67e74705SXin Li     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7047*67e74705SXin Li     if (!PD)
7048*67e74705SXin Li       continue;
7049*67e74705SXin Li     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7050*67e74705SXin Li       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7051*67e74705SXin Li         InstanceMethods.push_back(Getter);
7052*67e74705SXin Li     if (PD->isReadOnly())
7053*67e74705SXin Li       continue;
7054*67e74705SXin Li     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7055*67e74705SXin Li       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7056*67e74705SXin Li         InstanceMethods.push_back(Setter);
7057*67e74705SXin Li   }
7058*67e74705SXin Li 
7059*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7060*67e74705SXin Li                                   "_OBJC_$_INSTANCE_METHODS_",
7061*67e74705SXin Li                                   IDecl->getNameAsString(), true);
7062*67e74705SXin Li 
7063*67e74705SXin Li   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7064*67e74705SXin Li 
7065*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7066*67e74705SXin Li                                   "_OBJC_$_CLASS_METHODS_",
7067*67e74705SXin Li                                   IDecl->getNameAsString(), true);
7068*67e74705SXin Li 
7069*67e74705SXin Li   // Protocols referenced in class declaration?
7070*67e74705SXin Li   // Protocol's super protocol list
7071*67e74705SXin Li   std::vector<ObjCProtocolDecl *> RefedProtocols;
7072*67e74705SXin Li   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7073*67e74705SXin Li   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7074*67e74705SXin Li        E = Protocols.end();
7075*67e74705SXin Li        I != E; ++I) {
7076*67e74705SXin Li     RefedProtocols.push_back(*I);
7077*67e74705SXin Li     // Must write out all protocol definitions in current qualifier list,
7078*67e74705SXin Li     // and in their nested qualifiers before writing out current definition.
7079*67e74705SXin Li     RewriteObjCProtocolMetaData(*I, Result);
7080*67e74705SXin Li   }
7081*67e74705SXin Li 
7082*67e74705SXin Li   Write_protocol_list_initializer(Context, Result,
7083*67e74705SXin Li                                   RefedProtocols,
7084*67e74705SXin Li                                   "_OBJC_CLASS_PROTOCOLS_$_",
7085*67e74705SXin Li                                   IDecl->getNameAsString());
7086*67e74705SXin Li 
7087*67e74705SXin Li   // Protocol's property metadata.
7088*67e74705SXin Li   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7089*67e74705SXin Li       CDecl->instance_properties());
7090*67e74705SXin Li   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7091*67e74705SXin Li                                  /* Container */IDecl,
7092*67e74705SXin Li                                  "_OBJC_$_PROP_LIST_",
7093*67e74705SXin Li                                  CDecl->getNameAsString());
7094*67e74705SXin Li 
7095*67e74705SXin Li   // Data for initializing _class_ro_t  metaclass meta-data
7096*67e74705SXin Li   uint32_t flags = CLS_META;
7097*67e74705SXin Li   std::string InstanceSize;
7098*67e74705SXin Li   std::string InstanceStart;
7099*67e74705SXin Li 
7100*67e74705SXin Li   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7101*67e74705SXin Li   if (classIsHidden)
7102*67e74705SXin Li     flags |= OBJC2_CLS_HIDDEN;
7103*67e74705SXin Li 
7104*67e74705SXin Li   if (!CDecl->getSuperClass())
7105*67e74705SXin Li     // class is root
7106*67e74705SXin Li     flags |= CLS_ROOT;
7107*67e74705SXin Li   InstanceSize = "sizeof(struct _class_t)";
7108*67e74705SXin Li   InstanceStart = InstanceSize;
7109*67e74705SXin Li   Write__class_ro_t_initializer(Context, Result, flags,
7110*67e74705SXin Li                                 InstanceStart, InstanceSize,
7111*67e74705SXin Li                                 ClassMethods,
7112*67e74705SXin Li                                 nullptr,
7113*67e74705SXin Li                                 nullptr,
7114*67e74705SXin Li                                 nullptr,
7115*67e74705SXin Li                                 "_OBJC_METACLASS_RO_$_",
7116*67e74705SXin Li                                 CDecl->getNameAsString());
7117*67e74705SXin Li 
7118*67e74705SXin Li   // Data for initializing _class_ro_t meta-data
7119*67e74705SXin Li   flags = CLS;
7120*67e74705SXin Li   if (classIsHidden)
7121*67e74705SXin Li     flags |= OBJC2_CLS_HIDDEN;
7122*67e74705SXin Li 
7123*67e74705SXin Li   if (hasObjCExceptionAttribute(*Context, CDecl))
7124*67e74705SXin Li     flags |= CLS_EXCEPTION;
7125*67e74705SXin Li 
7126*67e74705SXin Li   if (!CDecl->getSuperClass())
7127*67e74705SXin Li     // class is root
7128*67e74705SXin Li     flags |= CLS_ROOT;
7129*67e74705SXin Li 
7130*67e74705SXin Li   InstanceSize.clear();
7131*67e74705SXin Li   InstanceStart.clear();
7132*67e74705SXin Li   if (!ObjCSynthesizedStructs.count(CDecl)) {
7133*67e74705SXin Li     InstanceSize = "0";
7134*67e74705SXin Li     InstanceStart = "0";
7135*67e74705SXin Li   }
7136*67e74705SXin Li   else {
7137*67e74705SXin Li     InstanceSize = "sizeof(struct ";
7138*67e74705SXin Li     InstanceSize += CDecl->getNameAsString();
7139*67e74705SXin Li     InstanceSize += "_IMPL)";
7140*67e74705SXin Li 
7141*67e74705SXin Li     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7142*67e74705SXin Li     if (IVD) {
7143*67e74705SXin Li       RewriteIvarOffsetComputation(IVD, InstanceStart);
7144*67e74705SXin Li     }
7145*67e74705SXin Li     else
7146*67e74705SXin Li       InstanceStart = InstanceSize;
7147*67e74705SXin Li   }
7148*67e74705SXin Li   Write__class_ro_t_initializer(Context, Result, flags,
7149*67e74705SXin Li                                 InstanceStart, InstanceSize,
7150*67e74705SXin Li                                 InstanceMethods,
7151*67e74705SXin Li                                 RefedProtocols,
7152*67e74705SXin Li                                 IVars,
7153*67e74705SXin Li                                 ClassProperties,
7154*67e74705SXin Li                                 "_OBJC_CLASS_RO_$_",
7155*67e74705SXin Li                                 CDecl->getNameAsString());
7156*67e74705SXin Li 
7157*67e74705SXin Li   Write_class_t(Context, Result,
7158*67e74705SXin Li                 "OBJC_METACLASS_$_",
7159*67e74705SXin Li                 CDecl, /*metaclass*/true);
7160*67e74705SXin Li 
7161*67e74705SXin Li   Write_class_t(Context, Result,
7162*67e74705SXin Li                 "OBJC_CLASS_$_",
7163*67e74705SXin Li                 CDecl, /*metaclass*/false);
7164*67e74705SXin Li 
7165*67e74705SXin Li   if (ImplementationIsNonLazy(IDecl))
7166*67e74705SXin Li     DefinedNonLazyClasses.push_back(CDecl);
7167*67e74705SXin Li }
7168*67e74705SXin Li 
RewriteClassSetupInitHook(std::string & Result)7169*67e74705SXin Li void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7170*67e74705SXin Li   int ClsDefCount = ClassImplementation.size();
7171*67e74705SXin Li   if (!ClsDefCount)
7172*67e74705SXin Li     return;
7173*67e74705SXin Li   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7174*67e74705SXin Li   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7175*67e74705SXin Li   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7176*67e74705SXin Li   for (int i = 0; i < ClsDefCount; i++) {
7177*67e74705SXin Li     ObjCImplementationDecl *IDecl = ClassImplementation[i];
7178*67e74705SXin Li     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7179*67e74705SXin Li     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7180*67e74705SXin Li     Result  += CDecl->getName(); Result += ",\n";
7181*67e74705SXin Li   }
7182*67e74705SXin Li   Result += "};\n";
7183*67e74705SXin Li }
7184*67e74705SXin Li 
RewriteMetaDataIntoBuffer(std::string & Result)7185*67e74705SXin Li void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7186*67e74705SXin Li   int ClsDefCount = ClassImplementation.size();
7187*67e74705SXin Li   int CatDefCount = CategoryImplementation.size();
7188*67e74705SXin Li 
7189*67e74705SXin Li   // For each implemented class, write out all its meta data.
7190*67e74705SXin Li   for (int i = 0; i < ClsDefCount; i++)
7191*67e74705SXin Li     RewriteObjCClassMetaData(ClassImplementation[i], Result);
7192*67e74705SXin Li 
7193*67e74705SXin Li   RewriteClassSetupInitHook(Result);
7194*67e74705SXin Li 
7195*67e74705SXin Li   // For each implemented category, write out all its meta data.
7196*67e74705SXin Li   for (int i = 0; i < CatDefCount; i++)
7197*67e74705SXin Li     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7198*67e74705SXin Li 
7199*67e74705SXin Li   RewriteCategorySetupInitHook(Result);
7200*67e74705SXin Li 
7201*67e74705SXin Li   if (ClsDefCount > 0) {
7202*67e74705SXin Li     if (LangOpts.MicrosoftExt)
7203*67e74705SXin Li       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7204*67e74705SXin Li     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7205*67e74705SXin Li     Result += llvm::utostr(ClsDefCount); Result += "]";
7206*67e74705SXin Li     Result +=
7207*67e74705SXin Li       " __attribute__((used, section (\"__DATA, __objc_classlist,"
7208*67e74705SXin Li       "regular,no_dead_strip\")))= {\n";
7209*67e74705SXin Li     for (int i = 0; i < ClsDefCount; i++) {
7210*67e74705SXin Li       Result += "\t&OBJC_CLASS_$_";
7211*67e74705SXin Li       Result += ClassImplementation[i]->getNameAsString();
7212*67e74705SXin Li       Result += ",\n";
7213*67e74705SXin Li     }
7214*67e74705SXin Li     Result += "};\n";
7215*67e74705SXin Li 
7216*67e74705SXin Li     if (!DefinedNonLazyClasses.empty()) {
7217*67e74705SXin Li       if (LangOpts.MicrosoftExt)
7218*67e74705SXin Li         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7219*67e74705SXin Li       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7220*67e74705SXin Li       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7221*67e74705SXin Li         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7222*67e74705SXin Li         Result += ",\n";
7223*67e74705SXin Li       }
7224*67e74705SXin Li       Result += "};\n";
7225*67e74705SXin Li     }
7226*67e74705SXin Li   }
7227*67e74705SXin Li 
7228*67e74705SXin Li   if (CatDefCount > 0) {
7229*67e74705SXin Li     if (LangOpts.MicrosoftExt)
7230*67e74705SXin Li       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7231*67e74705SXin Li     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7232*67e74705SXin Li     Result += llvm::utostr(CatDefCount); Result += "]";
7233*67e74705SXin Li     Result +=
7234*67e74705SXin Li     " __attribute__((used, section (\"__DATA, __objc_catlist,"
7235*67e74705SXin Li     "regular,no_dead_strip\")))= {\n";
7236*67e74705SXin Li     for (int i = 0; i < CatDefCount; i++) {
7237*67e74705SXin Li       Result += "\t&_OBJC_$_CATEGORY_";
7238*67e74705SXin Li       Result +=
7239*67e74705SXin Li         CategoryImplementation[i]->getClassInterface()->getNameAsString();
7240*67e74705SXin Li       Result += "_$_";
7241*67e74705SXin Li       Result += CategoryImplementation[i]->getNameAsString();
7242*67e74705SXin Li       Result += ",\n";
7243*67e74705SXin Li     }
7244*67e74705SXin Li     Result += "};\n";
7245*67e74705SXin Li   }
7246*67e74705SXin Li 
7247*67e74705SXin Li   if (!DefinedNonLazyCategories.empty()) {
7248*67e74705SXin Li     if (LangOpts.MicrosoftExt)
7249*67e74705SXin Li       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7250*67e74705SXin Li     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7251*67e74705SXin Li     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7252*67e74705SXin Li       Result += "\t&_OBJC_$_CATEGORY_";
7253*67e74705SXin Li       Result +=
7254*67e74705SXin Li         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7255*67e74705SXin Li       Result += "_$_";
7256*67e74705SXin Li       Result += DefinedNonLazyCategories[i]->getNameAsString();
7257*67e74705SXin Li       Result += ",\n";
7258*67e74705SXin Li     }
7259*67e74705SXin Li     Result += "};\n";
7260*67e74705SXin Li   }
7261*67e74705SXin Li }
7262*67e74705SXin Li 
WriteImageInfo(std::string & Result)7263*67e74705SXin Li void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7264*67e74705SXin Li   if (LangOpts.MicrosoftExt)
7265*67e74705SXin Li     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7266*67e74705SXin Li 
7267*67e74705SXin Li   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7268*67e74705SXin Li   // version 0, ObjCABI is 2
7269*67e74705SXin Li   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7270*67e74705SXin Li }
7271*67e74705SXin Li 
7272*67e74705SXin Li /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7273*67e74705SXin Li /// implementation.
RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl * IDecl,std::string & Result)7274*67e74705SXin Li void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7275*67e74705SXin Li                                               std::string &Result) {
7276*67e74705SXin Li   WriteModernMetadataDeclarations(Context, Result);
7277*67e74705SXin Li   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7278*67e74705SXin Li   // Find category declaration for this implementation.
7279*67e74705SXin Li   ObjCCategoryDecl *CDecl
7280*67e74705SXin Li     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7281*67e74705SXin Li 
7282*67e74705SXin Li   std::string FullCategoryName = ClassDecl->getNameAsString();
7283*67e74705SXin Li   FullCategoryName += "_$_";
7284*67e74705SXin Li   FullCategoryName += CDecl->getNameAsString();
7285*67e74705SXin Li 
7286*67e74705SXin Li   // Build _objc_method_list for class's instance methods if needed
7287*67e74705SXin Li   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7288*67e74705SXin Li 
7289*67e74705SXin Li   // If any of our property implementations have associated getters or
7290*67e74705SXin Li   // setters, produce metadata for them as well.
7291*67e74705SXin Li   for (const auto *Prop : IDecl->property_impls()) {
7292*67e74705SXin Li     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7293*67e74705SXin Li       continue;
7294*67e74705SXin Li     if (!Prop->getPropertyIvarDecl())
7295*67e74705SXin Li       continue;
7296*67e74705SXin Li     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7297*67e74705SXin Li     if (!PD)
7298*67e74705SXin Li       continue;
7299*67e74705SXin Li     if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7300*67e74705SXin Li       InstanceMethods.push_back(Getter);
7301*67e74705SXin Li     if (PD->isReadOnly())
7302*67e74705SXin Li       continue;
7303*67e74705SXin Li     if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7304*67e74705SXin Li       InstanceMethods.push_back(Setter);
7305*67e74705SXin Li   }
7306*67e74705SXin Li 
7307*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7308*67e74705SXin Li                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7309*67e74705SXin Li                                   FullCategoryName, true);
7310*67e74705SXin Li 
7311*67e74705SXin Li   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7312*67e74705SXin Li 
7313*67e74705SXin Li   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7314*67e74705SXin Li                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
7315*67e74705SXin Li                                   FullCategoryName, true);
7316*67e74705SXin Li 
7317*67e74705SXin Li   // Protocols referenced in class declaration?
7318*67e74705SXin Li   // Protocol's super protocol list
7319*67e74705SXin Li   SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7320*67e74705SXin Li   for (auto *I : CDecl->protocols())
7321*67e74705SXin Li     // Must write out all protocol definitions in current qualifier list,
7322*67e74705SXin Li     // and in their nested qualifiers before writing out current definition.
7323*67e74705SXin Li     RewriteObjCProtocolMetaData(I, Result);
7324*67e74705SXin Li 
7325*67e74705SXin Li   Write_protocol_list_initializer(Context, Result,
7326*67e74705SXin Li                                   RefedProtocols,
7327*67e74705SXin Li                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
7328*67e74705SXin Li                                   FullCategoryName);
7329*67e74705SXin Li 
7330*67e74705SXin Li   // Protocol's property metadata.
7331*67e74705SXin Li   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7332*67e74705SXin Li       CDecl->instance_properties());
7333*67e74705SXin Li   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7334*67e74705SXin Li                                 /* Container */IDecl,
7335*67e74705SXin Li                                 "_OBJC_$_PROP_LIST_",
7336*67e74705SXin Li                                 FullCategoryName);
7337*67e74705SXin Li 
7338*67e74705SXin Li   Write_category_t(*this, Context, Result,
7339*67e74705SXin Li                    CDecl,
7340*67e74705SXin Li                    ClassDecl,
7341*67e74705SXin Li                    InstanceMethods,
7342*67e74705SXin Li                    ClassMethods,
7343*67e74705SXin Li                    RefedProtocols,
7344*67e74705SXin Li                    ClassProperties);
7345*67e74705SXin Li 
7346*67e74705SXin Li   // Determine if this category is also "non-lazy".
7347*67e74705SXin Li   if (ImplementationIsNonLazy(IDecl))
7348*67e74705SXin Li     DefinedNonLazyCategories.push_back(CDecl);
7349*67e74705SXin Li }
7350*67e74705SXin Li 
RewriteCategorySetupInitHook(std::string & Result)7351*67e74705SXin Li void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7352*67e74705SXin Li   int CatDefCount = CategoryImplementation.size();
7353*67e74705SXin Li   if (!CatDefCount)
7354*67e74705SXin Li     return;
7355*67e74705SXin Li   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7356*67e74705SXin Li   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7357*67e74705SXin Li   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7358*67e74705SXin Li   for (int i = 0; i < CatDefCount; i++) {
7359*67e74705SXin Li     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7360*67e74705SXin Li     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7361*67e74705SXin Li     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7362*67e74705SXin Li     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7363*67e74705SXin Li     Result += ClassDecl->getName();
7364*67e74705SXin Li     Result += "_$_";
7365*67e74705SXin Li     Result += CatDecl->getName();
7366*67e74705SXin Li     Result += ",\n";
7367*67e74705SXin Li   }
7368*67e74705SXin Li   Result += "};\n";
7369*67e74705SXin Li }
7370*67e74705SXin Li 
7371*67e74705SXin Li // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7372*67e74705SXin Li /// class methods.
7373*67e74705SXin Li template<typename MethodIterator>
RewriteObjCMethodsMetaData(MethodIterator MethodBegin,MethodIterator MethodEnd,bool IsInstanceMethod,StringRef prefix,StringRef ClassName,std::string & Result)7374*67e74705SXin Li void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7375*67e74705SXin Li                                              MethodIterator MethodEnd,
7376*67e74705SXin Li                                              bool IsInstanceMethod,
7377*67e74705SXin Li                                              StringRef prefix,
7378*67e74705SXin Li                                              StringRef ClassName,
7379*67e74705SXin Li                                              std::string &Result) {
7380*67e74705SXin Li   if (MethodBegin == MethodEnd) return;
7381*67e74705SXin Li 
7382*67e74705SXin Li   if (!objc_impl_method) {
7383*67e74705SXin Li     /* struct _objc_method {
7384*67e74705SXin Li      SEL _cmd;
7385*67e74705SXin Li      char *method_types;
7386*67e74705SXin Li      void *_imp;
7387*67e74705SXin Li      }
7388*67e74705SXin Li      */
7389*67e74705SXin Li     Result += "\nstruct _objc_method {\n";
7390*67e74705SXin Li     Result += "\tSEL _cmd;\n";
7391*67e74705SXin Li     Result += "\tchar *method_types;\n";
7392*67e74705SXin Li     Result += "\tvoid *_imp;\n";
7393*67e74705SXin Li     Result += "};\n";
7394*67e74705SXin Li 
7395*67e74705SXin Li     objc_impl_method = true;
7396*67e74705SXin Li   }
7397*67e74705SXin Li 
7398*67e74705SXin Li   // Build _objc_method_list for class's methods if needed
7399*67e74705SXin Li 
7400*67e74705SXin Li   /* struct  {
7401*67e74705SXin Li    struct _objc_method_list *next_method;
7402*67e74705SXin Li    int method_count;
7403*67e74705SXin Li    struct _objc_method method_list[];
7404*67e74705SXin Li    }
7405*67e74705SXin Li    */
7406*67e74705SXin Li   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7407*67e74705SXin Li   Result += "\n";
7408*67e74705SXin Li   if (LangOpts.MicrosoftExt) {
7409*67e74705SXin Li     if (IsInstanceMethod)
7410*67e74705SXin Li       Result += "__declspec(allocate(\".inst_meth$B\")) ";
7411*67e74705SXin Li     else
7412*67e74705SXin Li       Result += "__declspec(allocate(\".cls_meth$B\")) ";
7413*67e74705SXin Li   }
7414*67e74705SXin Li   Result += "static struct {\n";
7415*67e74705SXin Li   Result += "\tstruct _objc_method_list *next_method;\n";
7416*67e74705SXin Li   Result += "\tint method_count;\n";
7417*67e74705SXin Li   Result += "\tstruct _objc_method method_list[";
7418*67e74705SXin Li   Result += utostr(NumMethods);
7419*67e74705SXin Li   Result += "];\n} _OBJC_";
7420*67e74705SXin Li   Result += prefix;
7421*67e74705SXin Li   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7422*67e74705SXin Li   Result += "_METHODS_";
7423*67e74705SXin Li   Result += ClassName;
7424*67e74705SXin Li   Result += " __attribute__ ((used, section (\"__OBJC, __";
7425*67e74705SXin Li   Result += IsInstanceMethod ? "inst" : "cls";
7426*67e74705SXin Li   Result += "_meth\")))= ";
7427*67e74705SXin Li   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7428*67e74705SXin Li 
7429*67e74705SXin Li   Result += "\t,{{(SEL)\"";
7430*67e74705SXin Li   Result += (*MethodBegin)->getSelector().getAsString().c_str();
7431*67e74705SXin Li   std::string MethodTypeString;
7432*67e74705SXin Li   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7433*67e74705SXin Li   Result += "\", \"";
7434*67e74705SXin Li   Result += MethodTypeString;
7435*67e74705SXin Li   Result += "\", (void *)";
7436*67e74705SXin Li   Result += MethodInternalNames[*MethodBegin];
7437*67e74705SXin Li   Result += "}\n";
7438*67e74705SXin Li   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7439*67e74705SXin Li     Result += "\t  ,{(SEL)\"";
7440*67e74705SXin Li     Result += (*MethodBegin)->getSelector().getAsString().c_str();
7441*67e74705SXin Li     std::string MethodTypeString;
7442*67e74705SXin Li     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7443*67e74705SXin Li     Result += "\", \"";
7444*67e74705SXin Li     Result += MethodTypeString;
7445*67e74705SXin Li     Result += "\", (void *)";
7446*67e74705SXin Li     Result += MethodInternalNames[*MethodBegin];
7447*67e74705SXin Li     Result += "}\n";
7448*67e74705SXin Li   }
7449*67e74705SXin Li   Result += "\t }\n};\n";
7450*67e74705SXin Li }
7451*67e74705SXin Li 
RewriteObjCIvarRefExpr(ObjCIvarRefExpr * IV)7452*67e74705SXin Li Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7453*67e74705SXin Li   SourceRange OldRange = IV->getSourceRange();
7454*67e74705SXin Li   Expr *BaseExpr = IV->getBase();
7455*67e74705SXin Li 
7456*67e74705SXin Li   // Rewrite the base, but without actually doing replaces.
7457*67e74705SXin Li   {
7458*67e74705SXin Li     DisableReplaceStmtScope S(*this);
7459*67e74705SXin Li     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7460*67e74705SXin Li     IV->setBase(BaseExpr);
7461*67e74705SXin Li   }
7462*67e74705SXin Li 
7463*67e74705SXin Li   ObjCIvarDecl *D = IV->getDecl();
7464*67e74705SXin Li 
7465*67e74705SXin Li   Expr *Replacement = IV;
7466*67e74705SXin Li 
7467*67e74705SXin Li     if (BaseExpr->getType()->isObjCObjectPointerType()) {
7468*67e74705SXin Li       const ObjCInterfaceType *iFaceDecl =
7469*67e74705SXin Li         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7470*67e74705SXin Li       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7471*67e74705SXin Li       // lookup which class implements the instance variable.
7472*67e74705SXin Li       ObjCInterfaceDecl *clsDeclared = nullptr;
7473*67e74705SXin Li       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7474*67e74705SXin Li                                                    clsDeclared);
7475*67e74705SXin Li       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7476*67e74705SXin Li 
7477*67e74705SXin Li       // Build name of symbol holding ivar offset.
7478*67e74705SXin Li       std::string IvarOffsetName;
7479*67e74705SXin Li       if (D->isBitField())
7480*67e74705SXin Li         ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7481*67e74705SXin Li       else
7482*67e74705SXin Li         WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7483*67e74705SXin Li 
7484*67e74705SXin Li       ReferencedIvars[clsDeclared].insert(D);
7485*67e74705SXin Li 
7486*67e74705SXin Li       // cast offset to "char *".
7487*67e74705SXin Li       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7488*67e74705SXin Li                                                     Context->getPointerType(Context->CharTy),
7489*67e74705SXin Li                                                     CK_BitCast,
7490*67e74705SXin Li                                                     BaseExpr);
7491*67e74705SXin Li       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7492*67e74705SXin Li                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
7493*67e74705SXin Li                                        Context->UnsignedLongTy, nullptr,
7494*67e74705SXin Li                                        SC_Extern);
7495*67e74705SXin Li       DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7496*67e74705SXin Li                                                    Context->UnsignedLongTy, VK_LValue,
7497*67e74705SXin Li                                                    SourceLocation());
7498*67e74705SXin Li       BinaryOperator *addExpr =
7499*67e74705SXin Li         new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7500*67e74705SXin Li                                      Context->getPointerType(Context->CharTy),
7501*67e74705SXin Li                                      VK_RValue, OK_Ordinary, SourceLocation(), false);
7502*67e74705SXin Li       // Don't forget the parens to enforce the proper binding.
7503*67e74705SXin Li       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7504*67e74705SXin Li                                               SourceLocation(),
7505*67e74705SXin Li                                               addExpr);
7506*67e74705SXin Li       QualType IvarT = D->getType();
7507*67e74705SXin Li       if (D->isBitField())
7508*67e74705SXin Li         IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7509*67e74705SXin Li 
7510*67e74705SXin Li       if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7511*67e74705SXin Li         RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7512*67e74705SXin Li         RD = RD->getDefinition();
7513*67e74705SXin Li         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7514*67e74705SXin Li           // decltype(((Foo_IMPL*)0)->bar) *
7515*67e74705SXin Li           ObjCContainerDecl *CDecl =
7516*67e74705SXin Li             dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7517*67e74705SXin Li           // ivar in class extensions requires special treatment.
7518*67e74705SXin Li           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7519*67e74705SXin Li             CDecl = CatDecl->getClassInterface();
7520*67e74705SXin Li           std::string RecName = CDecl->getName();
7521*67e74705SXin Li           RecName += "_IMPL";
7522*67e74705SXin Li           RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7523*67e74705SXin Li                                               SourceLocation(), SourceLocation(),
7524*67e74705SXin Li                                               &Context->Idents.get(RecName.c_str()));
7525*67e74705SXin Li           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7526*67e74705SXin Li           unsigned UnsignedIntSize =
7527*67e74705SXin Li             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7528*67e74705SXin Li           Expr *Zero = IntegerLiteral::Create(*Context,
7529*67e74705SXin Li                                               llvm::APInt(UnsignedIntSize, 0),
7530*67e74705SXin Li                                               Context->UnsignedIntTy, SourceLocation());
7531*67e74705SXin Li           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7532*67e74705SXin Li           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7533*67e74705SXin Li                                                   Zero);
7534*67e74705SXin Li           FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7535*67e74705SXin Li                                             SourceLocation(),
7536*67e74705SXin Li                                             &Context->Idents.get(D->getNameAsString()),
7537*67e74705SXin Li                                             IvarT, nullptr,
7538*67e74705SXin Li                                             /*BitWidth=*/nullptr,
7539*67e74705SXin Li                                             /*Mutable=*/true, ICIS_NoInit);
7540*67e74705SXin Li           MemberExpr *ME = new (Context)
7541*67e74705SXin Li               MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7542*67e74705SXin Li                          FD->getType(), VK_LValue, OK_Ordinary);
7543*67e74705SXin Li           IvarT = Context->getDecltypeType(ME, ME->getType());
7544*67e74705SXin Li         }
7545*67e74705SXin Li       }
7546*67e74705SXin Li       convertObjCTypeToCStyleType(IvarT);
7547*67e74705SXin Li       QualType castT = Context->getPointerType(IvarT);
7548*67e74705SXin Li 
7549*67e74705SXin Li       castExpr = NoTypeInfoCStyleCastExpr(Context,
7550*67e74705SXin Li                                           castT,
7551*67e74705SXin Li                                           CK_BitCast,
7552*67e74705SXin Li                                           PE);
7553*67e74705SXin Li 
7554*67e74705SXin Li 
7555*67e74705SXin Li       Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7556*67e74705SXin Li                                               VK_LValue, OK_Ordinary,
7557*67e74705SXin Li                                               SourceLocation());
7558*67e74705SXin Li       PE = new (Context) ParenExpr(OldRange.getBegin(),
7559*67e74705SXin Li                                    OldRange.getEnd(),
7560*67e74705SXin Li                                    Exp);
7561*67e74705SXin Li 
7562*67e74705SXin Li       if (D->isBitField()) {
7563*67e74705SXin Li         FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7564*67e74705SXin Li                                           SourceLocation(),
7565*67e74705SXin Li                                           &Context->Idents.get(D->getNameAsString()),
7566*67e74705SXin Li                                           D->getType(), nullptr,
7567*67e74705SXin Li                                           /*BitWidth=*/D->getBitWidth(),
7568*67e74705SXin Li                                           /*Mutable=*/true, ICIS_NoInit);
7569*67e74705SXin Li         MemberExpr *ME = new (Context)
7570*67e74705SXin Li             MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7571*67e74705SXin Li                        SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7572*67e74705SXin Li         Replacement = ME;
7573*67e74705SXin Li 
7574*67e74705SXin Li       }
7575*67e74705SXin Li       else
7576*67e74705SXin Li         Replacement = PE;
7577*67e74705SXin Li     }
7578*67e74705SXin Li 
7579*67e74705SXin Li     ReplaceStmtWithRange(IV, Replacement, OldRange);
7580*67e74705SXin Li     return Replacement;
7581*67e74705SXin Li }
7582*67e74705SXin Li 
7583*67e74705SXin Li #endif // CLANG_ENABLE_OBJC_REWRITER
7584