xref: /openbsd-src/gnu/llvm/clang/lib/Frontend/Rewrite/RewriteObjC.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // Hacks and fun related to the code rewriter.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Rewrite/Frontend/ASTConsumers.h"
14e5dd7070Spatrick #include "clang/AST/AST.h"
15e5dd7070Spatrick #include "clang/AST/ASTConsumer.h"
16e5dd7070Spatrick #include "clang/AST/Attr.h"
17e5dd7070Spatrick #include "clang/AST/ParentMap.h"
18e5dd7070Spatrick #include "clang/Basic/CharInfo.h"
19e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
20e5dd7070Spatrick #include "clang/Basic/IdentifierTable.h"
21e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
22e5dd7070Spatrick #include "clang/Config/config.h"
23e5dd7070Spatrick #include "clang/Lex/Lexer.h"
24e5dd7070Spatrick #include "clang/Rewrite/Core/Rewriter.h"
25e5dd7070Spatrick #include "llvm/ADT/DenseSet.h"
26e5dd7070Spatrick #include "llvm/ADT/SmallPtrSet.h"
27e5dd7070Spatrick #include "llvm/ADT/StringExtras.h"
28e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
29e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
30e5dd7070Spatrick #include <memory>
31e5dd7070Spatrick 
32e5dd7070Spatrick #if CLANG_ENABLE_OBJC_REWRITER
33e5dd7070Spatrick 
34e5dd7070Spatrick using namespace clang;
35e5dd7070Spatrick using llvm::utostr;
36e5dd7070Spatrick 
37e5dd7070Spatrick namespace {
38e5dd7070Spatrick   class RewriteObjC : public ASTConsumer {
39e5dd7070Spatrick   protected:
40e5dd7070Spatrick     enum {
41e5dd7070Spatrick       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
42e5dd7070Spatrick                                         block, ... */
43e5dd7070Spatrick       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
44e5dd7070Spatrick       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
45e5dd7070Spatrick                                         __block variable */
46e5dd7070Spatrick       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
47e5dd7070Spatrick                                         helpers */
48e5dd7070Spatrick       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
49e5dd7070Spatrick                                         support routines */
50e5dd7070Spatrick       BLOCK_BYREF_CURRENT_MAX = 256
51e5dd7070Spatrick     };
52e5dd7070Spatrick 
53e5dd7070Spatrick     enum {
54e5dd7070Spatrick       BLOCK_NEEDS_FREE =        (1 << 24),
55e5dd7070Spatrick       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
56e5dd7070Spatrick       BLOCK_HAS_CXX_OBJ =       (1 << 26),
57e5dd7070Spatrick       BLOCK_IS_GC =             (1 << 27),
58e5dd7070Spatrick       BLOCK_IS_GLOBAL =         (1 << 28),
59e5dd7070Spatrick       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
60e5dd7070Spatrick     };
61e5dd7070Spatrick     static const int OBJC_ABI_VERSION = 7;
62e5dd7070Spatrick 
63e5dd7070Spatrick     Rewriter Rewrite;
64e5dd7070Spatrick     DiagnosticsEngine &Diags;
65e5dd7070Spatrick     const LangOptions &LangOpts;
66e5dd7070Spatrick     ASTContext *Context;
67e5dd7070Spatrick     SourceManager *SM;
68e5dd7070Spatrick     TranslationUnitDecl *TUDecl;
69e5dd7070Spatrick     FileID MainFileID;
70e5dd7070Spatrick     const char *MainFileStart, *MainFileEnd;
71e5dd7070Spatrick     Stmt *CurrentBody;
72e5dd7070Spatrick     ParentMap *PropParentMap; // created lazily.
73e5dd7070Spatrick     std::string InFileName;
74e5dd7070Spatrick     std::unique_ptr<raw_ostream> OutFile;
75e5dd7070Spatrick     std::string Preamble;
76e5dd7070Spatrick 
77e5dd7070Spatrick     TypeDecl *ProtocolTypeDecl;
78e5dd7070Spatrick     VarDecl *GlobalVarDecl;
79e5dd7070Spatrick     unsigned RewriteFailedDiag;
80e5dd7070Spatrick     // ObjC string constant support.
81e5dd7070Spatrick     unsigned NumObjCStringLiterals;
82e5dd7070Spatrick     VarDecl *ConstantStringClassReference;
83e5dd7070Spatrick     RecordDecl *NSStringRecord;
84e5dd7070Spatrick 
85e5dd7070Spatrick     // ObjC foreach break/continue generation support.
86e5dd7070Spatrick     int BcLabelCount;
87e5dd7070Spatrick 
88e5dd7070Spatrick     unsigned TryFinallyContainsReturnDiag;
89e5dd7070Spatrick     // Needed for super.
90e5dd7070Spatrick     ObjCMethodDecl *CurMethodDef;
91e5dd7070Spatrick     RecordDecl *SuperStructDecl;
92e5dd7070Spatrick     RecordDecl *ConstantStringDecl;
93e5dd7070Spatrick 
94e5dd7070Spatrick     FunctionDecl *MsgSendFunctionDecl;
95e5dd7070Spatrick     FunctionDecl *MsgSendSuperFunctionDecl;
96e5dd7070Spatrick     FunctionDecl *MsgSendStretFunctionDecl;
97e5dd7070Spatrick     FunctionDecl *MsgSendSuperStretFunctionDecl;
98e5dd7070Spatrick     FunctionDecl *MsgSendFpretFunctionDecl;
99e5dd7070Spatrick     FunctionDecl *GetClassFunctionDecl;
100e5dd7070Spatrick     FunctionDecl *GetMetaClassFunctionDecl;
101e5dd7070Spatrick     FunctionDecl *GetSuperClassFunctionDecl;
102e5dd7070Spatrick     FunctionDecl *SelGetUidFunctionDecl;
103e5dd7070Spatrick     FunctionDecl *CFStringFunctionDecl;
104e5dd7070Spatrick     FunctionDecl *SuperConstructorFunctionDecl;
105e5dd7070Spatrick     FunctionDecl *CurFunctionDef;
106e5dd7070Spatrick     FunctionDecl *CurFunctionDeclToDeclareForBlock;
107e5dd7070Spatrick 
108e5dd7070Spatrick     /* Misc. containers needed for meta-data rewrite. */
109e5dd7070Spatrick     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110e5dd7070Spatrick     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111e5dd7070Spatrick     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112e5dd7070Spatrick     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
113e5dd7070Spatrick     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
114e5dd7070Spatrick     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
115e5dd7070Spatrick     SmallVector<Stmt *, 32> Stmts;
116e5dd7070Spatrick     SmallVector<int, 8> ObjCBcLabelNo;
117e5dd7070Spatrick     // Remember all the @protocol(<expr>) expressions.
118e5dd7070Spatrick     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
119e5dd7070Spatrick 
120e5dd7070Spatrick     llvm::DenseSet<uint64_t> CopyDestroyCache;
121e5dd7070Spatrick 
122e5dd7070Spatrick     // Block expressions.
123e5dd7070Spatrick     SmallVector<BlockExpr *, 32> Blocks;
124e5dd7070Spatrick     SmallVector<int, 32> InnerDeclRefsCount;
125e5dd7070Spatrick     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
126e5dd7070Spatrick 
127e5dd7070Spatrick     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
128e5dd7070Spatrick 
129e5dd7070Spatrick     // Block related declarations.
130e5dd7070Spatrick     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131e5dd7070Spatrick     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132e5dd7070Spatrick     SmallVector<ValueDecl *, 8> BlockByRefDecls;
133e5dd7070Spatrick     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
134e5dd7070Spatrick     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
135e5dd7070Spatrick     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136e5dd7070Spatrick     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
137e5dd7070Spatrick 
138e5dd7070Spatrick     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
139e5dd7070Spatrick 
140e5dd7070Spatrick     // This maps an original source AST to it's rewritten form. This allows
141e5dd7070Spatrick     // us to avoid rewriting the same node twice (which is very uncommon).
142e5dd7070Spatrick     // This is needed to support some of the exotic property rewriting.
143e5dd7070Spatrick     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
144e5dd7070Spatrick 
145e5dd7070Spatrick     // Needed for header files being rewritten
146e5dd7070Spatrick     bool IsHeader;
147e5dd7070Spatrick     bool SilenceRewriteMacroWarning;
148e5dd7070Spatrick     bool objc_impl_method;
149e5dd7070Spatrick 
150e5dd7070Spatrick     bool DisableReplaceStmt;
151e5dd7070Spatrick     class DisableReplaceStmtScope {
152e5dd7070Spatrick       RewriteObjC &R;
153e5dd7070Spatrick       bool SavedValue;
154e5dd7070Spatrick 
155e5dd7070Spatrick     public:
DisableReplaceStmtScope(RewriteObjC & R)156e5dd7070Spatrick       DisableReplaceStmtScope(RewriteObjC &R)
157e5dd7070Spatrick         : R(R), SavedValue(R.DisableReplaceStmt) {
158e5dd7070Spatrick         R.DisableReplaceStmt = true;
159e5dd7070Spatrick       }
160e5dd7070Spatrick 
~DisableReplaceStmtScope()161e5dd7070Spatrick       ~DisableReplaceStmtScope() {
162e5dd7070Spatrick         R.DisableReplaceStmt = SavedValue;
163e5dd7070Spatrick       }
164e5dd7070Spatrick     };
165e5dd7070Spatrick 
166e5dd7070Spatrick     void InitializeCommon(ASTContext &context);
167e5dd7070Spatrick 
168e5dd7070Spatrick   public:
169e5dd7070Spatrick     // Top Level Driver code.
HandleTopLevelDecl(DeclGroupRef D)170e5dd7070Spatrick     bool HandleTopLevelDecl(DeclGroupRef D) override {
171e5dd7070Spatrick       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172e5dd7070Spatrick         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173e5dd7070Spatrick           if (!Class->isThisDeclarationADefinition()) {
174e5dd7070Spatrick             RewriteForwardClassDecl(D);
175e5dd7070Spatrick             break;
176e5dd7070Spatrick           }
177e5dd7070Spatrick         }
178e5dd7070Spatrick 
179e5dd7070Spatrick         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180e5dd7070Spatrick           if (!Proto->isThisDeclarationADefinition()) {
181e5dd7070Spatrick             RewriteForwardProtocolDecl(D);
182e5dd7070Spatrick             break;
183e5dd7070Spatrick           }
184e5dd7070Spatrick         }
185e5dd7070Spatrick 
186e5dd7070Spatrick         HandleTopLevelSingleDecl(*I);
187e5dd7070Spatrick       }
188e5dd7070Spatrick       return true;
189e5dd7070Spatrick     }
190e5dd7070Spatrick 
191e5dd7070Spatrick     void HandleTopLevelSingleDecl(Decl *D);
192e5dd7070Spatrick     void HandleDeclInMainFile(Decl *D);
193e5dd7070Spatrick     RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
194e5dd7070Spatrick                 DiagnosticsEngine &D, const LangOptions &LOpts,
195e5dd7070Spatrick                 bool silenceMacroWarn);
196e5dd7070Spatrick 
~RewriteObjC()197e5dd7070Spatrick     ~RewriteObjC() override {}
198e5dd7070Spatrick 
199e5dd7070Spatrick     void HandleTranslationUnit(ASTContext &C) override;
200e5dd7070Spatrick 
ReplaceStmt(Stmt * Old,Stmt * New)201e5dd7070Spatrick     void ReplaceStmt(Stmt *Old, Stmt *New) {
202e5dd7070Spatrick       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
203e5dd7070Spatrick     }
204e5dd7070Spatrick 
ReplaceStmtWithRange(Stmt * Old,Stmt * New,SourceRange SrcRange)205e5dd7070Spatrick     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
206e5dd7070Spatrick       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
207e5dd7070Spatrick 
208e5dd7070Spatrick       Stmt *ReplacingStmt = ReplacedNodes[Old];
209e5dd7070Spatrick       if (ReplacingStmt)
210e5dd7070Spatrick         return; // We can't rewrite the same node twice.
211e5dd7070Spatrick 
212e5dd7070Spatrick       if (DisableReplaceStmt)
213e5dd7070Spatrick         return;
214e5dd7070Spatrick 
215e5dd7070Spatrick       // Measure the old text.
216e5dd7070Spatrick       int Size = Rewrite.getRangeSize(SrcRange);
217e5dd7070Spatrick       if (Size == -1) {
218e5dd7070Spatrick         Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
219e5dd7070Spatrick             << Old->getSourceRange();
220e5dd7070Spatrick         return;
221e5dd7070Spatrick       }
222e5dd7070Spatrick       // Get the new text.
223e5dd7070Spatrick       std::string SStr;
224e5dd7070Spatrick       llvm::raw_string_ostream S(SStr);
225e5dd7070Spatrick       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
226e5dd7070Spatrick       const std::string &Str = S.str();
227e5dd7070Spatrick 
228e5dd7070Spatrick       // If replacement succeeded or warning disabled return with no warning.
229e5dd7070Spatrick       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
230e5dd7070Spatrick         ReplacedNodes[Old] = New;
231e5dd7070Spatrick         return;
232e5dd7070Spatrick       }
233e5dd7070Spatrick       if (SilenceRewriteMacroWarning)
234e5dd7070Spatrick         return;
235e5dd7070Spatrick       Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
236e5dd7070Spatrick           << Old->getSourceRange();
237e5dd7070Spatrick     }
238e5dd7070Spatrick 
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter=true)239e5dd7070Spatrick     void InsertText(SourceLocation Loc, StringRef Str,
240e5dd7070Spatrick                     bool InsertAfter = true) {
241e5dd7070Spatrick       // If insertion succeeded or warning disabled return with no warning.
242e5dd7070Spatrick       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
243e5dd7070Spatrick           SilenceRewriteMacroWarning)
244e5dd7070Spatrick         return;
245e5dd7070Spatrick 
246e5dd7070Spatrick       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
247e5dd7070Spatrick     }
248e5dd7070Spatrick 
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef Str)249e5dd7070Spatrick     void ReplaceText(SourceLocation Start, unsigned OrigLength,
250e5dd7070Spatrick                      StringRef Str) {
251e5dd7070Spatrick       // If removal succeeded or warning disabled return with no warning.
252e5dd7070Spatrick       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
253e5dd7070Spatrick           SilenceRewriteMacroWarning)
254e5dd7070Spatrick         return;
255e5dd7070Spatrick 
256e5dd7070Spatrick       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
257e5dd7070Spatrick     }
258e5dd7070Spatrick 
259e5dd7070Spatrick     // Syntactic Rewriting.
260e5dd7070Spatrick     void RewriteRecordBody(RecordDecl *RD);
261e5dd7070Spatrick     void RewriteInclude();
262e5dd7070Spatrick     void RewriteForwardClassDecl(DeclGroupRef D);
263e5dd7070Spatrick     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
264e5dd7070Spatrick     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
265e5dd7070Spatrick                                      const std::string &typedefString);
266e5dd7070Spatrick     void RewriteImplementations();
267e5dd7070Spatrick     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
268e5dd7070Spatrick                                  ObjCImplementationDecl *IMD,
269e5dd7070Spatrick                                  ObjCCategoryImplDecl *CID);
270e5dd7070Spatrick     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
271e5dd7070Spatrick     void RewriteImplementationDecl(Decl *Dcl);
272e5dd7070Spatrick     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
273e5dd7070Spatrick                                ObjCMethodDecl *MDecl, std::string &ResultStr);
274e5dd7070Spatrick     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
275e5dd7070Spatrick                                const FunctionType *&FPRetType);
276e5dd7070Spatrick     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
277e5dd7070Spatrick                             ValueDecl *VD, bool def=false);
278e5dd7070Spatrick     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
279e5dd7070Spatrick     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
280e5dd7070Spatrick     void RewriteForwardProtocolDecl(DeclGroupRef D);
281e5dd7070Spatrick     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
282e5dd7070Spatrick     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
283e5dd7070Spatrick     void RewriteProperty(ObjCPropertyDecl *prop);
284e5dd7070Spatrick     void RewriteFunctionDecl(FunctionDecl *FD);
285e5dd7070Spatrick     void RewriteBlockPointerType(std::string& Str, QualType Type);
286e5dd7070Spatrick     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
287e5dd7070Spatrick     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
288e5dd7070Spatrick     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
289e5dd7070Spatrick     void RewriteTypeOfDecl(VarDecl *VD);
290e5dd7070Spatrick     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
291e5dd7070Spatrick 
292e5dd7070Spatrick     // Expression Rewriting.
293e5dd7070Spatrick     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
294e5dd7070Spatrick     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
295e5dd7070Spatrick     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
296e5dd7070Spatrick     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
297e5dd7070Spatrick     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
298e5dd7070Spatrick     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
299e5dd7070Spatrick     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
300e5dd7070Spatrick     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
301e5dd7070Spatrick     void RewriteTryReturnStmts(Stmt *S);
302e5dd7070Spatrick     void RewriteSyncReturnStmts(Stmt *S, std::string buf);
303e5dd7070Spatrick     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
304e5dd7070Spatrick     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
305e5dd7070Spatrick     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
306e5dd7070Spatrick     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307e5dd7070Spatrick                                        SourceLocation OrigEnd);
308e5dd7070Spatrick     Stmt *RewriteBreakStmt(BreakStmt *S);
309e5dd7070Spatrick     Stmt *RewriteContinueStmt(ContinueStmt *S);
310e5dd7070Spatrick     void RewriteCastExpr(CStyleCastExpr *CE);
311e5dd7070Spatrick 
312e5dd7070Spatrick     // Block rewriting.
313e5dd7070Spatrick     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
314e5dd7070Spatrick 
315e5dd7070Spatrick     // Block specific rewrite rules.
316e5dd7070Spatrick     void RewriteBlockPointerDecl(NamedDecl *VD);
317e5dd7070Spatrick     void RewriteByRefVar(VarDecl *VD);
318e5dd7070Spatrick     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
319e5dd7070Spatrick     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
320e5dd7070Spatrick     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
321e5dd7070Spatrick 
322e5dd7070Spatrick     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
323e5dd7070Spatrick                                       std::string &Result);
324e5dd7070Spatrick 
325e5dd7070Spatrick     void Initialize(ASTContext &context) override = 0;
326e5dd7070Spatrick 
327e5dd7070Spatrick     // Metadata Rewriting.
328e5dd7070Spatrick     virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
329e5dd7070Spatrick     virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
330e5dd7070Spatrick                                                  StringRef prefix,
331e5dd7070Spatrick                                                  StringRef ClassName,
332e5dd7070Spatrick                                                  std::string &Result) = 0;
333e5dd7070Spatrick     virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
334e5dd7070Spatrick                                              std::string &Result) = 0;
335e5dd7070Spatrick     virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336e5dd7070Spatrick                                      StringRef prefix,
337e5dd7070Spatrick                                      StringRef ClassName,
338e5dd7070Spatrick                                      std::string &Result) = 0;
339e5dd7070Spatrick     virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
340e5dd7070Spatrick                                           std::string &Result) = 0;
341e5dd7070Spatrick 
342e5dd7070Spatrick     // Rewriting ivar access
343e5dd7070Spatrick     virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
344e5dd7070Spatrick     virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
345e5dd7070Spatrick                                          std::string &Result) = 0;
346e5dd7070Spatrick 
347e5dd7070Spatrick     // Misc. AST transformation routines. Sometimes they end up calling
348e5dd7070Spatrick     // rewriting routines on the new ASTs.
349e5dd7070Spatrick     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
350e5dd7070Spatrick                                            ArrayRef<Expr *> Args,
351e5dd7070Spatrick                                            SourceLocation StartLoc=SourceLocation(),
352e5dd7070Spatrick                                            SourceLocation EndLoc=SourceLocation());
353e5dd7070Spatrick     CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
354e5dd7070Spatrick                                         QualType msgSendType,
355e5dd7070Spatrick                                         QualType returnType,
356e5dd7070Spatrick                                         SmallVectorImpl<QualType> &ArgTypes,
357e5dd7070Spatrick                                         SmallVectorImpl<Expr*> &MsgExprs,
358e5dd7070Spatrick                                         ObjCMethodDecl *Method);
359e5dd7070Spatrick     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360e5dd7070Spatrick                            SourceLocation StartLoc=SourceLocation(),
361e5dd7070Spatrick                            SourceLocation EndLoc=SourceLocation());
362e5dd7070Spatrick 
363e5dd7070Spatrick     void SynthCountByEnumWithState(std::string &buf);
364e5dd7070Spatrick     void SynthMsgSendFunctionDecl();
365e5dd7070Spatrick     void SynthMsgSendSuperFunctionDecl();
366e5dd7070Spatrick     void SynthMsgSendStretFunctionDecl();
367e5dd7070Spatrick     void SynthMsgSendFpretFunctionDecl();
368e5dd7070Spatrick     void SynthMsgSendSuperStretFunctionDecl();
369e5dd7070Spatrick     void SynthGetClassFunctionDecl();
370e5dd7070Spatrick     void SynthGetMetaClassFunctionDecl();
371e5dd7070Spatrick     void SynthGetSuperClassFunctionDecl();
372e5dd7070Spatrick     void SynthSelGetUidFunctionDecl();
373e5dd7070Spatrick     void SynthSuperConstructorFunctionDecl();
374e5dd7070Spatrick 
375e5dd7070Spatrick     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
376e5dd7070Spatrick     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
377e5dd7070Spatrick                                       StringRef funcName, std::string Tag);
378e5dd7070Spatrick     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
379e5dd7070Spatrick                                       StringRef funcName, std::string Tag);
380e5dd7070Spatrick     std::string SynthesizeBlockImpl(BlockExpr *CE,
381e5dd7070Spatrick                                     std::string Tag, std::string Desc);
382e5dd7070Spatrick     std::string SynthesizeBlockDescriptor(std::string DescTag,
383e5dd7070Spatrick                                           std::string ImplTag,
384e5dd7070Spatrick                                           int i, StringRef funcName,
385e5dd7070Spatrick                                           unsigned hasCopy);
386e5dd7070Spatrick     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
387e5dd7070Spatrick     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
388e5dd7070Spatrick                                  StringRef FunName);
389e5dd7070Spatrick     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390e5dd7070Spatrick     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391e5dd7070Spatrick             const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
392e5dd7070Spatrick 
393e5dd7070Spatrick     // Misc. helper routines.
394e5dd7070Spatrick     QualType getProtocolType();
395e5dd7070Spatrick     void WarnAboutReturnGotoStmts(Stmt *S);
396e5dd7070Spatrick     void HasReturnStmts(Stmt *S, bool &hasReturns);
397e5dd7070Spatrick     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398e5dd7070Spatrick     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399e5dd7070Spatrick     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400e5dd7070Spatrick 
401e5dd7070Spatrick     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
402e5dd7070Spatrick     void CollectBlockDeclRefInfo(BlockExpr *Exp);
403e5dd7070Spatrick     void GetBlockDeclRefExprs(Stmt *S);
404e5dd7070Spatrick     void GetInnerBlockDeclRefExprs(Stmt *S,
405e5dd7070Spatrick                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
406e5dd7070Spatrick                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
407e5dd7070Spatrick 
408e5dd7070Spatrick     // We avoid calling Type::isBlockPointerType(), since it operates on the
409e5dd7070Spatrick     // canonical type. We only care if the top-level type is a closure pointer.
isTopLevelBlockPointerType(QualType T)410e5dd7070Spatrick     bool isTopLevelBlockPointerType(QualType T) {
411e5dd7070Spatrick       return isa<BlockPointerType>(T);
412e5dd7070Spatrick     }
413e5dd7070Spatrick 
414e5dd7070Spatrick     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415e5dd7070Spatrick     /// to a function pointer type and upon success, returns true; false
416e5dd7070Spatrick     /// otherwise.
convertBlockPointerToFunctionPointer(QualType & T)417e5dd7070Spatrick     bool convertBlockPointerToFunctionPointer(QualType &T) {
418e5dd7070Spatrick       if (isTopLevelBlockPointerType(T)) {
419e5dd7070Spatrick         const auto *BPT = T->castAs<BlockPointerType>();
420e5dd7070Spatrick         T = Context->getPointerType(BPT->getPointeeType());
421e5dd7070Spatrick         return true;
422e5dd7070Spatrick       }
423e5dd7070Spatrick       return false;
424e5dd7070Spatrick     }
425e5dd7070Spatrick 
426e5dd7070Spatrick     bool needToScanForQualifiers(QualType T);
427e5dd7070Spatrick     QualType getSuperStructType();
428e5dd7070Spatrick     QualType getConstantStringStructType();
429e5dd7070Spatrick     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430e5dd7070Spatrick     bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431e5dd7070Spatrick 
convertToUnqualifiedObjCType(QualType & T)432e5dd7070Spatrick     void convertToUnqualifiedObjCType(QualType &T) {
433e5dd7070Spatrick       if (T->isObjCQualifiedIdType())
434e5dd7070Spatrick         T = Context->getObjCIdType();
435e5dd7070Spatrick       else if (T->isObjCQualifiedClassType())
436e5dd7070Spatrick         T = Context->getObjCClassType();
437e5dd7070Spatrick       else if (T->isObjCObjectPointerType() &&
438e5dd7070Spatrick                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439e5dd7070Spatrick         if (const ObjCObjectPointerType * OBJPT =
440e5dd7070Spatrick               T->getAsObjCInterfacePointerType()) {
441e5dd7070Spatrick           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442e5dd7070Spatrick           T = QualType(IFaceT, 0);
443e5dd7070Spatrick           T = Context->getPointerType(T);
444e5dd7070Spatrick         }
445e5dd7070Spatrick      }
446e5dd7070Spatrick     }
447e5dd7070Spatrick 
448e5dd7070Spatrick     // FIXME: This predicate seems like it would be useful to add to ASTContext.
isObjCType(QualType T)449e5dd7070Spatrick     bool isObjCType(QualType T) {
450e5dd7070Spatrick       if (!LangOpts.ObjC)
451e5dd7070Spatrick         return false;
452e5dd7070Spatrick 
453e5dd7070Spatrick       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
454e5dd7070Spatrick 
455e5dd7070Spatrick       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456e5dd7070Spatrick           OCT == Context->getCanonicalType(Context->getObjCClassType()))
457e5dd7070Spatrick         return true;
458e5dd7070Spatrick 
459e5dd7070Spatrick       if (const PointerType *PT = OCT->getAs<PointerType>()) {
460e5dd7070Spatrick         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
461e5dd7070Spatrick             PT->getPointeeType()->isObjCQualifiedIdType())
462e5dd7070Spatrick           return true;
463e5dd7070Spatrick       }
464e5dd7070Spatrick       return false;
465e5dd7070Spatrick     }
466e5dd7070Spatrick     bool PointerTypeTakesAnyBlockArguments(QualType QT);
467e5dd7070Spatrick     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
468e5dd7070Spatrick     void GetExtentOfArgList(const char *Name, const char *&LParen,
469e5dd7070Spatrick                             const char *&RParen);
470e5dd7070Spatrick 
QuoteDoublequotes(std::string & From,std::string & To)471e5dd7070Spatrick     void QuoteDoublequotes(std::string &From, std::string &To) {
472e5dd7070Spatrick       for (unsigned i = 0; i < From.length(); i++) {
473e5dd7070Spatrick         if (From[i] == '"')
474e5dd7070Spatrick           To += "\\\"";
475e5dd7070Spatrick         else
476e5dd7070Spatrick           To += From[i];
477e5dd7070Spatrick       }
478e5dd7070Spatrick     }
479e5dd7070Spatrick 
getSimpleFunctionType(QualType result,ArrayRef<QualType> args,bool variadic=false)480e5dd7070Spatrick     QualType getSimpleFunctionType(QualType result,
481e5dd7070Spatrick                                    ArrayRef<QualType> args,
482e5dd7070Spatrick                                    bool variadic = false) {
483e5dd7070Spatrick       if (result == Context->getObjCInstanceType())
484e5dd7070Spatrick         result =  Context->getObjCIdType();
485e5dd7070Spatrick       FunctionProtoType::ExtProtoInfo fpi;
486e5dd7070Spatrick       fpi.Variadic = variadic;
487e5dd7070Spatrick       return Context->getFunctionType(result, args, fpi);
488e5dd7070Spatrick     }
489e5dd7070Spatrick 
490e5dd7070Spatrick     // Helper function: create a CStyleCastExpr with trivial type source info.
NoTypeInfoCStyleCastExpr(ASTContext * Ctx,QualType Ty,CastKind Kind,Expr * E)491e5dd7070Spatrick     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
492e5dd7070Spatrick                                              CastKind Kind, Expr *E) {
493e5dd7070Spatrick       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
494a9ac8606Spatrick       return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
495a9ac8606Spatrick                                     FPOptionsOverride(), TInfo,
496a9ac8606Spatrick                                     SourceLocation(), SourceLocation());
497e5dd7070Spatrick     }
498e5dd7070Spatrick 
getStringLiteral(StringRef Str)499e5dd7070Spatrick     StringLiteral *getStringLiteral(StringRef Str) {
500e5dd7070Spatrick       QualType StrType = Context->getConstantArrayType(
501e5dd7070Spatrick           Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
502e5dd7070Spatrick           ArrayType::Normal, 0);
503*12c85518Srobert       return StringLiteral::Create(*Context, Str, StringLiteral::Ordinary,
504e5dd7070Spatrick                                    /*Pascal=*/false, StrType, SourceLocation());
505e5dd7070Spatrick     }
506e5dd7070Spatrick   };
507e5dd7070Spatrick 
508e5dd7070Spatrick   class RewriteObjCFragileABI : public RewriteObjC {
509e5dd7070Spatrick   public:
RewriteObjCFragileABI(std::string inFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)510e5dd7070Spatrick     RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
511e5dd7070Spatrick                           DiagnosticsEngine &D, const LangOptions &LOpts,
512e5dd7070Spatrick                           bool silenceMacroWarn)
513e5dd7070Spatrick         : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
514e5dd7070Spatrick 
~RewriteObjCFragileABI()515e5dd7070Spatrick     ~RewriteObjCFragileABI() override {}
516e5dd7070Spatrick     void Initialize(ASTContext &context) override;
517e5dd7070Spatrick 
518e5dd7070Spatrick     // Rewriting metadata
519e5dd7070Spatrick     template<typename MethodIterator>
520e5dd7070Spatrick     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521e5dd7070Spatrick                                     MethodIterator MethodEnd,
522e5dd7070Spatrick                                     bool IsInstanceMethod,
523e5dd7070Spatrick                                     StringRef prefix,
524e5dd7070Spatrick                                     StringRef ClassName,
525e5dd7070Spatrick                                     std::string &Result);
526e5dd7070Spatrick     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527e5dd7070Spatrick                                      StringRef prefix, StringRef ClassName,
528e5dd7070Spatrick                                      std::string &Result) override;
529e5dd7070Spatrick     void RewriteObjCProtocolListMetaData(
530e5dd7070Spatrick           const ObjCList<ObjCProtocolDecl> &Prots,
531e5dd7070Spatrick           StringRef prefix, StringRef ClassName, std::string &Result) override;
532e5dd7070Spatrick     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533e5dd7070Spatrick                                   std::string &Result) override;
534e5dd7070Spatrick     void RewriteMetaDataIntoBuffer(std::string &Result) override;
535e5dd7070Spatrick     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536e5dd7070Spatrick                                      std::string &Result) override;
537e5dd7070Spatrick 
538e5dd7070Spatrick     // Rewriting ivar
539e5dd7070Spatrick     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540e5dd7070Spatrick                                       std::string &Result) override;
541e5dd7070Spatrick     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
542e5dd7070Spatrick   };
543e5dd7070Spatrick } // end anonymous namespace
544e5dd7070Spatrick 
RewriteBlocksInFunctionProtoType(QualType funcType,NamedDecl * D)545e5dd7070Spatrick void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546e5dd7070Spatrick                                                    NamedDecl *D) {
547e5dd7070Spatrick   if (const FunctionProtoType *fproto
548e5dd7070Spatrick       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
549e5dd7070Spatrick     for (const auto &I : fproto->param_types())
550e5dd7070Spatrick       if (isTopLevelBlockPointerType(I)) {
551e5dd7070Spatrick         // All the args are checked/rewritten. Don't call twice!
552e5dd7070Spatrick         RewriteBlockPointerDecl(D);
553e5dd7070Spatrick         break;
554e5dd7070Spatrick       }
555e5dd7070Spatrick   }
556e5dd7070Spatrick }
557e5dd7070Spatrick 
CheckFunctionPointerDecl(QualType funcType,NamedDecl * ND)558e5dd7070Spatrick void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
559e5dd7070Spatrick   const PointerType *PT = funcType->getAs<PointerType>();
560e5dd7070Spatrick   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
561e5dd7070Spatrick     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
562e5dd7070Spatrick }
563e5dd7070Spatrick 
IsHeaderFile(const std::string & Filename)564e5dd7070Spatrick static bool IsHeaderFile(const std::string &Filename) {
565e5dd7070Spatrick   std::string::size_type DotPos = Filename.rfind('.');
566e5dd7070Spatrick 
567e5dd7070Spatrick   if (DotPos == std::string::npos) {
568e5dd7070Spatrick     // no file extension
569e5dd7070Spatrick     return false;
570e5dd7070Spatrick   }
571e5dd7070Spatrick 
572*12c85518Srobert   std::string Ext = Filename.substr(DotPos + 1);
573e5dd7070Spatrick   // C header: .h
574e5dd7070Spatrick   // C++ header: .hh or .H;
575e5dd7070Spatrick   return Ext == "h" || Ext == "hh" || Ext == "H";
576e5dd7070Spatrick }
577e5dd7070Spatrick 
RewriteObjC(std::string inFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & D,const LangOptions & LOpts,bool silenceMacroWarn)578e5dd7070Spatrick RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
579e5dd7070Spatrick                          DiagnosticsEngine &D, const LangOptions &LOpts,
580e5dd7070Spatrick                          bool silenceMacroWarn)
581e5dd7070Spatrick     : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
582e5dd7070Spatrick       SilenceRewriteMacroWarning(silenceMacroWarn) {
583e5dd7070Spatrick   IsHeader = IsHeaderFile(inFile);
584e5dd7070Spatrick   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
585e5dd7070Spatrick                "rewriting sub-expression within a macro (may not be correct)");
586e5dd7070Spatrick   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587e5dd7070Spatrick                DiagnosticsEngine::Warning,
588e5dd7070Spatrick                "rewriter doesn't support user-specified control flow semantics "
589e5dd7070Spatrick                "for @try/@finally (code may not execute properly)");
590e5dd7070Spatrick }
591e5dd7070Spatrick 
592e5dd7070Spatrick std::unique_ptr<ASTConsumer>
CreateObjCRewriter(const std::string & InFile,std::unique_ptr<raw_ostream> OS,DiagnosticsEngine & Diags,const LangOptions & LOpts,bool SilenceRewriteMacroWarning)593e5dd7070Spatrick clang::CreateObjCRewriter(const std::string &InFile,
594e5dd7070Spatrick                           std::unique_ptr<raw_ostream> OS,
595e5dd7070Spatrick                           DiagnosticsEngine &Diags, const LangOptions &LOpts,
596e5dd7070Spatrick                           bool SilenceRewriteMacroWarning) {
597e5dd7070Spatrick   return std::make_unique<RewriteObjCFragileABI>(
598e5dd7070Spatrick       InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
599e5dd7070Spatrick }
600e5dd7070Spatrick 
InitializeCommon(ASTContext & context)601e5dd7070Spatrick void RewriteObjC::InitializeCommon(ASTContext &context) {
602e5dd7070Spatrick   Context = &context;
603e5dd7070Spatrick   SM = &Context->getSourceManager();
604e5dd7070Spatrick   TUDecl = Context->getTranslationUnitDecl();
605e5dd7070Spatrick   MsgSendFunctionDecl = nullptr;
606e5dd7070Spatrick   MsgSendSuperFunctionDecl = nullptr;
607e5dd7070Spatrick   MsgSendStretFunctionDecl = nullptr;
608e5dd7070Spatrick   MsgSendSuperStretFunctionDecl = nullptr;
609e5dd7070Spatrick   MsgSendFpretFunctionDecl = nullptr;
610e5dd7070Spatrick   GetClassFunctionDecl = nullptr;
611e5dd7070Spatrick   GetMetaClassFunctionDecl = nullptr;
612e5dd7070Spatrick   GetSuperClassFunctionDecl = nullptr;
613e5dd7070Spatrick   SelGetUidFunctionDecl = nullptr;
614e5dd7070Spatrick   CFStringFunctionDecl = nullptr;
615e5dd7070Spatrick   ConstantStringClassReference = nullptr;
616e5dd7070Spatrick   NSStringRecord = nullptr;
617e5dd7070Spatrick   CurMethodDef = nullptr;
618e5dd7070Spatrick   CurFunctionDef = nullptr;
619e5dd7070Spatrick   CurFunctionDeclToDeclareForBlock = nullptr;
620e5dd7070Spatrick   GlobalVarDecl = nullptr;
621e5dd7070Spatrick   SuperStructDecl = nullptr;
622e5dd7070Spatrick   ProtocolTypeDecl = nullptr;
623e5dd7070Spatrick   ConstantStringDecl = nullptr;
624e5dd7070Spatrick   BcLabelCount = 0;
625e5dd7070Spatrick   SuperConstructorFunctionDecl = nullptr;
626e5dd7070Spatrick   NumObjCStringLiterals = 0;
627e5dd7070Spatrick   PropParentMap = nullptr;
628e5dd7070Spatrick   CurrentBody = nullptr;
629e5dd7070Spatrick   DisableReplaceStmt = false;
630e5dd7070Spatrick   objc_impl_method = false;
631e5dd7070Spatrick 
632e5dd7070Spatrick   // Get the ID and start/end of the main file.
633e5dd7070Spatrick   MainFileID = SM->getMainFileID();
634a9ac8606Spatrick   llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
635a9ac8606Spatrick   MainFileStart = MainBuf.getBufferStart();
636a9ac8606Spatrick   MainFileEnd = MainBuf.getBufferEnd();
637e5dd7070Spatrick 
638e5dd7070Spatrick   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
639e5dd7070Spatrick }
640e5dd7070Spatrick 
641e5dd7070Spatrick //===----------------------------------------------------------------------===//
642e5dd7070Spatrick // Top Level Driver Code
643e5dd7070Spatrick //===----------------------------------------------------------------------===//
644e5dd7070Spatrick 
HandleTopLevelSingleDecl(Decl * D)645e5dd7070Spatrick void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
646e5dd7070Spatrick   if (Diags.hasErrorOccurred())
647e5dd7070Spatrick     return;
648e5dd7070Spatrick 
649e5dd7070Spatrick   // Two cases: either the decl could be in the main file, or it could be in a
650e5dd7070Spatrick   // #included file.  If the former, rewrite it now.  If the later, check to see
651e5dd7070Spatrick   // if we rewrote the #include/#import.
652e5dd7070Spatrick   SourceLocation Loc = D->getLocation();
653e5dd7070Spatrick   Loc = SM->getExpansionLoc(Loc);
654e5dd7070Spatrick 
655e5dd7070Spatrick   // If this is for a builtin, ignore it.
656e5dd7070Spatrick   if (Loc.isInvalid()) return;
657e5dd7070Spatrick 
658e5dd7070Spatrick   // Look for built-in declarations that we need to refer during the rewrite.
659e5dd7070Spatrick   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
660e5dd7070Spatrick     RewriteFunctionDecl(FD);
661e5dd7070Spatrick   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
662e5dd7070Spatrick     // declared in <Foundation/NSString.h>
663e5dd7070Spatrick     if (FVD->getName() == "_NSConstantStringClassReference") {
664e5dd7070Spatrick       ConstantStringClassReference = FVD;
665e5dd7070Spatrick       return;
666e5dd7070Spatrick     }
667e5dd7070Spatrick   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
668e5dd7070Spatrick     if (ID->isThisDeclarationADefinition())
669e5dd7070Spatrick       RewriteInterfaceDecl(ID);
670e5dd7070Spatrick   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
671e5dd7070Spatrick     RewriteCategoryDecl(CD);
672e5dd7070Spatrick   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
673e5dd7070Spatrick     if (PD->isThisDeclarationADefinition())
674e5dd7070Spatrick       RewriteProtocolDecl(PD);
675e5dd7070Spatrick   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
676e5dd7070Spatrick     // Recurse into linkage specifications
677e5dd7070Spatrick     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678e5dd7070Spatrick                                  DIEnd = LSD->decls_end();
679e5dd7070Spatrick          DI != DIEnd; ) {
680e5dd7070Spatrick       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
681e5dd7070Spatrick         if (!IFace->isThisDeclarationADefinition()) {
682e5dd7070Spatrick           SmallVector<Decl *, 8> DG;
683e5dd7070Spatrick           SourceLocation StartLoc = IFace->getBeginLoc();
684e5dd7070Spatrick           do {
685e5dd7070Spatrick             if (isa<ObjCInterfaceDecl>(*DI) &&
686e5dd7070Spatrick                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687e5dd7070Spatrick                 StartLoc == (*DI)->getBeginLoc())
688e5dd7070Spatrick               DG.push_back(*DI);
689e5dd7070Spatrick             else
690e5dd7070Spatrick               break;
691e5dd7070Spatrick 
692e5dd7070Spatrick             ++DI;
693e5dd7070Spatrick           } while (DI != DIEnd);
694e5dd7070Spatrick           RewriteForwardClassDecl(DG);
695e5dd7070Spatrick           continue;
696e5dd7070Spatrick         }
697e5dd7070Spatrick       }
698e5dd7070Spatrick 
699e5dd7070Spatrick       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
700e5dd7070Spatrick         if (!Proto->isThisDeclarationADefinition()) {
701e5dd7070Spatrick           SmallVector<Decl *, 8> DG;
702e5dd7070Spatrick           SourceLocation StartLoc = Proto->getBeginLoc();
703e5dd7070Spatrick           do {
704e5dd7070Spatrick             if (isa<ObjCProtocolDecl>(*DI) &&
705e5dd7070Spatrick                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706e5dd7070Spatrick                 StartLoc == (*DI)->getBeginLoc())
707e5dd7070Spatrick               DG.push_back(*DI);
708e5dd7070Spatrick             else
709e5dd7070Spatrick               break;
710e5dd7070Spatrick 
711e5dd7070Spatrick             ++DI;
712e5dd7070Spatrick           } while (DI != DIEnd);
713e5dd7070Spatrick           RewriteForwardProtocolDecl(DG);
714e5dd7070Spatrick           continue;
715e5dd7070Spatrick         }
716e5dd7070Spatrick       }
717e5dd7070Spatrick 
718e5dd7070Spatrick       HandleTopLevelSingleDecl(*DI);
719e5dd7070Spatrick       ++DI;
720e5dd7070Spatrick     }
721e5dd7070Spatrick   }
722e5dd7070Spatrick   // If we have a decl in the main file, see if we should rewrite it.
723e5dd7070Spatrick   if (SM->isWrittenInMainFile(Loc))
724e5dd7070Spatrick     return HandleDeclInMainFile(D);
725e5dd7070Spatrick }
726e5dd7070Spatrick 
727e5dd7070Spatrick //===----------------------------------------------------------------------===//
728e5dd7070Spatrick // Syntactic (non-AST) Rewriting Code
729e5dd7070Spatrick //===----------------------------------------------------------------------===//
730e5dd7070Spatrick 
RewriteInclude()731e5dd7070Spatrick void RewriteObjC::RewriteInclude() {
732e5dd7070Spatrick   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
733e5dd7070Spatrick   StringRef MainBuf = SM->getBufferData(MainFileID);
734e5dd7070Spatrick   const char *MainBufStart = MainBuf.begin();
735e5dd7070Spatrick   const char *MainBufEnd = MainBuf.end();
736e5dd7070Spatrick   size_t ImportLen = strlen("import");
737e5dd7070Spatrick 
738e5dd7070Spatrick   // Loop over the whole file, looking for includes.
739e5dd7070Spatrick   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740e5dd7070Spatrick     if (*BufPtr == '#') {
741e5dd7070Spatrick       if (++BufPtr == MainBufEnd)
742e5dd7070Spatrick         return;
743e5dd7070Spatrick       while (*BufPtr == ' ' || *BufPtr == '\t')
744e5dd7070Spatrick         if (++BufPtr == MainBufEnd)
745e5dd7070Spatrick           return;
746e5dd7070Spatrick       if (!strncmp(BufPtr, "import", ImportLen)) {
747e5dd7070Spatrick         // replace import with include
748e5dd7070Spatrick         SourceLocation ImportLoc =
749e5dd7070Spatrick           LocStart.getLocWithOffset(BufPtr-MainBufStart);
750e5dd7070Spatrick         ReplaceText(ImportLoc, ImportLen, "include");
751e5dd7070Spatrick         BufPtr += ImportLen;
752e5dd7070Spatrick       }
753e5dd7070Spatrick     }
754e5dd7070Spatrick   }
755e5dd7070Spatrick }
756e5dd7070Spatrick 
getIvarAccessString(ObjCIvarDecl * OID)757e5dd7070Spatrick static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758e5dd7070Spatrick   const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
759e5dd7070Spatrick   std::string S;
760e5dd7070Spatrick   S = "((struct ";
761e5dd7070Spatrick   S += ClassDecl->getIdentifier()->getName();
762e5dd7070Spatrick   S += "_IMPL *)self)->";
763e5dd7070Spatrick   S += OID->getName();
764e5dd7070Spatrick   return S;
765e5dd7070Spatrick }
766e5dd7070Spatrick 
RewritePropertyImplDecl(ObjCPropertyImplDecl * PID,ObjCImplementationDecl * IMD,ObjCCategoryImplDecl * CID)767e5dd7070Spatrick void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768e5dd7070Spatrick                                           ObjCImplementationDecl *IMD,
769e5dd7070Spatrick                                           ObjCCategoryImplDecl *CID) {
770e5dd7070Spatrick   static bool objcGetPropertyDefined = false;
771e5dd7070Spatrick   static bool objcSetPropertyDefined = false;
772e5dd7070Spatrick   SourceLocation startLoc = PID->getBeginLoc();
773e5dd7070Spatrick   InsertText(startLoc, "// ");
774e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
775e5dd7070Spatrick   assert((*startBuf == '@') && "bogus @synthesize location");
776e5dd7070Spatrick   const char *semiBuf = strchr(startBuf, ';');
777e5dd7070Spatrick   assert((*semiBuf == ';') && "@synthesize: can't find ';'");
778e5dd7070Spatrick   SourceLocation onePastSemiLoc =
779e5dd7070Spatrick     startLoc.getLocWithOffset(semiBuf-startBuf+1);
780e5dd7070Spatrick 
781e5dd7070Spatrick   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782e5dd7070Spatrick     return; // FIXME: is this correct?
783e5dd7070Spatrick 
784e5dd7070Spatrick   // Generate the 'getter' function.
785e5dd7070Spatrick   ObjCPropertyDecl *PD = PID->getPropertyDecl();
786e5dd7070Spatrick   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
787e5dd7070Spatrick 
788e5dd7070Spatrick   if (!OID)
789e5dd7070Spatrick     return;
790e5dd7070Spatrick 
791e5dd7070Spatrick   unsigned Attributes = PD->getPropertyAttributes();
792e5dd7070Spatrick   if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) {
793ec727ea7Spatrick     bool GenGetProperty =
794ec727ea7Spatrick         !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
795ec727ea7Spatrick         (Attributes & (ObjCPropertyAttribute::kind_retain |
796ec727ea7Spatrick                        ObjCPropertyAttribute::kind_copy));
797e5dd7070Spatrick     std::string Getr;
798e5dd7070Spatrick     if (GenGetProperty && !objcGetPropertyDefined) {
799e5dd7070Spatrick       objcGetPropertyDefined = true;
800e5dd7070Spatrick       // FIXME. Is this attribute correct in all cases?
801e5dd7070Spatrick       Getr = "\nextern \"C\" __declspec(dllimport) "
802e5dd7070Spatrick             "id objc_getProperty(id, SEL, long, bool);\n";
803e5dd7070Spatrick     }
804e5dd7070Spatrick     RewriteObjCMethodDecl(OID->getContainingInterface(),
805e5dd7070Spatrick                           PID->getGetterMethodDecl(), Getr);
806e5dd7070Spatrick     Getr += "{ ";
807e5dd7070Spatrick     // Synthesize an explicit cast to gain access to the ivar.
808e5dd7070Spatrick     // See objc-act.c:objc_synthesize_new_getter() for details.
809e5dd7070Spatrick     if (GenGetProperty) {
810e5dd7070Spatrick       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
811e5dd7070Spatrick       Getr += "typedef ";
812e5dd7070Spatrick       const FunctionType *FPRetType = nullptr;
813e5dd7070Spatrick       RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
814e5dd7070Spatrick                             FPRetType);
815e5dd7070Spatrick       Getr += " _TYPE";
816e5dd7070Spatrick       if (FPRetType) {
817e5dd7070Spatrick         Getr += ")"; // close the precedence "scope" for "*".
818e5dd7070Spatrick 
819e5dd7070Spatrick         // Now, emit the argument types (if any).
820e5dd7070Spatrick         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
821e5dd7070Spatrick           Getr += "(";
822e5dd7070Spatrick           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
823e5dd7070Spatrick             if (i) Getr += ", ";
824e5dd7070Spatrick             std::string ParamStr =
825e5dd7070Spatrick                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
826e5dd7070Spatrick             Getr += ParamStr;
827e5dd7070Spatrick           }
828e5dd7070Spatrick           if (FT->isVariadic()) {
829e5dd7070Spatrick             if (FT->getNumParams())
830e5dd7070Spatrick               Getr += ", ";
831e5dd7070Spatrick             Getr += "...";
832e5dd7070Spatrick           }
833e5dd7070Spatrick           Getr += ")";
834e5dd7070Spatrick         } else
835e5dd7070Spatrick           Getr += "()";
836e5dd7070Spatrick       }
837e5dd7070Spatrick       Getr += ";\n";
838e5dd7070Spatrick       Getr += "return (_TYPE)";
839e5dd7070Spatrick       Getr += "objc_getProperty(self, _cmd, ";
840e5dd7070Spatrick       RewriteIvarOffsetComputation(OID, Getr);
841e5dd7070Spatrick       Getr += ", 1)";
842e5dd7070Spatrick     }
843e5dd7070Spatrick     else
844e5dd7070Spatrick       Getr += "return " + getIvarAccessString(OID);
845e5dd7070Spatrick     Getr += "; }";
846e5dd7070Spatrick     InsertText(onePastSemiLoc, Getr);
847e5dd7070Spatrick   }
848e5dd7070Spatrick 
849e5dd7070Spatrick   if (PD->isReadOnly() || !PID->getSetterMethodDecl() ||
850e5dd7070Spatrick       PID->getSetterMethodDecl()->isDefined())
851e5dd7070Spatrick     return;
852e5dd7070Spatrick 
853e5dd7070Spatrick   // Generate the 'setter' function.
854e5dd7070Spatrick   std::string Setr;
855ec727ea7Spatrick   bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
856ec727ea7Spatrick                                       ObjCPropertyAttribute::kind_copy);
857e5dd7070Spatrick   if (GenSetProperty && !objcSetPropertyDefined) {
858e5dd7070Spatrick     objcSetPropertyDefined = true;
859e5dd7070Spatrick     // FIXME. Is this attribute correct in all cases?
860e5dd7070Spatrick     Setr = "\nextern \"C\" __declspec(dllimport) "
861e5dd7070Spatrick     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
862e5dd7070Spatrick   }
863e5dd7070Spatrick 
864e5dd7070Spatrick   RewriteObjCMethodDecl(OID->getContainingInterface(),
865e5dd7070Spatrick                         PID->getSetterMethodDecl(), Setr);
866e5dd7070Spatrick   Setr += "{ ";
867e5dd7070Spatrick   // Synthesize an explicit cast to initialize the ivar.
868e5dd7070Spatrick   // See objc-act.c:objc_synthesize_new_setter() for details.
869e5dd7070Spatrick   if (GenSetProperty) {
870e5dd7070Spatrick     Setr += "objc_setProperty (self, _cmd, ";
871e5dd7070Spatrick     RewriteIvarOffsetComputation(OID, Setr);
872e5dd7070Spatrick     Setr += ", (id)";
873e5dd7070Spatrick     Setr += PD->getName();
874e5dd7070Spatrick     Setr += ", ";
875ec727ea7Spatrick     if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
876e5dd7070Spatrick       Setr += "0, ";
877e5dd7070Spatrick     else
878e5dd7070Spatrick       Setr += "1, ";
879ec727ea7Spatrick     if (Attributes & ObjCPropertyAttribute::kind_copy)
880e5dd7070Spatrick       Setr += "1)";
881e5dd7070Spatrick     else
882e5dd7070Spatrick       Setr += "0)";
883e5dd7070Spatrick   }
884e5dd7070Spatrick   else {
885e5dd7070Spatrick     Setr += getIvarAccessString(OID) + " = ";
886e5dd7070Spatrick     Setr += PD->getName();
887e5dd7070Spatrick   }
888e5dd7070Spatrick   Setr += "; }";
889e5dd7070Spatrick   InsertText(onePastSemiLoc, Setr);
890e5dd7070Spatrick }
891e5dd7070Spatrick 
RewriteOneForwardClassDecl(ObjCInterfaceDecl * ForwardDecl,std::string & typedefString)892e5dd7070Spatrick static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
893e5dd7070Spatrick                                        std::string &typedefString) {
894e5dd7070Spatrick   typedefString += "#ifndef _REWRITER_typedef_";
895e5dd7070Spatrick   typedefString += ForwardDecl->getNameAsString();
896e5dd7070Spatrick   typedefString += "\n";
897e5dd7070Spatrick   typedefString += "#define _REWRITER_typedef_";
898e5dd7070Spatrick   typedefString += ForwardDecl->getNameAsString();
899e5dd7070Spatrick   typedefString += "\n";
900e5dd7070Spatrick   typedefString += "typedef struct objc_object ";
901e5dd7070Spatrick   typedefString += ForwardDecl->getNameAsString();
902e5dd7070Spatrick   typedefString += ";\n#endif\n";
903e5dd7070Spatrick }
904e5dd7070Spatrick 
RewriteForwardClassEpilogue(ObjCInterfaceDecl * ClassDecl,const std::string & typedefString)905e5dd7070Spatrick void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
906e5dd7070Spatrick                                               const std::string &typedefString) {
907e5dd7070Spatrick   SourceLocation startLoc = ClassDecl->getBeginLoc();
908e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
909e5dd7070Spatrick   const char *semiPtr = strchr(startBuf, ';');
910e5dd7070Spatrick   // Replace the @class with typedefs corresponding to the classes.
911e5dd7070Spatrick   ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
912e5dd7070Spatrick }
913e5dd7070Spatrick 
RewriteForwardClassDecl(DeclGroupRef D)914e5dd7070Spatrick void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
915e5dd7070Spatrick   std::string typedefString;
916e5dd7070Spatrick   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
917e5dd7070Spatrick     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
918e5dd7070Spatrick     if (I == D.begin()) {
919e5dd7070Spatrick       // Translate to typedef's that forward reference structs with the same name
920e5dd7070Spatrick       // as the class. As a convenience, we include the original declaration
921e5dd7070Spatrick       // as a comment.
922e5dd7070Spatrick       typedefString += "// @class ";
923e5dd7070Spatrick       typedefString += ForwardDecl->getNameAsString();
924e5dd7070Spatrick       typedefString += ";\n";
925e5dd7070Spatrick     }
926e5dd7070Spatrick     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
927e5dd7070Spatrick   }
928e5dd7070Spatrick   DeclGroupRef::iterator I = D.begin();
929e5dd7070Spatrick   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
930e5dd7070Spatrick }
931e5dd7070Spatrick 
RewriteForwardClassDecl(const SmallVectorImpl<Decl * > & D)932e5dd7070Spatrick void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
933e5dd7070Spatrick   std::string typedefString;
934e5dd7070Spatrick   for (unsigned i = 0; i < D.size(); i++) {
935e5dd7070Spatrick     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
936e5dd7070Spatrick     if (i == 0) {
937e5dd7070Spatrick       typedefString += "// @class ";
938e5dd7070Spatrick       typedefString += ForwardDecl->getNameAsString();
939e5dd7070Spatrick       typedefString += ";\n";
940e5dd7070Spatrick     }
941e5dd7070Spatrick     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
942e5dd7070Spatrick   }
943e5dd7070Spatrick   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
944e5dd7070Spatrick }
945e5dd7070Spatrick 
RewriteMethodDeclaration(ObjCMethodDecl * Method)946e5dd7070Spatrick void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
947e5dd7070Spatrick   // When method is a synthesized one, such as a getter/setter there is
948e5dd7070Spatrick   // nothing to rewrite.
949e5dd7070Spatrick   if (Method->isImplicit())
950e5dd7070Spatrick     return;
951e5dd7070Spatrick   SourceLocation LocStart = Method->getBeginLoc();
952e5dd7070Spatrick   SourceLocation LocEnd = Method->getEndLoc();
953e5dd7070Spatrick 
954e5dd7070Spatrick   if (SM->getExpansionLineNumber(LocEnd) >
955e5dd7070Spatrick       SM->getExpansionLineNumber(LocStart)) {
956e5dd7070Spatrick     InsertText(LocStart, "#if 0\n");
957e5dd7070Spatrick     ReplaceText(LocEnd, 1, ";\n#endif\n");
958e5dd7070Spatrick   } else {
959e5dd7070Spatrick     InsertText(LocStart, "// ");
960e5dd7070Spatrick   }
961e5dd7070Spatrick }
962e5dd7070Spatrick 
RewriteProperty(ObjCPropertyDecl * prop)963e5dd7070Spatrick void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
964e5dd7070Spatrick   SourceLocation Loc = prop->getAtLoc();
965e5dd7070Spatrick 
966e5dd7070Spatrick   ReplaceText(Loc, 0, "// ");
967e5dd7070Spatrick   // FIXME: handle properties that are declared across multiple lines.
968e5dd7070Spatrick }
969e5dd7070Spatrick 
RewriteCategoryDecl(ObjCCategoryDecl * CatDecl)970e5dd7070Spatrick void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
971e5dd7070Spatrick   SourceLocation LocStart = CatDecl->getBeginLoc();
972e5dd7070Spatrick 
973e5dd7070Spatrick   // FIXME: handle category headers that are declared across multiple lines.
974e5dd7070Spatrick   ReplaceText(LocStart, 0, "// ");
975e5dd7070Spatrick 
976e5dd7070Spatrick   for (auto *I : CatDecl->instance_properties())
977e5dd7070Spatrick     RewriteProperty(I);
978e5dd7070Spatrick   for (auto *I : CatDecl->instance_methods())
979e5dd7070Spatrick     RewriteMethodDeclaration(I);
980e5dd7070Spatrick   for (auto *I : CatDecl->class_methods())
981e5dd7070Spatrick     RewriteMethodDeclaration(I);
982e5dd7070Spatrick 
983e5dd7070Spatrick   // Lastly, comment out the @end.
984e5dd7070Spatrick   ReplaceText(CatDecl->getAtEndRange().getBegin(),
985e5dd7070Spatrick               strlen("@end"), "/* @end */");
986e5dd7070Spatrick }
987e5dd7070Spatrick 
RewriteProtocolDecl(ObjCProtocolDecl * PDecl)988e5dd7070Spatrick void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
989e5dd7070Spatrick   SourceLocation LocStart = PDecl->getBeginLoc();
990e5dd7070Spatrick   assert(PDecl->isThisDeclarationADefinition());
991e5dd7070Spatrick 
992e5dd7070Spatrick   // FIXME: handle protocol headers that are declared across multiple lines.
993e5dd7070Spatrick   ReplaceText(LocStart, 0, "// ");
994e5dd7070Spatrick 
995e5dd7070Spatrick   for (auto *I : PDecl->instance_methods())
996e5dd7070Spatrick     RewriteMethodDeclaration(I);
997e5dd7070Spatrick   for (auto *I : PDecl->class_methods())
998e5dd7070Spatrick     RewriteMethodDeclaration(I);
999e5dd7070Spatrick   for (auto *I : PDecl->instance_properties())
1000e5dd7070Spatrick     RewriteProperty(I);
1001e5dd7070Spatrick 
1002e5dd7070Spatrick   // Lastly, comment out the @end.
1003e5dd7070Spatrick   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1004e5dd7070Spatrick   ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1005e5dd7070Spatrick 
1006e5dd7070Spatrick   // Must comment out @optional/@required
1007e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(LocStart);
1008e5dd7070Spatrick   const char *endBuf = SM->getCharacterData(LocEnd);
1009e5dd7070Spatrick   for (const char *p = startBuf; p < endBuf; p++) {
1010e5dd7070Spatrick     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1011e5dd7070Spatrick       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1012e5dd7070Spatrick       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1013e5dd7070Spatrick 
1014e5dd7070Spatrick     }
1015e5dd7070Spatrick     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1016e5dd7070Spatrick       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1017e5dd7070Spatrick       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1018e5dd7070Spatrick 
1019e5dd7070Spatrick     }
1020e5dd7070Spatrick   }
1021e5dd7070Spatrick }
1022e5dd7070Spatrick 
RewriteForwardProtocolDecl(DeclGroupRef D)1023e5dd7070Spatrick void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1024e5dd7070Spatrick   SourceLocation LocStart = (*D.begin())->getBeginLoc();
1025e5dd7070Spatrick   if (LocStart.isInvalid())
1026e5dd7070Spatrick     llvm_unreachable("Invalid SourceLocation");
1027e5dd7070Spatrick   // FIXME: handle forward protocol that are declared across multiple lines.
1028e5dd7070Spatrick   ReplaceText(LocStart, 0, "// ");
1029e5dd7070Spatrick }
1030e5dd7070Spatrick 
1031e5dd7070Spatrick void
RewriteForwardProtocolDecl(const SmallVectorImpl<Decl * > & DG)1032e5dd7070Spatrick RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1033e5dd7070Spatrick   SourceLocation LocStart = DG[0]->getBeginLoc();
1034e5dd7070Spatrick   if (LocStart.isInvalid())
1035e5dd7070Spatrick     llvm_unreachable("Invalid SourceLocation");
1036e5dd7070Spatrick   // FIXME: handle forward protocol that are declared across multiple lines.
1037e5dd7070Spatrick   ReplaceText(LocStart, 0, "// ");
1038e5dd7070Spatrick }
1039e5dd7070Spatrick 
RewriteTypeIntoString(QualType T,std::string & ResultStr,const FunctionType * & FPRetType)1040e5dd7070Spatrick void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1041e5dd7070Spatrick                                         const FunctionType *&FPRetType) {
1042e5dd7070Spatrick   if (T->isObjCQualifiedIdType())
1043e5dd7070Spatrick     ResultStr += "id";
1044e5dd7070Spatrick   else if (T->isFunctionPointerType() ||
1045e5dd7070Spatrick            T->isBlockPointerType()) {
1046e5dd7070Spatrick     // needs special handling, since pointer-to-functions have special
1047e5dd7070Spatrick     // syntax (where a decaration models use).
1048e5dd7070Spatrick     QualType retType = T;
1049e5dd7070Spatrick     QualType PointeeTy;
1050e5dd7070Spatrick     if (const PointerType* PT = retType->getAs<PointerType>())
1051e5dd7070Spatrick       PointeeTy = PT->getPointeeType();
1052e5dd7070Spatrick     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1053e5dd7070Spatrick       PointeeTy = BPT->getPointeeType();
1054e5dd7070Spatrick     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1055e5dd7070Spatrick       ResultStr +=
1056e5dd7070Spatrick           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1057e5dd7070Spatrick       ResultStr += "(*";
1058e5dd7070Spatrick     }
1059e5dd7070Spatrick   } else
1060e5dd7070Spatrick     ResultStr += T.getAsString(Context->getPrintingPolicy());
1061e5dd7070Spatrick }
1062e5dd7070Spatrick 
RewriteObjCMethodDecl(const ObjCInterfaceDecl * IDecl,ObjCMethodDecl * OMD,std::string & ResultStr)1063e5dd7070Spatrick void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1064e5dd7070Spatrick                                         ObjCMethodDecl *OMD,
1065e5dd7070Spatrick                                         std::string &ResultStr) {
1066e5dd7070Spatrick   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1067e5dd7070Spatrick   const FunctionType *FPRetType = nullptr;
1068e5dd7070Spatrick   ResultStr += "\nstatic ";
1069e5dd7070Spatrick   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1070e5dd7070Spatrick   ResultStr += " ";
1071e5dd7070Spatrick 
1072e5dd7070Spatrick   // Unique method name
1073e5dd7070Spatrick   std::string NameStr;
1074e5dd7070Spatrick 
1075e5dd7070Spatrick   if (OMD->isInstanceMethod())
1076e5dd7070Spatrick     NameStr += "_I_";
1077e5dd7070Spatrick   else
1078e5dd7070Spatrick     NameStr += "_C_";
1079e5dd7070Spatrick 
1080e5dd7070Spatrick   NameStr += IDecl->getNameAsString();
1081e5dd7070Spatrick   NameStr += "_";
1082e5dd7070Spatrick 
1083e5dd7070Spatrick   if (ObjCCategoryImplDecl *CID =
1084e5dd7070Spatrick       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1085e5dd7070Spatrick     NameStr += CID->getNameAsString();
1086e5dd7070Spatrick     NameStr += "_";
1087e5dd7070Spatrick   }
1088e5dd7070Spatrick   // Append selector names, replacing ':' with '_'
1089e5dd7070Spatrick   {
1090e5dd7070Spatrick     std::string selString = OMD->getSelector().getAsString();
1091e5dd7070Spatrick     int len = selString.size();
1092e5dd7070Spatrick     for (int i = 0; i < len; i++)
1093e5dd7070Spatrick       if (selString[i] == ':')
1094e5dd7070Spatrick         selString[i] = '_';
1095e5dd7070Spatrick     NameStr += selString;
1096e5dd7070Spatrick   }
1097e5dd7070Spatrick   // Remember this name for metadata emission
1098e5dd7070Spatrick   MethodInternalNames[OMD] = NameStr;
1099e5dd7070Spatrick   ResultStr += NameStr;
1100e5dd7070Spatrick 
1101e5dd7070Spatrick   // Rewrite arguments
1102e5dd7070Spatrick   ResultStr += "(";
1103e5dd7070Spatrick 
1104e5dd7070Spatrick   // invisible arguments
1105e5dd7070Spatrick   if (OMD->isInstanceMethod()) {
1106e5dd7070Spatrick     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1107e5dd7070Spatrick     selfTy = Context->getPointerType(selfTy);
1108e5dd7070Spatrick     if (!LangOpts.MicrosoftExt) {
1109e5dd7070Spatrick       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1110e5dd7070Spatrick         ResultStr += "struct ";
1111e5dd7070Spatrick     }
1112e5dd7070Spatrick     // When rewriting for Microsoft, explicitly omit the structure name.
1113e5dd7070Spatrick     ResultStr += IDecl->getNameAsString();
1114e5dd7070Spatrick     ResultStr += " *";
1115e5dd7070Spatrick   }
1116e5dd7070Spatrick   else
1117e5dd7070Spatrick     ResultStr += Context->getObjCClassType().getAsString(
1118e5dd7070Spatrick       Context->getPrintingPolicy());
1119e5dd7070Spatrick 
1120e5dd7070Spatrick   ResultStr += " self, ";
1121e5dd7070Spatrick   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1122e5dd7070Spatrick   ResultStr += " _cmd";
1123e5dd7070Spatrick 
1124e5dd7070Spatrick   // Method arguments.
1125e5dd7070Spatrick   for (const auto *PDecl : OMD->parameters()) {
1126e5dd7070Spatrick     ResultStr += ", ";
1127e5dd7070Spatrick     if (PDecl->getType()->isObjCQualifiedIdType()) {
1128e5dd7070Spatrick       ResultStr += "id ";
1129e5dd7070Spatrick       ResultStr += PDecl->getNameAsString();
1130e5dd7070Spatrick     } else {
1131e5dd7070Spatrick       std::string Name = PDecl->getNameAsString();
1132e5dd7070Spatrick       QualType QT = PDecl->getType();
1133e5dd7070Spatrick       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1134e5dd7070Spatrick       (void)convertBlockPointerToFunctionPointer(QT);
1135e5dd7070Spatrick       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1136e5dd7070Spatrick       ResultStr += Name;
1137e5dd7070Spatrick     }
1138e5dd7070Spatrick   }
1139e5dd7070Spatrick   if (OMD->isVariadic())
1140e5dd7070Spatrick     ResultStr += ", ...";
1141e5dd7070Spatrick   ResultStr += ") ";
1142e5dd7070Spatrick 
1143e5dd7070Spatrick   if (FPRetType) {
1144e5dd7070Spatrick     ResultStr += ")"; // close the precedence "scope" for "*".
1145e5dd7070Spatrick 
1146e5dd7070Spatrick     // Now, emit the argument types (if any).
1147e5dd7070Spatrick     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1148e5dd7070Spatrick       ResultStr += "(";
1149e5dd7070Spatrick       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1150e5dd7070Spatrick         if (i) ResultStr += ", ";
1151e5dd7070Spatrick         std::string ParamStr =
1152e5dd7070Spatrick             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1153e5dd7070Spatrick         ResultStr += ParamStr;
1154e5dd7070Spatrick       }
1155e5dd7070Spatrick       if (FT->isVariadic()) {
1156e5dd7070Spatrick         if (FT->getNumParams())
1157e5dd7070Spatrick           ResultStr += ", ";
1158e5dd7070Spatrick         ResultStr += "...";
1159e5dd7070Spatrick       }
1160e5dd7070Spatrick       ResultStr += ")";
1161e5dd7070Spatrick     } else {
1162e5dd7070Spatrick       ResultStr += "()";
1163e5dd7070Spatrick     }
1164e5dd7070Spatrick   }
1165e5dd7070Spatrick }
1166e5dd7070Spatrick 
RewriteImplementationDecl(Decl * OID)1167e5dd7070Spatrick void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1168e5dd7070Spatrick   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1169e5dd7070Spatrick   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1170e5dd7070Spatrick   assert((IMD || CID) && "Unknown ImplementationDecl");
1171e5dd7070Spatrick 
1172e5dd7070Spatrick   InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// ");
1173e5dd7070Spatrick 
1174e5dd7070Spatrick   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1175e5dd7070Spatrick     if (!OMD->getBody())
1176e5dd7070Spatrick       continue;
1177e5dd7070Spatrick     std::string ResultStr;
1178e5dd7070Spatrick     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1179e5dd7070Spatrick     SourceLocation LocStart = OMD->getBeginLoc();
1180e5dd7070Spatrick     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1181e5dd7070Spatrick 
1182e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(LocStart);
1183e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(LocEnd);
1184e5dd7070Spatrick     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1185e5dd7070Spatrick   }
1186e5dd7070Spatrick 
1187e5dd7070Spatrick   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1188e5dd7070Spatrick     if (!OMD->getBody())
1189e5dd7070Spatrick       continue;
1190e5dd7070Spatrick     std::string ResultStr;
1191e5dd7070Spatrick     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1192e5dd7070Spatrick     SourceLocation LocStart = OMD->getBeginLoc();
1193e5dd7070Spatrick     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1194e5dd7070Spatrick 
1195e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(LocStart);
1196e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(LocEnd);
1197e5dd7070Spatrick     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1198e5dd7070Spatrick   }
1199e5dd7070Spatrick   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1200e5dd7070Spatrick     RewritePropertyImplDecl(I, IMD, CID);
1201e5dd7070Spatrick 
1202e5dd7070Spatrick   InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1203e5dd7070Spatrick }
1204e5dd7070Spatrick 
RewriteInterfaceDecl(ObjCInterfaceDecl * ClassDecl)1205e5dd7070Spatrick void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1206e5dd7070Spatrick   std::string ResultStr;
1207e5dd7070Spatrick   if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1208e5dd7070Spatrick     // we haven't seen a forward decl - generate a typedef.
1209e5dd7070Spatrick     ResultStr = "#ifndef _REWRITER_typedef_";
1210e5dd7070Spatrick     ResultStr += ClassDecl->getNameAsString();
1211e5dd7070Spatrick     ResultStr += "\n";
1212e5dd7070Spatrick     ResultStr += "#define _REWRITER_typedef_";
1213e5dd7070Spatrick     ResultStr += ClassDecl->getNameAsString();
1214e5dd7070Spatrick     ResultStr += "\n";
1215e5dd7070Spatrick     ResultStr += "typedef struct objc_object ";
1216e5dd7070Spatrick     ResultStr += ClassDecl->getNameAsString();
1217e5dd7070Spatrick     ResultStr += ";\n#endif\n";
1218e5dd7070Spatrick     // Mark this typedef as having been generated.
1219e5dd7070Spatrick     ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1220e5dd7070Spatrick   }
1221e5dd7070Spatrick   RewriteObjCInternalStruct(ClassDecl, ResultStr);
1222e5dd7070Spatrick 
1223e5dd7070Spatrick   for (auto *I : ClassDecl->instance_properties())
1224e5dd7070Spatrick     RewriteProperty(I);
1225e5dd7070Spatrick   for (auto *I : ClassDecl->instance_methods())
1226e5dd7070Spatrick     RewriteMethodDeclaration(I);
1227e5dd7070Spatrick   for (auto *I : ClassDecl->class_methods())
1228e5dd7070Spatrick     RewriteMethodDeclaration(I);
1229e5dd7070Spatrick 
1230e5dd7070Spatrick   // Lastly, comment out the @end.
1231e5dd7070Spatrick   ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1232e5dd7070Spatrick               "/* @end */");
1233e5dd7070Spatrick }
1234e5dd7070Spatrick 
RewritePropertyOrImplicitSetter(PseudoObjectExpr * PseudoOp)1235e5dd7070Spatrick Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1236e5dd7070Spatrick   SourceRange OldRange = PseudoOp->getSourceRange();
1237e5dd7070Spatrick 
1238e5dd7070Spatrick   // We just magically know some things about the structure of this
1239e5dd7070Spatrick   // expression.
1240e5dd7070Spatrick   ObjCMessageExpr *OldMsg =
1241e5dd7070Spatrick     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1242e5dd7070Spatrick                             PseudoOp->getNumSemanticExprs() - 1));
1243e5dd7070Spatrick 
1244e5dd7070Spatrick   // Because the rewriter doesn't allow us to rewrite rewritten code,
1245e5dd7070Spatrick   // we need to suppress rewriting the sub-statements.
1246e5dd7070Spatrick   Expr *Base, *RHS;
1247e5dd7070Spatrick   {
1248e5dd7070Spatrick     DisableReplaceStmtScope S(*this);
1249e5dd7070Spatrick 
1250e5dd7070Spatrick     // Rebuild the base expression if we have one.
1251e5dd7070Spatrick     Base = nullptr;
1252e5dd7070Spatrick     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1253e5dd7070Spatrick       Base = OldMsg->getInstanceReceiver();
1254e5dd7070Spatrick       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1255e5dd7070Spatrick       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1256e5dd7070Spatrick     }
1257e5dd7070Spatrick 
1258e5dd7070Spatrick     // Rebuild the RHS.
1259e5dd7070Spatrick     RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1260e5dd7070Spatrick     RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1261e5dd7070Spatrick     RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1262e5dd7070Spatrick   }
1263e5dd7070Spatrick 
1264e5dd7070Spatrick   // TODO: avoid this copy.
1265e5dd7070Spatrick   SmallVector<SourceLocation, 1> SelLocs;
1266e5dd7070Spatrick   OldMsg->getSelectorLocs(SelLocs);
1267e5dd7070Spatrick 
1268e5dd7070Spatrick   ObjCMessageExpr *NewMsg = nullptr;
1269e5dd7070Spatrick   switch (OldMsg->getReceiverKind()) {
1270e5dd7070Spatrick   case ObjCMessageExpr::Class:
1271e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1272e5dd7070Spatrick                                      OldMsg->getValueKind(),
1273e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1274e5dd7070Spatrick                                      OldMsg->getClassReceiverTypeInfo(),
1275e5dd7070Spatrick                                      OldMsg->getSelector(),
1276e5dd7070Spatrick                                      SelLocs,
1277e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1278e5dd7070Spatrick                                      RHS,
1279e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1280e5dd7070Spatrick                                      OldMsg->isImplicit());
1281e5dd7070Spatrick     break;
1282e5dd7070Spatrick 
1283e5dd7070Spatrick   case ObjCMessageExpr::Instance:
1284e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1285e5dd7070Spatrick                                      OldMsg->getValueKind(),
1286e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1287e5dd7070Spatrick                                      Base,
1288e5dd7070Spatrick                                      OldMsg->getSelector(),
1289e5dd7070Spatrick                                      SelLocs,
1290e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1291e5dd7070Spatrick                                      RHS,
1292e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1293e5dd7070Spatrick                                      OldMsg->isImplicit());
1294e5dd7070Spatrick     break;
1295e5dd7070Spatrick 
1296e5dd7070Spatrick   case ObjCMessageExpr::SuperClass:
1297e5dd7070Spatrick   case ObjCMessageExpr::SuperInstance:
1298e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1299e5dd7070Spatrick                                      OldMsg->getValueKind(),
1300e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1301e5dd7070Spatrick                                      OldMsg->getSuperLoc(),
1302e5dd7070Spatrick                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1303e5dd7070Spatrick                                      OldMsg->getSuperType(),
1304e5dd7070Spatrick                                      OldMsg->getSelector(),
1305e5dd7070Spatrick                                      SelLocs,
1306e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1307e5dd7070Spatrick                                      RHS,
1308e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1309e5dd7070Spatrick                                      OldMsg->isImplicit());
1310e5dd7070Spatrick     break;
1311e5dd7070Spatrick   }
1312e5dd7070Spatrick 
1313e5dd7070Spatrick   Stmt *Replacement = SynthMessageExpr(NewMsg);
1314e5dd7070Spatrick   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1315e5dd7070Spatrick   return Replacement;
1316e5dd7070Spatrick }
1317e5dd7070Spatrick 
RewritePropertyOrImplicitGetter(PseudoObjectExpr * PseudoOp)1318e5dd7070Spatrick Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1319e5dd7070Spatrick   SourceRange OldRange = PseudoOp->getSourceRange();
1320e5dd7070Spatrick 
1321e5dd7070Spatrick   // We just magically know some things about the structure of this
1322e5dd7070Spatrick   // expression.
1323e5dd7070Spatrick   ObjCMessageExpr *OldMsg =
1324e5dd7070Spatrick     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1325e5dd7070Spatrick 
1326e5dd7070Spatrick   // Because the rewriter doesn't allow us to rewrite rewritten code,
1327e5dd7070Spatrick   // we need to suppress rewriting the sub-statements.
1328e5dd7070Spatrick   Expr *Base = nullptr;
1329e5dd7070Spatrick   {
1330e5dd7070Spatrick     DisableReplaceStmtScope S(*this);
1331e5dd7070Spatrick 
1332e5dd7070Spatrick     // Rebuild the base expression if we have one.
1333e5dd7070Spatrick     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1334e5dd7070Spatrick       Base = OldMsg->getInstanceReceiver();
1335e5dd7070Spatrick       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1336e5dd7070Spatrick       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1337e5dd7070Spatrick     }
1338e5dd7070Spatrick   }
1339e5dd7070Spatrick 
1340e5dd7070Spatrick   // Intentionally empty.
1341e5dd7070Spatrick   SmallVector<SourceLocation, 1> SelLocs;
1342e5dd7070Spatrick   SmallVector<Expr*, 1> Args;
1343e5dd7070Spatrick 
1344e5dd7070Spatrick   ObjCMessageExpr *NewMsg = nullptr;
1345e5dd7070Spatrick   switch (OldMsg->getReceiverKind()) {
1346e5dd7070Spatrick   case ObjCMessageExpr::Class:
1347e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1348e5dd7070Spatrick                                      OldMsg->getValueKind(),
1349e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1350e5dd7070Spatrick                                      OldMsg->getClassReceiverTypeInfo(),
1351e5dd7070Spatrick                                      OldMsg->getSelector(),
1352e5dd7070Spatrick                                      SelLocs,
1353e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1354e5dd7070Spatrick                                      Args,
1355e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1356e5dd7070Spatrick                                      OldMsg->isImplicit());
1357e5dd7070Spatrick     break;
1358e5dd7070Spatrick 
1359e5dd7070Spatrick   case ObjCMessageExpr::Instance:
1360e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1361e5dd7070Spatrick                                      OldMsg->getValueKind(),
1362e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1363e5dd7070Spatrick                                      Base,
1364e5dd7070Spatrick                                      OldMsg->getSelector(),
1365e5dd7070Spatrick                                      SelLocs,
1366e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1367e5dd7070Spatrick                                      Args,
1368e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1369e5dd7070Spatrick                                      OldMsg->isImplicit());
1370e5dd7070Spatrick     break;
1371e5dd7070Spatrick 
1372e5dd7070Spatrick   case ObjCMessageExpr::SuperClass:
1373e5dd7070Spatrick   case ObjCMessageExpr::SuperInstance:
1374e5dd7070Spatrick     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1375e5dd7070Spatrick                                      OldMsg->getValueKind(),
1376e5dd7070Spatrick                                      OldMsg->getLeftLoc(),
1377e5dd7070Spatrick                                      OldMsg->getSuperLoc(),
1378e5dd7070Spatrick                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1379e5dd7070Spatrick                                      OldMsg->getSuperType(),
1380e5dd7070Spatrick                                      OldMsg->getSelector(),
1381e5dd7070Spatrick                                      SelLocs,
1382e5dd7070Spatrick                                      OldMsg->getMethodDecl(),
1383e5dd7070Spatrick                                      Args,
1384e5dd7070Spatrick                                      OldMsg->getRightLoc(),
1385e5dd7070Spatrick                                      OldMsg->isImplicit());
1386e5dd7070Spatrick     break;
1387e5dd7070Spatrick   }
1388e5dd7070Spatrick 
1389e5dd7070Spatrick   Stmt *Replacement = SynthMessageExpr(NewMsg);
1390e5dd7070Spatrick   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1391e5dd7070Spatrick   return Replacement;
1392e5dd7070Spatrick }
1393e5dd7070Spatrick 
1394e5dd7070Spatrick /// SynthCountByEnumWithState - To print:
1395e5dd7070Spatrick /// ((unsigned int (*)
1396e5dd7070Spatrick ///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1397e5dd7070Spatrick ///  (void *)objc_msgSend)((id)l_collection,
1398e5dd7070Spatrick ///                        sel_registerName(
1399e5dd7070Spatrick ///                          "countByEnumeratingWithState:objects:count:"),
1400e5dd7070Spatrick ///                        &enumState,
1401e5dd7070Spatrick ///                        (id *)__rw_items, (unsigned int)16)
1402e5dd7070Spatrick ///
SynthCountByEnumWithState(std::string & buf)1403e5dd7070Spatrick void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1404e5dd7070Spatrick   buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1405e5dd7070Spatrick   "id *, unsigned int))(void *)objc_msgSend)";
1406e5dd7070Spatrick   buf += "\n\t\t";
1407e5dd7070Spatrick   buf += "((id)l_collection,\n\t\t";
1408e5dd7070Spatrick   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1409e5dd7070Spatrick   buf += "\n\t\t";
1410e5dd7070Spatrick   buf += "&enumState, "
1411e5dd7070Spatrick          "(id *)__rw_items, (unsigned int)16)";
1412e5dd7070Spatrick }
1413e5dd7070Spatrick 
1414e5dd7070Spatrick /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1415e5dd7070Spatrick /// statement to exit to its outer synthesized loop.
1416e5dd7070Spatrick ///
RewriteBreakStmt(BreakStmt * S)1417e5dd7070Spatrick Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1418e5dd7070Spatrick   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1419e5dd7070Spatrick     return S;
1420e5dd7070Spatrick   // replace break with goto __break_label
1421e5dd7070Spatrick   std::string buf;
1422e5dd7070Spatrick 
1423e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1424e5dd7070Spatrick   buf = "goto __break_label_";
1425e5dd7070Spatrick   buf += utostr(ObjCBcLabelNo.back());
1426e5dd7070Spatrick   ReplaceText(startLoc, strlen("break"), buf);
1427e5dd7070Spatrick 
1428e5dd7070Spatrick   return nullptr;
1429e5dd7070Spatrick }
1430e5dd7070Spatrick 
1431e5dd7070Spatrick /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1432e5dd7070Spatrick /// statement to continue with its inner synthesized loop.
1433e5dd7070Spatrick ///
RewriteContinueStmt(ContinueStmt * S)1434e5dd7070Spatrick Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1435e5dd7070Spatrick   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1436e5dd7070Spatrick     return S;
1437e5dd7070Spatrick   // replace continue with goto __continue_label
1438e5dd7070Spatrick   std::string buf;
1439e5dd7070Spatrick 
1440e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1441e5dd7070Spatrick   buf = "goto __continue_label_";
1442e5dd7070Spatrick   buf += utostr(ObjCBcLabelNo.back());
1443e5dd7070Spatrick   ReplaceText(startLoc, strlen("continue"), buf);
1444e5dd7070Spatrick 
1445e5dd7070Spatrick   return nullptr;
1446e5dd7070Spatrick }
1447e5dd7070Spatrick 
1448e5dd7070Spatrick /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1449e5dd7070Spatrick ///  It rewrites:
1450e5dd7070Spatrick /// for ( type elem in collection) { stmts; }
1451e5dd7070Spatrick 
1452e5dd7070Spatrick /// Into:
1453e5dd7070Spatrick /// {
1454e5dd7070Spatrick ///   type elem;
1455e5dd7070Spatrick ///   struct __objcFastEnumerationState enumState = { 0 };
1456e5dd7070Spatrick ///   id __rw_items[16];
1457e5dd7070Spatrick ///   id l_collection = (id)collection;
1458e5dd7070Spatrick ///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1459e5dd7070Spatrick ///                                       objects:__rw_items count:16];
1460e5dd7070Spatrick /// if (limit) {
1461e5dd7070Spatrick ///   unsigned long startMutations = *enumState.mutationsPtr;
1462e5dd7070Spatrick ///   do {
1463e5dd7070Spatrick ///        unsigned long counter = 0;
1464e5dd7070Spatrick ///        do {
1465e5dd7070Spatrick ///             if (startMutations != *enumState.mutationsPtr)
1466e5dd7070Spatrick ///               objc_enumerationMutation(l_collection);
1467e5dd7070Spatrick ///             elem = (type)enumState.itemsPtr[counter++];
1468e5dd7070Spatrick ///             stmts;
1469e5dd7070Spatrick ///             __continue_label: ;
1470e5dd7070Spatrick ///        } while (counter < limit);
1471e5dd7070Spatrick ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1472e5dd7070Spatrick ///                                  objects:__rw_items count:16]);
1473e5dd7070Spatrick ///   elem = nil;
1474e5dd7070Spatrick ///   __break_label: ;
1475e5dd7070Spatrick ///  }
1476e5dd7070Spatrick ///  else
1477e5dd7070Spatrick ///       elem = nil;
1478e5dd7070Spatrick ///  }
1479e5dd7070Spatrick ///
RewriteObjCForCollectionStmt(ObjCForCollectionStmt * S,SourceLocation OrigEnd)1480e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1481e5dd7070Spatrick                                                 SourceLocation OrigEnd) {
1482e5dd7070Spatrick   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1483e5dd7070Spatrick   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1484e5dd7070Spatrick          "ObjCForCollectionStmt Statement stack mismatch");
1485e5dd7070Spatrick   assert(!ObjCBcLabelNo.empty() &&
1486e5dd7070Spatrick          "ObjCForCollectionStmt - Label No stack empty");
1487e5dd7070Spatrick 
1488e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1489e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
1490e5dd7070Spatrick   StringRef elementName;
1491e5dd7070Spatrick   std::string elementTypeAsString;
1492e5dd7070Spatrick   std::string buf;
1493e5dd7070Spatrick   buf = "\n{\n\t";
1494e5dd7070Spatrick   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1495e5dd7070Spatrick     // type elem;
1496e5dd7070Spatrick     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1497e5dd7070Spatrick     QualType ElementType = cast<ValueDecl>(D)->getType();
1498e5dd7070Spatrick     if (ElementType->isObjCQualifiedIdType() ||
1499e5dd7070Spatrick         ElementType->isObjCQualifiedInterfaceType())
1500e5dd7070Spatrick       // Simply use 'id' for all qualified types.
1501e5dd7070Spatrick       elementTypeAsString = "id";
1502e5dd7070Spatrick     else
1503e5dd7070Spatrick       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1504e5dd7070Spatrick     buf += elementTypeAsString;
1505e5dd7070Spatrick     buf += " ";
1506e5dd7070Spatrick     elementName = D->getName();
1507e5dd7070Spatrick     buf += elementName;
1508e5dd7070Spatrick     buf += ";\n\t";
1509e5dd7070Spatrick   }
1510e5dd7070Spatrick   else {
1511e5dd7070Spatrick     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1512e5dd7070Spatrick     elementName = DR->getDecl()->getName();
1513e5dd7070Spatrick     ValueDecl *VD = DR->getDecl();
1514e5dd7070Spatrick     if (VD->getType()->isObjCQualifiedIdType() ||
1515e5dd7070Spatrick         VD->getType()->isObjCQualifiedInterfaceType())
1516e5dd7070Spatrick       // Simply use 'id' for all qualified types.
1517e5dd7070Spatrick       elementTypeAsString = "id";
1518e5dd7070Spatrick     else
1519e5dd7070Spatrick       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1520e5dd7070Spatrick   }
1521e5dd7070Spatrick 
1522e5dd7070Spatrick   // struct __objcFastEnumerationState enumState = { 0 };
1523e5dd7070Spatrick   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1524e5dd7070Spatrick   // id __rw_items[16];
1525e5dd7070Spatrick   buf += "id __rw_items[16];\n\t";
1526e5dd7070Spatrick   // id l_collection = (id)
1527e5dd7070Spatrick   buf += "id l_collection = (id)";
1528e5dd7070Spatrick   // Find start location of 'collection' the hard way!
1529e5dd7070Spatrick   const char *startCollectionBuf = startBuf;
1530e5dd7070Spatrick   startCollectionBuf += 3;  // skip 'for'
1531e5dd7070Spatrick   startCollectionBuf = strchr(startCollectionBuf, '(');
1532e5dd7070Spatrick   startCollectionBuf++; // skip '('
1533e5dd7070Spatrick   // find 'in' and skip it.
1534e5dd7070Spatrick   while (*startCollectionBuf != ' ' ||
1535e5dd7070Spatrick          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1536e5dd7070Spatrick          (*(startCollectionBuf+3) != ' ' &&
1537e5dd7070Spatrick           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1538e5dd7070Spatrick     startCollectionBuf++;
1539e5dd7070Spatrick   startCollectionBuf += 3;
1540e5dd7070Spatrick 
1541e5dd7070Spatrick   // Replace: "for (type element in" with string constructed thus far.
1542e5dd7070Spatrick   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1543e5dd7070Spatrick   // Replace ')' in for '(' type elem in collection ')' with ';'
1544e5dd7070Spatrick   SourceLocation rightParenLoc = S->getRParenLoc();
1545e5dd7070Spatrick   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1546e5dd7070Spatrick   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1547e5dd7070Spatrick   buf = ";\n\t";
1548e5dd7070Spatrick 
1549e5dd7070Spatrick   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1550e5dd7070Spatrick   //                                   objects:__rw_items count:16];
1551e5dd7070Spatrick   // which is synthesized into:
1552e5dd7070Spatrick   // unsigned int limit =
1553e5dd7070Spatrick   // ((unsigned int (*)
1554e5dd7070Spatrick   //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1555e5dd7070Spatrick   //  (void *)objc_msgSend)((id)l_collection,
1556e5dd7070Spatrick   //                        sel_registerName(
1557e5dd7070Spatrick   //                          "countByEnumeratingWithState:objects:count:"),
1558e5dd7070Spatrick   //                        (struct __objcFastEnumerationState *)&state,
1559e5dd7070Spatrick   //                        (id *)__rw_items, (unsigned int)16);
1560e5dd7070Spatrick   buf += "unsigned long limit =\n\t\t";
1561e5dd7070Spatrick   SynthCountByEnumWithState(buf);
1562e5dd7070Spatrick   buf += ";\n\t";
1563e5dd7070Spatrick   /// if (limit) {
1564e5dd7070Spatrick   ///   unsigned long startMutations = *enumState.mutationsPtr;
1565e5dd7070Spatrick   ///   do {
1566e5dd7070Spatrick   ///        unsigned long counter = 0;
1567e5dd7070Spatrick   ///        do {
1568e5dd7070Spatrick   ///             if (startMutations != *enumState.mutationsPtr)
1569e5dd7070Spatrick   ///               objc_enumerationMutation(l_collection);
1570e5dd7070Spatrick   ///             elem = (type)enumState.itemsPtr[counter++];
1571e5dd7070Spatrick   buf += "if (limit) {\n\t";
1572e5dd7070Spatrick   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1573e5dd7070Spatrick   buf += "do {\n\t\t";
1574e5dd7070Spatrick   buf += "unsigned long counter = 0;\n\t\t";
1575e5dd7070Spatrick   buf += "do {\n\t\t\t";
1576e5dd7070Spatrick   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1577e5dd7070Spatrick   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1578e5dd7070Spatrick   buf += elementName;
1579e5dd7070Spatrick   buf += " = (";
1580e5dd7070Spatrick   buf += elementTypeAsString;
1581e5dd7070Spatrick   buf += ")enumState.itemsPtr[counter++];";
1582e5dd7070Spatrick   // Replace ')' in for '(' type elem in collection ')' with all of these.
1583e5dd7070Spatrick   ReplaceText(lparenLoc, 1, buf);
1584e5dd7070Spatrick 
1585e5dd7070Spatrick   ///            __continue_label: ;
1586e5dd7070Spatrick   ///        } while (counter < limit);
1587e5dd7070Spatrick   ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1588e5dd7070Spatrick   ///                                  objects:__rw_items count:16]);
1589e5dd7070Spatrick   ///   elem = nil;
1590e5dd7070Spatrick   ///   __break_label: ;
1591e5dd7070Spatrick   ///  }
1592e5dd7070Spatrick   ///  else
1593e5dd7070Spatrick   ///       elem = nil;
1594e5dd7070Spatrick   ///  }
1595e5dd7070Spatrick   ///
1596e5dd7070Spatrick   buf = ";\n\t";
1597e5dd7070Spatrick   buf += "__continue_label_";
1598e5dd7070Spatrick   buf += utostr(ObjCBcLabelNo.back());
1599e5dd7070Spatrick   buf += ": ;";
1600e5dd7070Spatrick   buf += "\n\t\t";
1601e5dd7070Spatrick   buf += "} while (counter < limit);\n\t";
1602e5dd7070Spatrick   buf += "} while (limit = ";
1603e5dd7070Spatrick   SynthCountByEnumWithState(buf);
1604e5dd7070Spatrick   buf += ");\n\t";
1605e5dd7070Spatrick   buf += elementName;
1606e5dd7070Spatrick   buf += " = ((";
1607e5dd7070Spatrick   buf += elementTypeAsString;
1608e5dd7070Spatrick   buf += ")0);\n\t";
1609e5dd7070Spatrick   buf += "__break_label_";
1610e5dd7070Spatrick   buf += utostr(ObjCBcLabelNo.back());
1611e5dd7070Spatrick   buf += ": ;\n\t";
1612e5dd7070Spatrick   buf += "}\n\t";
1613e5dd7070Spatrick   buf += "else\n\t\t";
1614e5dd7070Spatrick   buf += elementName;
1615e5dd7070Spatrick   buf += " = ((";
1616e5dd7070Spatrick   buf += elementTypeAsString;
1617e5dd7070Spatrick   buf += ")0);\n\t";
1618e5dd7070Spatrick   buf += "}\n";
1619e5dd7070Spatrick 
1620e5dd7070Spatrick   // Insert all these *after* the statement body.
1621e5dd7070Spatrick   // FIXME: If this should support Obj-C++, support CXXTryStmt
1622e5dd7070Spatrick   if (isa<CompoundStmt>(S->getBody())) {
1623e5dd7070Spatrick     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1624e5dd7070Spatrick     InsertText(endBodyLoc, buf);
1625e5dd7070Spatrick   } else {
1626e5dd7070Spatrick     /* Need to treat single statements specially. For example:
1627e5dd7070Spatrick      *
1628e5dd7070Spatrick      *     for (A *a in b) if (stuff()) break;
1629e5dd7070Spatrick      *     for (A *a in b) xxxyy;
1630e5dd7070Spatrick      *
1631e5dd7070Spatrick      * The following code simply scans ahead to the semi to find the actual end.
1632e5dd7070Spatrick      */
1633e5dd7070Spatrick     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1634e5dd7070Spatrick     const char *semiBuf = strchr(stmtBuf, ';');
1635e5dd7070Spatrick     assert(semiBuf && "Can't find ';'");
1636e5dd7070Spatrick     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1637e5dd7070Spatrick     InsertText(endBodyLoc, buf);
1638e5dd7070Spatrick   }
1639e5dd7070Spatrick   Stmts.pop_back();
1640e5dd7070Spatrick   ObjCBcLabelNo.pop_back();
1641e5dd7070Spatrick   return nullptr;
1642e5dd7070Spatrick }
1643e5dd7070Spatrick 
1644e5dd7070Spatrick /// RewriteObjCSynchronizedStmt -
1645e5dd7070Spatrick /// This routine rewrites @synchronized(expr) stmt;
1646e5dd7070Spatrick /// into:
1647e5dd7070Spatrick /// objc_sync_enter(expr);
1648e5dd7070Spatrick /// @try stmt @finally { objc_sync_exit(expr); }
1649e5dd7070Spatrick ///
RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt * S)1650e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1651e5dd7070Spatrick   // Get the start location and compute the semi location.
1652e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1653e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
1654e5dd7070Spatrick 
1655e5dd7070Spatrick   assert((*startBuf == '@') && "bogus @synchronized location");
1656e5dd7070Spatrick 
1657e5dd7070Spatrick   std::string buf;
1658e5dd7070Spatrick   buf = "objc_sync_enter((id)";
1659e5dd7070Spatrick   const char *lparenBuf = startBuf;
1660e5dd7070Spatrick   while (*lparenBuf != '(') lparenBuf++;
1661e5dd7070Spatrick   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1662e5dd7070Spatrick   // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1663e5dd7070Spatrick   // the sync expression is typically a message expression that's already
1664e5dd7070Spatrick   // been rewritten! (which implies the SourceLocation's are invalid).
1665e5dd7070Spatrick   SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
1666e5dd7070Spatrick   const char *endBuf = SM->getCharacterData(endLoc);
1667e5dd7070Spatrick   while (*endBuf != ')') endBuf--;
1668e5dd7070Spatrick   SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1669e5dd7070Spatrick   buf = ");\n";
1670e5dd7070Spatrick   // declare a new scope with two variables, _stack and _rethrow.
1671e5dd7070Spatrick   buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1672e5dd7070Spatrick   buf += "int buf[18/*32-bit i386*/];\n";
1673e5dd7070Spatrick   buf += "char *pointers[4];} _stack;\n";
1674e5dd7070Spatrick   buf += "id volatile _rethrow = 0;\n";
1675e5dd7070Spatrick   buf += "objc_exception_try_enter(&_stack);\n";
1676e5dd7070Spatrick   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1677e5dd7070Spatrick   ReplaceText(rparenLoc, 1, buf);
1678e5dd7070Spatrick   startLoc = S->getSynchBody()->getEndLoc();
1679e5dd7070Spatrick   startBuf = SM->getCharacterData(startLoc);
1680e5dd7070Spatrick 
1681e5dd7070Spatrick   assert((*startBuf == '}') && "bogus @synchronized block");
1682e5dd7070Spatrick   SourceLocation lastCurlyLoc = startLoc;
1683e5dd7070Spatrick   buf = "}\nelse {\n";
1684e5dd7070Spatrick   buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1685e5dd7070Spatrick   buf += "}\n";
1686e5dd7070Spatrick   buf += "{ /* implicit finally clause */\n";
1687e5dd7070Spatrick   buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1688e5dd7070Spatrick 
1689e5dd7070Spatrick   std::string syncBuf;
1690e5dd7070Spatrick   syncBuf += " objc_sync_exit(";
1691e5dd7070Spatrick 
1692e5dd7070Spatrick   Expr *syncExpr = S->getSynchExpr();
1693e5dd7070Spatrick   CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1694e5dd7070Spatrick                   ? CK_BitCast :
1695e5dd7070Spatrick                 syncExpr->getType()->isBlockPointerType()
1696e5dd7070Spatrick                   ? CK_BlockPointerToObjCPointerCast
1697e5dd7070Spatrick                   : CK_CPointerToObjCPointerCast;
1698e5dd7070Spatrick   syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1699e5dd7070Spatrick                                       CK, syncExpr);
1700e5dd7070Spatrick   std::string syncExprBufS;
1701e5dd7070Spatrick   llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1702e5dd7070Spatrick   assert(syncExpr != nullptr && "Expected non-null Expr");
1703e5dd7070Spatrick   syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1704e5dd7070Spatrick   syncBuf += syncExprBuf.str();
1705e5dd7070Spatrick   syncBuf += ");";
1706e5dd7070Spatrick 
1707e5dd7070Spatrick   buf += syncBuf;
1708e5dd7070Spatrick   buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1709e5dd7070Spatrick   buf += "}\n";
1710e5dd7070Spatrick   buf += "}";
1711e5dd7070Spatrick 
1712e5dd7070Spatrick   ReplaceText(lastCurlyLoc, 1, buf);
1713e5dd7070Spatrick 
1714e5dd7070Spatrick   bool hasReturns = false;
1715e5dd7070Spatrick   HasReturnStmts(S->getSynchBody(), hasReturns);
1716e5dd7070Spatrick   if (hasReturns)
1717e5dd7070Spatrick     RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1718e5dd7070Spatrick 
1719e5dd7070Spatrick   return nullptr;
1720e5dd7070Spatrick }
1721e5dd7070Spatrick 
WarnAboutReturnGotoStmts(Stmt * S)1722e5dd7070Spatrick void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1723e5dd7070Spatrick {
1724e5dd7070Spatrick   // Perform a bottom up traversal of all children.
1725e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
1726e5dd7070Spatrick     if (SubStmt)
1727e5dd7070Spatrick       WarnAboutReturnGotoStmts(SubStmt);
1728e5dd7070Spatrick 
1729e5dd7070Spatrick   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1730e5dd7070Spatrick     Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1731e5dd7070Spatrick                  TryFinallyContainsReturnDiag);
1732e5dd7070Spatrick   }
1733e5dd7070Spatrick }
1734e5dd7070Spatrick 
HasReturnStmts(Stmt * S,bool & hasReturns)1735e5dd7070Spatrick void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1736e5dd7070Spatrick {
1737e5dd7070Spatrick   // Perform a bottom up traversal of all children.
1738e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
1739e5dd7070Spatrick     if (SubStmt)
1740e5dd7070Spatrick       HasReturnStmts(SubStmt, hasReturns);
1741e5dd7070Spatrick 
1742e5dd7070Spatrick   if (isa<ReturnStmt>(S))
1743e5dd7070Spatrick     hasReturns = true;
1744e5dd7070Spatrick }
1745e5dd7070Spatrick 
RewriteTryReturnStmts(Stmt * S)1746e5dd7070Spatrick void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1747e5dd7070Spatrick   // Perform a bottom up traversal of all children.
1748e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
1749e5dd7070Spatrick     if (SubStmt) {
1750e5dd7070Spatrick       RewriteTryReturnStmts(SubStmt);
1751e5dd7070Spatrick     }
1752e5dd7070Spatrick   if (isa<ReturnStmt>(S)) {
1753e5dd7070Spatrick     SourceLocation startLoc = S->getBeginLoc();
1754e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(startLoc);
1755e5dd7070Spatrick     const char *semiBuf = strchr(startBuf, ';');
1756e5dd7070Spatrick     assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1757e5dd7070Spatrick     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1758e5dd7070Spatrick 
1759e5dd7070Spatrick     std::string buf;
1760e5dd7070Spatrick     buf = "{ objc_exception_try_exit(&_stack); return";
1761e5dd7070Spatrick 
1762e5dd7070Spatrick     ReplaceText(startLoc, 6, buf);
1763e5dd7070Spatrick     InsertText(onePastSemiLoc, "}");
1764e5dd7070Spatrick   }
1765e5dd7070Spatrick }
1766e5dd7070Spatrick 
RewriteSyncReturnStmts(Stmt * S,std::string syncExitBuf)1767e5dd7070Spatrick void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1768e5dd7070Spatrick   // Perform a bottom up traversal of all children.
1769e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
1770e5dd7070Spatrick     if (SubStmt) {
1771e5dd7070Spatrick       RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1772e5dd7070Spatrick     }
1773e5dd7070Spatrick   if (isa<ReturnStmt>(S)) {
1774e5dd7070Spatrick     SourceLocation startLoc = S->getBeginLoc();
1775e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(startLoc);
1776e5dd7070Spatrick 
1777e5dd7070Spatrick     const char *semiBuf = strchr(startBuf, ';');
1778e5dd7070Spatrick     assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1779e5dd7070Spatrick     SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1780e5dd7070Spatrick 
1781e5dd7070Spatrick     std::string buf;
1782e5dd7070Spatrick     buf = "{ objc_exception_try_exit(&_stack);";
1783e5dd7070Spatrick     buf += syncExitBuf;
1784e5dd7070Spatrick     buf += " return";
1785e5dd7070Spatrick 
1786e5dd7070Spatrick     ReplaceText(startLoc, 6, buf);
1787e5dd7070Spatrick     InsertText(onePastSemiLoc, "}");
1788e5dd7070Spatrick   }
1789e5dd7070Spatrick }
1790e5dd7070Spatrick 
RewriteObjCTryStmt(ObjCAtTryStmt * S)1791e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1792e5dd7070Spatrick   // Get the start location and compute the semi location.
1793e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1794e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
1795e5dd7070Spatrick 
1796e5dd7070Spatrick   assert((*startBuf == '@') && "bogus @try location");
1797e5dd7070Spatrick 
1798e5dd7070Spatrick   std::string buf;
1799e5dd7070Spatrick   // declare a new scope with two variables, _stack and _rethrow.
1800e5dd7070Spatrick   buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1801e5dd7070Spatrick   buf += "int buf[18/*32-bit i386*/];\n";
1802e5dd7070Spatrick   buf += "char *pointers[4];} _stack;\n";
1803e5dd7070Spatrick   buf += "id volatile _rethrow = 0;\n";
1804e5dd7070Spatrick   buf += "objc_exception_try_enter(&_stack);\n";
1805e5dd7070Spatrick   buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1806e5dd7070Spatrick 
1807e5dd7070Spatrick   ReplaceText(startLoc, 4, buf);
1808e5dd7070Spatrick 
1809e5dd7070Spatrick   startLoc = S->getTryBody()->getEndLoc();
1810e5dd7070Spatrick   startBuf = SM->getCharacterData(startLoc);
1811e5dd7070Spatrick 
1812e5dd7070Spatrick   assert((*startBuf == '}') && "bogus @try block");
1813e5dd7070Spatrick 
1814e5dd7070Spatrick   SourceLocation lastCurlyLoc = startLoc;
1815e5dd7070Spatrick   if (S->getNumCatchStmts()) {
1816e5dd7070Spatrick     startLoc = startLoc.getLocWithOffset(1);
1817e5dd7070Spatrick     buf = " /* @catch begin */ else {\n";
1818e5dd7070Spatrick     buf += " id _caught = objc_exception_extract(&_stack);\n";
1819e5dd7070Spatrick     buf += " objc_exception_try_enter (&_stack);\n";
1820e5dd7070Spatrick     buf += " if (_setjmp(_stack.buf))\n";
1821e5dd7070Spatrick     buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1822e5dd7070Spatrick     buf += " else { /* @catch continue */";
1823e5dd7070Spatrick 
1824e5dd7070Spatrick     InsertText(startLoc, buf);
1825e5dd7070Spatrick   } else { /* no catch list */
1826e5dd7070Spatrick     buf = "}\nelse {\n";
1827e5dd7070Spatrick     buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1828e5dd7070Spatrick     buf += "}";
1829e5dd7070Spatrick     ReplaceText(lastCurlyLoc, 1, buf);
1830e5dd7070Spatrick   }
1831e5dd7070Spatrick   Stmt *lastCatchBody = nullptr;
1832e5dd7070Spatrick   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1833e5dd7070Spatrick     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1834e5dd7070Spatrick     VarDecl *catchDecl = Catch->getCatchParamDecl();
1835e5dd7070Spatrick 
1836e5dd7070Spatrick     if (I == 0)
1837e5dd7070Spatrick       buf = "if ("; // we are generating code for the first catch clause
1838e5dd7070Spatrick     else
1839e5dd7070Spatrick       buf = "else if (";
1840e5dd7070Spatrick     startLoc = Catch->getBeginLoc();
1841e5dd7070Spatrick     startBuf = SM->getCharacterData(startLoc);
1842e5dd7070Spatrick 
1843e5dd7070Spatrick     assert((*startBuf == '@') && "bogus @catch location");
1844e5dd7070Spatrick 
1845e5dd7070Spatrick     const char *lParenLoc = strchr(startBuf, '(');
1846e5dd7070Spatrick 
1847e5dd7070Spatrick     if (Catch->hasEllipsis()) {
1848e5dd7070Spatrick       // Now rewrite the body...
1849e5dd7070Spatrick       lastCatchBody = Catch->getCatchBody();
1850e5dd7070Spatrick       SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1851e5dd7070Spatrick       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1852e5dd7070Spatrick       assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1853e5dd7070Spatrick              "bogus @catch paren location");
1854e5dd7070Spatrick       assert((*bodyBuf == '{') && "bogus @catch body location");
1855e5dd7070Spatrick 
1856e5dd7070Spatrick       buf += "1) { id _tmp = _caught;";
1857e5dd7070Spatrick       Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1858e5dd7070Spatrick     } else if (catchDecl) {
1859e5dd7070Spatrick       QualType t = catchDecl->getType();
1860e5dd7070Spatrick       if (t == Context->getObjCIdType()) {
1861e5dd7070Spatrick         buf += "1) { ";
1862e5dd7070Spatrick         ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1863e5dd7070Spatrick       } else if (const ObjCObjectPointerType *Ptr =
1864e5dd7070Spatrick                    t->getAs<ObjCObjectPointerType>()) {
1865e5dd7070Spatrick         // Should be a pointer to a class.
1866e5dd7070Spatrick         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1867e5dd7070Spatrick         if (IDecl) {
1868e5dd7070Spatrick           buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1869e5dd7070Spatrick           buf += IDecl->getNameAsString();
1870e5dd7070Spatrick           buf += "\"), (struct objc_object *)_caught)) { ";
1871e5dd7070Spatrick           ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1872e5dd7070Spatrick         }
1873e5dd7070Spatrick       }
1874e5dd7070Spatrick       // Now rewrite the body...
1875e5dd7070Spatrick       lastCatchBody = Catch->getCatchBody();
1876e5dd7070Spatrick       SourceLocation rParenLoc = Catch->getRParenLoc();
1877e5dd7070Spatrick       SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1878e5dd7070Spatrick       const char *bodyBuf = SM->getCharacterData(bodyLoc);
1879e5dd7070Spatrick       const char *rParenBuf = SM->getCharacterData(rParenLoc);
1880e5dd7070Spatrick       assert((*rParenBuf == ')') && "bogus @catch paren location");
1881e5dd7070Spatrick       assert((*bodyBuf == '{') && "bogus @catch body location");
1882e5dd7070Spatrick 
1883e5dd7070Spatrick       // Here we replace ") {" with "= _caught;" (which initializes and
1884e5dd7070Spatrick       // declares the @catch parameter).
1885e5dd7070Spatrick       ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1886e5dd7070Spatrick     } else {
1887e5dd7070Spatrick       llvm_unreachable("@catch rewrite bug");
1888e5dd7070Spatrick     }
1889e5dd7070Spatrick   }
1890e5dd7070Spatrick   // Complete the catch list...
1891e5dd7070Spatrick   if (lastCatchBody) {
1892e5dd7070Spatrick     SourceLocation bodyLoc = lastCatchBody->getEndLoc();
1893e5dd7070Spatrick     assert(*SM->getCharacterData(bodyLoc) == '}' &&
1894e5dd7070Spatrick            "bogus @catch body location");
1895e5dd7070Spatrick 
1896e5dd7070Spatrick     // Insert the last (implicit) else clause *before* the right curly brace.
1897e5dd7070Spatrick     bodyLoc = bodyLoc.getLocWithOffset(-1);
1898e5dd7070Spatrick     buf = "} /* last catch end */\n";
1899e5dd7070Spatrick     buf += "else {\n";
1900e5dd7070Spatrick     buf += " _rethrow = _caught;\n";
1901e5dd7070Spatrick     buf += " objc_exception_try_exit(&_stack);\n";
1902e5dd7070Spatrick     buf += "} } /* @catch end */\n";
1903e5dd7070Spatrick     if (!S->getFinallyStmt())
1904e5dd7070Spatrick       buf += "}\n";
1905e5dd7070Spatrick     InsertText(bodyLoc, buf);
1906e5dd7070Spatrick 
1907e5dd7070Spatrick     // Set lastCurlyLoc
1908e5dd7070Spatrick     lastCurlyLoc = lastCatchBody->getEndLoc();
1909e5dd7070Spatrick   }
1910e5dd7070Spatrick   if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1911e5dd7070Spatrick     startLoc = finalStmt->getBeginLoc();
1912e5dd7070Spatrick     startBuf = SM->getCharacterData(startLoc);
1913e5dd7070Spatrick     assert((*startBuf == '@') && "bogus @finally start");
1914e5dd7070Spatrick 
1915e5dd7070Spatrick     ReplaceText(startLoc, 8, "/* @finally */");
1916e5dd7070Spatrick 
1917e5dd7070Spatrick     Stmt *body = finalStmt->getFinallyBody();
1918e5dd7070Spatrick     SourceLocation startLoc = body->getBeginLoc();
1919e5dd7070Spatrick     SourceLocation endLoc = body->getEndLoc();
1920e5dd7070Spatrick     assert(*SM->getCharacterData(startLoc) == '{' &&
1921e5dd7070Spatrick            "bogus @finally body location");
1922e5dd7070Spatrick     assert(*SM->getCharacterData(endLoc) == '}' &&
1923e5dd7070Spatrick            "bogus @finally body location");
1924e5dd7070Spatrick 
1925e5dd7070Spatrick     startLoc = startLoc.getLocWithOffset(1);
1926e5dd7070Spatrick     InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1927e5dd7070Spatrick     endLoc = endLoc.getLocWithOffset(-1);
1928e5dd7070Spatrick     InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1929e5dd7070Spatrick 
1930e5dd7070Spatrick     // Set lastCurlyLoc
1931e5dd7070Spatrick     lastCurlyLoc = body->getEndLoc();
1932e5dd7070Spatrick 
1933e5dd7070Spatrick     // Now check for any return/continue/go statements within the @try.
1934e5dd7070Spatrick     WarnAboutReturnGotoStmts(S->getTryBody());
1935e5dd7070Spatrick   } else { /* no finally clause - make sure we synthesize an implicit one */
1936e5dd7070Spatrick     buf = "{ /* implicit finally clause */\n";
1937e5dd7070Spatrick     buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1938e5dd7070Spatrick     buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1939e5dd7070Spatrick     buf += "}";
1940e5dd7070Spatrick     ReplaceText(lastCurlyLoc, 1, buf);
1941e5dd7070Spatrick 
1942e5dd7070Spatrick     // Now check for any return/continue/go statements within the @try.
1943e5dd7070Spatrick     // The implicit finally clause won't called if the @try contains any
1944e5dd7070Spatrick     // jump statements.
1945e5dd7070Spatrick     bool hasReturns = false;
1946e5dd7070Spatrick     HasReturnStmts(S->getTryBody(), hasReturns);
1947e5dd7070Spatrick     if (hasReturns)
1948e5dd7070Spatrick       RewriteTryReturnStmts(S->getTryBody());
1949e5dd7070Spatrick   }
1950e5dd7070Spatrick   // Now emit the final closing curly brace...
1951e5dd7070Spatrick   lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1952e5dd7070Spatrick   InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1953e5dd7070Spatrick   return nullptr;
1954e5dd7070Spatrick }
1955e5dd7070Spatrick 
1956e5dd7070Spatrick // This can't be done with ReplaceStmt(S, ThrowExpr), since
1957e5dd7070Spatrick // the throw expression is typically a message expression that's already
1958e5dd7070Spatrick // been rewritten! (which implies the SourceLocation's are invalid).
RewriteObjCThrowStmt(ObjCAtThrowStmt * S)1959e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1960e5dd7070Spatrick   // Get the start location and compute the semi location.
1961e5dd7070Spatrick   SourceLocation startLoc = S->getBeginLoc();
1962e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(startLoc);
1963e5dd7070Spatrick 
1964e5dd7070Spatrick   assert((*startBuf == '@') && "bogus @throw location");
1965e5dd7070Spatrick 
1966e5dd7070Spatrick   std::string buf;
1967e5dd7070Spatrick   /* void objc_exception_throw(id) __attribute__((noreturn)); */
1968e5dd7070Spatrick   if (S->getThrowExpr())
1969e5dd7070Spatrick     buf = "objc_exception_throw(";
1970e5dd7070Spatrick   else // add an implicit argument
1971e5dd7070Spatrick     buf = "objc_exception_throw(_caught";
1972e5dd7070Spatrick 
1973e5dd7070Spatrick   // handle "@  throw" correctly.
1974e5dd7070Spatrick   const char *wBuf = strchr(startBuf, 'w');
1975e5dd7070Spatrick   assert((*wBuf == 'w') && "@throw: can't find 'w'");
1976e5dd7070Spatrick   ReplaceText(startLoc, wBuf-startBuf+1, buf);
1977e5dd7070Spatrick 
1978e5dd7070Spatrick   const char *semiBuf = strchr(startBuf, ';');
1979e5dd7070Spatrick   assert((*semiBuf == ';') && "@throw: can't find ';'");
1980e5dd7070Spatrick   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1981e5dd7070Spatrick   ReplaceText(semiLoc, 1, ");");
1982e5dd7070Spatrick   return nullptr;
1983e5dd7070Spatrick }
1984e5dd7070Spatrick 
RewriteAtEncode(ObjCEncodeExpr * Exp)1985e5dd7070Spatrick Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1986e5dd7070Spatrick   // Create a new string expression.
1987e5dd7070Spatrick   std::string StrEncoding;
1988e5dd7070Spatrick   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1989e5dd7070Spatrick   Expr *Replacement = getStringLiteral(StrEncoding);
1990e5dd7070Spatrick   ReplaceStmt(Exp, Replacement);
1991e5dd7070Spatrick 
1992e5dd7070Spatrick   // Replace this subexpr in the parent.
1993e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1994e5dd7070Spatrick   return Replacement;
1995e5dd7070Spatrick }
1996e5dd7070Spatrick 
RewriteAtSelector(ObjCSelectorExpr * Exp)1997e5dd7070Spatrick Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1998e5dd7070Spatrick   if (!SelGetUidFunctionDecl)
1999e5dd7070Spatrick     SynthSelGetUidFunctionDecl();
2000e5dd7070Spatrick   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2001e5dd7070Spatrick   // Create a call to sel_registerName("selName").
2002e5dd7070Spatrick   SmallVector<Expr*, 8> SelExprs;
2003e5dd7070Spatrick   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2004e5dd7070Spatrick   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2005e5dd7070Spatrick                                                   SelExprs);
2006e5dd7070Spatrick   ReplaceStmt(Exp, SelExp);
2007e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2008e5dd7070Spatrick   return SelExp;
2009e5dd7070Spatrick }
2010e5dd7070Spatrick 
2011e5dd7070Spatrick CallExpr *
SynthesizeCallToFunctionDecl(FunctionDecl * FD,ArrayRef<Expr * > Args,SourceLocation StartLoc,SourceLocation EndLoc)2012e5dd7070Spatrick RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2013e5dd7070Spatrick                                           ArrayRef<Expr *> Args,
2014e5dd7070Spatrick                                           SourceLocation StartLoc,
2015e5dd7070Spatrick                                           SourceLocation EndLoc) {
2016e5dd7070Spatrick   // Get the type, we will need to reference it in a couple spots.
2017e5dd7070Spatrick   QualType msgSendType = FD->getType();
2018e5dd7070Spatrick 
2019e5dd7070Spatrick   // Create a reference to the objc_msgSend() declaration.
2020e5dd7070Spatrick   DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2021e5dd7070Spatrick                                                VK_LValue, SourceLocation());
2022e5dd7070Spatrick 
2023e5dd7070Spatrick   // Now, we cast the reference to a pointer to the objc_msgSend type.
2024e5dd7070Spatrick   QualType pToFunc = Context->getPointerType(msgSendType);
2025e5dd7070Spatrick   ImplicitCastExpr *ICE =
2026e5dd7070Spatrick       ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2027a9ac8606Spatrick                                DRE, nullptr, VK_PRValue, FPOptionsOverride());
2028e5dd7070Spatrick 
2029e5dd7070Spatrick   const auto *FT = msgSendType->castAs<FunctionType>();
2030e5dd7070Spatrick 
2031a9ac8606Spatrick   CallExpr *Exp =
2032a9ac8606Spatrick       CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
2033a9ac8606Spatrick                        VK_PRValue, EndLoc, FPOptionsOverride());
2034e5dd7070Spatrick   return Exp;
2035e5dd7070Spatrick }
2036e5dd7070Spatrick 
scanForProtocolRefs(const char * startBuf,const char * endBuf,const char * & startRef,const char * & endRef)2037e5dd7070Spatrick static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2038e5dd7070Spatrick                                 const char *&startRef, const char *&endRef) {
2039e5dd7070Spatrick   while (startBuf < endBuf) {
2040e5dd7070Spatrick     if (*startBuf == '<')
2041e5dd7070Spatrick       startRef = startBuf; // mark the start.
2042e5dd7070Spatrick     if (*startBuf == '>') {
2043e5dd7070Spatrick       if (startRef && *startRef == '<') {
2044e5dd7070Spatrick         endRef = startBuf; // mark the end.
2045e5dd7070Spatrick         return true;
2046e5dd7070Spatrick       }
2047e5dd7070Spatrick       return false;
2048e5dd7070Spatrick     }
2049e5dd7070Spatrick     startBuf++;
2050e5dd7070Spatrick   }
2051e5dd7070Spatrick   return false;
2052e5dd7070Spatrick }
2053e5dd7070Spatrick 
scanToNextArgument(const char * & argRef)2054e5dd7070Spatrick static void scanToNextArgument(const char *&argRef) {
2055e5dd7070Spatrick   int angle = 0;
2056e5dd7070Spatrick   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2057e5dd7070Spatrick     if (*argRef == '<')
2058e5dd7070Spatrick       angle++;
2059e5dd7070Spatrick     else if (*argRef == '>')
2060e5dd7070Spatrick       angle--;
2061e5dd7070Spatrick     argRef++;
2062e5dd7070Spatrick   }
2063e5dd7070Spatrick   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2064e5dd7070Spatrick }
2065e5dd7070Spatrick 
needToScanForQualifiers(QualType T)2066e5dd7070Spatrick bool RewriteObjC::needToScanForQualifiers(QualType T) {
2067e5dd7070Spatrick   if (T->isObjCQualifiedIdType())
2068e5dd7070Spatrick     return true;
2069e5dd7070Spatrick   if (const PointerType *PT = T->getAs<PointerType>()) {
2070e5dd7070Spatrick     if (PT->getPointeeType()->isObjCQualifiedIdType())
2071e5dd7070Spatrick       return true;
2072e5dd7070Spatrick   }
2073e5dd7070Spatrick   if (T->isObjCObjectPointerType()) {
2074e5dd7070Spatrick     T = T->getPointeeType();
2075e5dd7070Spatrick     return T->isObjCQualifiedInterfaceType();
2076e5dd7070Spatrick   }
2077e5dd7070Spatrick   if (T->isArrayType()) {
2078e5dd7070Spatrick     QualType ElemTy = Context->getBaseElementType(T);
2079e5dd7070Spatrick     return needToScanForQualifiers(ElemTy);
2080e5dd7070Spatrick   }
2081e5dd7070Spatrick   return false;
2082e5dd7070Spatrick }
2083e5dd7070Spatrick 
RewriteObjCQualifiedInterfaceTypes(Expr * E)2084e5dd7070Spatrick void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2085e5dd7070Spatrick   QualType Type = E->getType();
2086e5dd7070Spatrick   if (needToScanForQualifiers(Type)) {
2087e5dd7070Spatrick     SourceLocation Loc, EndLoc;
2088e5dd7070Spatrick 
2089e5dd7070Spatrick     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2090e5dd7070Spatrick       Loc = ECE->getLParenLoc();
2091e5dd7070Spatrick       EndLoc = ECE->getRParenLoc();
2092e5dd7070Spatrick     } else {
2093e5dd7070Spatrick       Loc = E->getBeginLoc();
2094e5dd7070Spatrick       EndLoc = E->getEndLoc();
2095e5dd7070Spatrick     }
2096e5dd7070Spatrick     // This will defend against trying to rewrite synthesized expressions.
2097e5dd7070Spatrick     if (Loc.isInvalid() || EndLoc.isInvalid())
2098e5dd7070Spatrick       return;
2099e5dd7070Spatrick 
2100e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(Loc);
2101e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(EndLoc);
2102e5dd7070Spatrick     const char *startRef = nullptr, *endRef = nullptr;
2103e5dd7070Spatrick     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2104e5dd7070Spatrick       // Get the locations of the startRef, endRef.
2105e5dd7070Spatrick       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2106e5dd7070Spatrick       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2107e5dd7070Spatrick       // Comment out the protocol references.
2108e5dd7070Spatrick       InsertText(LessLoc, "/*");
2109e5dd7070Spatrick       InsertText(GreaterLoc, "*/");
2110e5dd7070Spatrick     }
2111e5dd7070Spatrick   }
2112e5dd7070Spatrick }
2113e5dd7070Spatrick 
RewriteObjCQualifiedInterfaceTypes(Decl * Dcl)2114e5dd7070Spatrick void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2115e5dd7070Spatrick   SourceLocation Loc;
2116e5dd7070Spatrick   QualType Type;
2117e5dd7070Spatrick   const FunctionProtoType *proto = nullptr;
2118e5dd7070Spatrick   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2119e5dd7070Spatrick     Loc = VD->getLocation();
2120e5dd7070Spatrick     Type = VD->getType();
2121e5dd7070Spatrick   }
2122e5dd7070Spatrick   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2123e5dd7070Spatrick     Loc = FD->getLocation();
2124e5dd7070Spatrick     // Check for ObjC 'id' and class types that have been adorned with protocol
2125e5dd7070Spatrick     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2126e5dd7070Spatrick     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2127e5dd7070Spatrick     assert(funcType && "missing function type");
2128e5dd7070Spatrick     proto = dyn_cast<FunctionProtoType>(funcType);
2129e5dd7070Spatrick     if (!proto)
2130e5dd7070Spatrick       return;
2131e5dd7070Spatrick     Type = proto->getReturnType();
2132e5dd7070Spatrick   }
2133e5dd7070Spatrick   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2134e5dd7070Spatrick     Loc = FD->getLocation();
2135e5dd7070Spatrick     Type = FD->getType();
2136e5dd7070Spatrick   }
2137e5dd7070Spatrick   else
2138e5dd7070Spatrick     return;
2139e5dd7070Spatrick 
2140e5dd7070Spatrick   if (needToScanForQualifiers(Type)) {
2141e5dd7070Spatrick     // Since types are unique, we need to scan the buffer.
2142e5dd7070Spatrick 
2143e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(Loc);
2144e5dd7070Spatrick     const char *startBuf = endBuf;
2145e5dd7070Spatrick     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2146e5dd7070Spatrick       startBuf--; // scan backward (from the decl location) for return type.
2147e5dd7070Spatrick     const char *startRef = nullptr, *endRef = nullptr;
2148e5dd7070Spatrick     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2149e5dd7070Spatrick       // Get the locations of the startRef, endRef.
2150e5dd7070Spatrick       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2151e5dd7070Spatrick       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2152e5dd7070Spatrick       // Comment out the protocol references.
2153e5dd7070Spatrick       InsertText(LessLoc, "/*");
2154e5dd7070Spatrick       InsertText(GreaterLoc, "*/");
2155e5dd7070Spatrick     }
2156e5dd7070Spatrick   }
2157e5dd7070Spatrick   if (!proto)
2158e5dd7070Spatrick       return; // most likely, was a variable
2159e5dd7070Spatrick   // Now check arguments.
2160e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(Loc);
2161e5dd7070Spatrick   const char *startFuncBuf = startBuf;
2162e5dd7070Spatrick   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2163e5dd7070Spatrick     if (needToScanForQualifiers(proto->getParamType(i))) {
2164e5dd7070Spatrick       // Since types are unique, we need to scan the buffer.
2165e5dd7070Spatrick 
2166e5dd7070Spatrick       const char *endBuf = startBuf;
2167e5dd7070Spatrick       // scan forward (from the decl location) for argument types.
2168e5dd7070Spatrick       scanToNextArgument(endBuf);
2169e5dd7070Spatrick       const char *startRef = nullptr, *endRef = nullptr;
2170e5dd7070Spatrick       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2171e5dd7070Spatrick         // Get the locations of the startRef, endRef.
2172e5dd7070Spatrick         SourceLocation LessLoc =
2173e5dd7070Spatrick           Loc.getLocWithOffset(startRef-startFuncBuf);
2174e5dd7070Spatrick         SourceLocation GreaterLoc =
2175e5dd7070Spatrick           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2176e5dd7070Spatrick         // Comment out the protocol references.
2177e5dd7070Spatrick         InsertText(LessLoc, "/*");
2178e5dd7070Spatrick         InsertText(GreaterLoc, "*/");
2179e5dd7070Spatrick       }
2180e5dd7070Spatrick       startBuf = ++endBuf;
2181e5dd7070Spatrick     }
2182e5dd7070Spatrick     else {
2183e5dd7070Spatrick       // If the function name is derived from a macro expansion, then the
2184e5dd7070Spatrick       // argument buffer will not follow the name. Need to speak with Chris.
2185e5dd7070Spatrick       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2186e5dd7070Spatrick         startBuf++; // scan forward (from the decl location) for argument types.
2187e5dd7070Spatrick       startBuf++;
2188e5dd7070Spatrick     }
2189e5dd7070Spatrick   }
2190e5dd7070Spatrick }
2191e5dd7070Spatrick 
RewriteTypeOfDecl(VarDecl * ND)2192e5dd7070Spatrick void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2193e5dd7070Spatrick   QualType QT = ND->getType();
2194e5dd7070Spatrick   const Type* TypePtr = QT->getAs<Type>();
2195e5dd7070Spatrick   if (!isa<TypeOfExprType>(TypePtr))
2196e5dd7070Spatrick     return;
2197e5dd7070Spatrick   while (isa<TypeOfExprType>(TypePtr)) {
2198e5dd7070Spatrick     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2199e5dd7070Spatrick     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2200e5dd7070Spatrick     TypePtr = QT->getAs<Type>();
2201e5dd7070Spatrick   }
2202e5dd7070Spatrick   // FIXME. This will not work for multiple declarators; as in:
2203e5dd7070Spatrick   // __typeof__(a) b,c,d;
2204e5dd7070Spatrick   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2205e5dd7070Spatrick   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2206e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(DeclLoc);
2207e5dd7070Spatrick   if (ND->getInit()) {
2208e5dd7070Spatrick     std::string Name(ND->getNameAsString());
2209e5dd7070Spatrick     TypeAsString += " " + Name + " = ";
2210e5dd7070Spatrick     Expr *E = ND->getInit();
2211e5dd7070Spatrick     SourceLocation startLoc;
2212e5dd7070Spatrick     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2213e5dd7070Spatrick       startLoc = ECE->getLParenLoc();
2214e5dd7070Spatrick     else
2215e5dd7070Spatrick       startLoc = E->getBeginLoc();
2216e5dd7070Spatrick     startLoc = SM->getExpansionLoc(startLoc);
2217e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(startLoc);
2218e5dd7070Spatrick     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2219e5dd7070Spatrick   }
2220e5dd7070Spatrick   else {
2221e5dd7070Spatrick     SourceLocation X = ND->getEndLoc();
2222e5dd7070Spatrick     X = SM->getExpansionLoc(X);
2223e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(X);
2224e5dd7070Spatrick     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2225e5dd7070Spatrick   }
2226e5dd7070Spatrick }
2227e5dd7070Spatrick 
2228e5dd7070Spatrick // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
SynthSelGetUidFunctionDecl()2229e5dd7070Spatrick void RewriteObjC::SynthSelGetUidFunctionDecl() {
2230e5dd7070Spatrick   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2231e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2232e5dd7070Spatrick   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2233e5dd7070Spatrick   QualType getFuncType =
2234e5dd7070Spatrick     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2235e5dd7070Spatrick   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2236e5dd7070Spatrick                                                SourceLocation(),
2237e5dd7070Spatrick                                                SourceLocation(),
2238e5dd7070Spatrick                                                SelGetUidIdent, getFuncType,
2239e5dd7070Spatrick                                                nullptr, SC_Extern);
2240e5dd7070Spatrick }
2241e5dd7070Spatrick 
RewriteFunctionDecl(FunctionDecl * FD)2242e5dd7070Spatrick void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2243e5dd7070Spatrick   // declared in <objc/objc.h>
2244e5dd7070Spatrick   if (FD->getIdentifier() &&
2245e5dd7070Spatrick       FD->getName() == "sel_registerName") {
2246e5dd7070Spatrick     SelGetUidFunctionDecl = FD;
2247e5dd7070Spatrick     return;
2248e5dd7070Spatrick   }
2249e5dd7070Spatrick   RewriteObjCQualifiedInterfaceTypes(FD);
2250e5dd7070Spatrick }
2251e5dd7070Spatrick 
RewriteBlockPointerType(std::string & Str,QualType Type)2252e5dd7070Spatrick void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2253e5dd7070Spatrick   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2254e5dd7070Spatrick   const char *argPtr = TypeString.c_str();
2255e5dd7070Spatrick   if (!strchr(argPtr, '^')) {
2256e5dd7070Spatrick     Str += TypeString;
2257e5dd7070Spatrick     return;
2258e5dd7070Spatrick   }
2259e5dd7070Spatrick   while (*argPtr) {
2260e5dd7070Spatrick     Str += (*argPtr == '^' ? '*' : *argPtr);
2261e5dd7070Spatrick     argPtr++;
2262e5dd7070Spatrick   }
2263e5dd7070Spatrick }
2264e5dd7070Spatrick 
2265e5dd7070Spatrick // FIXME. Consolidate this routine with RewriteBlockPointerType.
RewriteBlockPointerTypeVariable(std::string & Str,ValueDecl * VD)2266e5dd7070Spatrick void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2267e5dd7070Spatrick                                                   ValueDecl *VD) {
2268e5dd7070Spatrick   QualType Type = VD->getType();
2269e5dd7070Spatrick   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2270e5dd7070Spatrick   const char *argPtr = TypeString.c_str();
2271e5dd7070Spatrick   int paren = 0;
2272e5dd7070Spatrick   while (*argPtr) {
2273e5dd7070Spatrick     switch (*argPtr) {
2274e5dd7070Spatrick       case '(':
2275e5dd7070Spatrick         Str += *argPtr;
2276e5dd7070Spatrick         paren++;
2277e5dd7070Spatrick         break;
2278e5dd7070Spatrick       case ')':
2279e5dd7070Spatrick         Str += *argPtr;
2280e5dd7070Spatrick         paren--;
2281e5dd7070Spatrick         break;
2282e5dd7070Spatrick       case '^':
2283e5dd7070Spatrick         Str += '*';
2284e5dd7070Spatrick         if (paren == 1)
2285e5dd7070Spatrick           Str += VD->getNameAsString();
2286e5dd7070Spatrick         break;
2287e5dd7070Spatrick       default:
2288e5dd7070Spatrick         Str += *argPtr;
2289e5dd7070Spatrick         break;
2290e5dd7070Spatrick     }
2291e5dd7070Spatrick     argPtr++;
2292e5dd7070Spatrick   }
2293e5dd7070Spatrick }
2294e5dd7070Spatrick 
RewriteBlockLiteralFunctionDecl(FunctionDecl * FD)2295e5dd7070Spatrick void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2296e5dd7070Spatrick   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2297e5dd7070Spatrick   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2298e5dd7070Spatrick   const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType);
2299e5dd7070Spatrick   if (!proto)
2300e5dd7070Spatrick     return;
2301e5dd7070Spatrick   QualType Type = proto->getReturnType();
2302e5dd7070Spatrick   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2303e5dd7070Spatrick   FdStr += " ";
2304e5dd7070Spatrick   FdStr += FD->getName();
2305e5dd7070Spatrick   FdStr +=  "(";
2306e5dd7070Spatrick   unsigned numArgs = proto->getNumParams();
2307e5dd7070Spatrick   for (unsigned i = 0; i < numArgs; i++) {
2308e5dd7070Spatrick     QualType ArgType = proto->getParamType(i);
2309e5dd7070Spatrick     RewriteBlockPointerType(FdStr, ArgType);
2310e5dd7070Spatrick     if (i+1 < numArgs)
2311e5dd7070Spatrick       FdStr += ", ";
2312e5dd7070Spatrick   }
2313e5dd7070Spatrick   FdStr +=  ");\n";
2314e5dd7070Spatrick   InsertText(FunLocStart, FdStr);
2315e5dd7070Spatrick   CurFunctionDeclToDeclareForBlock = nullptr;
2316e5dd7070Spatrick }
2317e5dd7070Spatrick 
2318e5dd7070Spatrick // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
SynthSuperConstructorFunctionDecl()2319e5dd7070Spatrick void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2320e5dd7070Spatrick   if (SuperConstructorFunctionDecl)
2321e5dd7070Spatrick     return;
2322e5dd7070Spatrick   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2323e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2324e5dd7070Spatrick   QualType argT = Context->getObjCIdType();
2325e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'id' type");
2326e5dd7070Spatrick   ArgTys.push_back(argT);
2327e5dd7070Spatrick   ArgTys.push_back(argT);
2328e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2329e5dd7070Spatrick                                                ArgTys);
2330e5dd7070Spatrick   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2331e5dd7070Spatrick                                                      SourceLocation(),
2332e5dd7070Spatrick                                                      SourceLocation(),
2333e5dd7070Spatrick                                                      msgSendIdent, msgSendType,
2334e5dd7070Spatrick                                                      nullptr, SC_Extern);
2335e5dd7070Spatrick }
2336e5dd7070Spatrick 
2337e5dd7070Spatrick // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
SynthMsgSendFunctionDecl()2338e5dd7070Spatrick void RewriteObjC::SynthMsgSendFunctionDecl() {
2339e5dd7070Spatrick   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2340e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2341e5dd7070Spatrick   QualType argT = Context->getObjCIdType();
2342e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'id' type");
2343e5dd7070Spatrick   ArgTys.push_back(argT);
2344e5dd7070Spatrick   argT = Context->getObjCSelType();
2345e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'SEL' type");
2346e5dd7070Spatrick   ArgTys.push_back(argT);
2347e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2348e5dd7070Spatrick                                                ArgTys, /*variadic=*/true);
2349e5dd7070Spatrick   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2350e5dd7070Spatrick                                              SourceLocation(),
2351e5dd7070Spatrick                                              SourceLocation(),
2352e5dd7070Spatrick                                              msgSendIdent, msgSendType,
2353e5dd7070Spatrick                                              nullptr, SC_Extern);
2354e5dd7070Spatrick }
2355e5dd7070Spatrick 
2356e5dd7070Spatrick // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
SynthMsgSendSuperFunctionDecl()2357e5dd7070Spatrick void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2358e5dd7070Spatrick   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2359e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2360e5dd7070Spatrick   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2361e5dd7070Spatrick                                       SourceLocation(), SourceLocation(),
2362e5dd7070Spatrick                                       &Context->Idents.get("objc_super"));
2363e5dd7070Spatrick   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2364e5dd7070Spatrick   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2365e5dd7070Spatrick   ArgTys.push_back(argT);
2366e5dd7070Spatrick   argT = Context->getObjCSelType();
2367e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'SEL' type");
2368e5dd7070Spatrick   ArgTys.push_back(argT);
2369e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2370e5dd7070Spatrick                                                ArgTys, /*variadic=*/true);
2371e5dd7070Spatrick   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2372e5dd7070Spatrick                                                   SourceLocation(),
2373e5dd7070Spatrick                                                   SourceLocation(),
2374e5dd7070Spatrick                                                   msgSendIdent, msgSendType,
2375e5dd7070Spatrick                                                   nullptr, SC_Extern);
2376e5dd7070Spatrick }
2377e5dd7070Spatrick 
2378e5dd7070Spatrick // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
SynthMsgSendStretFunctionDecl()2379e5dd7070Spatrick void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2380e5dd7070Spatrick   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2381e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2382e5dd7070Spatrick   QualType argT = Context->getObjCIdType();
2383e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'id' type");
2384e5dd7070Spatrick   ArgTys.push_back(argT);
2385e5dd7070Spatrick   argT = Context->getObjCSelType();
2386e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'SEL' type");
2387e5dd7070Spatrick   ArgTys.push_back(argT);
2388e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2389e5dd7070Spatrick                                                ArgTys, /*variadic=*/true);
2390e5dd7070Spatrick   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2391e5dd7070Spatrick                                                   SourceLocation(),
2392e5dd7070Spatrick                                                   SourceLocation(),
2393e5dd7070Spatrick                                                   msgSendIdent, msgSendType,
2394e5dd7070Spatrick                                                   nullptr, SC_Extern);
2395e5dd7070Spatrick }
2396e5dd7070Spatrick 
2397e5dd7070Spatrick // SynthMsgSendSuperStretFunctionDecl -
2398e5dd7070Spatrick // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
SynthMsgSendSuperStretFunctionDecl()2399e5dd7070Spatrick void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2400e5dd7070Spatrick   IdentifierInfo *msgSendIdent =
2401e5dd7070Spatrick     &Context->Idents.get("objc_msgSendSuper_stret");
2402e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2403e5dd7070Spatrick   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2404e5dd7070Spatrick                                       SourceLocation(), SourceLocation(),
2405e5dd7070Spatrick                                       &Context->Idents.get("objc_super"));
2406e5dd7070Spatrick   QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2407e5dd7070Spatrick   assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2408e5dd7070Spatrick   ArgTys.push_back(argT);
2409e5dd7070Spatrick   argT = Context->getObjCSelType();
2410e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'SEL' type");
2411e5dd7070Spatrick   ArgTys.push_back(argT);
2412e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2413e5dd7070Spatrick                                                ArgTys, /*variadic=*/true);
2414e5dd7070Spatrick   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2415e5dd7070Spatrick                                                        SourceLocation(),
2416e5dd7070Spatrick                                                        SourceLocation(),
2417e5dd7070Spatrick                                                        msgSendIdent,
2418e5dd7070Spatrick                                                        msgSendType, nullptr,
2419e5dd7070Spatrick                                                        SC_Extern);
2420e5dd7070Spatrick }
2421e5dd7070Spatrick 
2422e5dd7070Spatrick // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
SynthMsgSendFpretFunctionDecl()2423e5dd7070Spatrick void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2424e5dd7070Spatrick   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2425e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2426e5dd7070Spatrick   QualType argT = Context->getObjCIdType();
2427e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'id' type");
2428e5dd7070Spatrick   ArgTys.push_back(argT);
2429e5dd7070Spatrick   argT = Context->getObjCSelType();
2430e5dd7070Spatrick   assert(!argT.isNull() && "Can't find 'SEL' type");
2431e5dd7070Spatrick   ArgTys.push_back(argT);
2432e5dd7070Spatrick   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2433e5dd7070Spatrick                                                ArgTys, /*variadic=*/true);
2434e5dd7070Spatrick   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2435e5dd7070Spatrick                                                   SourceLocation(),
2436e5dd7070Spatrick                                                   SourceLocation(),
2437e5dd7070Spatrick                                                   msgSendIdent, msgSendType,
2438e5dd7070Spatrick                                                   nullptr, SC_Extern);
2439e5dd7070Spatrick }
2440e5dd7070Spatrick 
2441e5dd7070Spatrick // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
SynthGetClassFunctionDecl()2442e5dd7070Spatrick void RewriteObjC::SynthGetClassFunctionDecl() {
2443e5dd7070Spatrick   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2444e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2445e5dd7070Spatrick   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2446e5dd7070Spatrick   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2447e5dd7070Spatrick                                                 ArgTys);
2448e5dd7070Spatrick   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2449e5dd7070Spatrick                                               SourceLocation(),
2450e5dd7070Spatrick                                               SourceLocation(),
2451e5dd7070Spatrick                                               getClassIdent, getClassType,
2452e5dd7070Spatrick                                               nullptr, SC_Extern);
2453e5dd7070Spatrick }
2454e5dd7070Spatrick 
2455e5dd7070Spatrick // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
SynthGetSuperClassFunctionDecl()2456e5dd7070Spatrick void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2457e5dd7070Spatrick   IdentifierInfo *getSuperClassIdent =
2458e5dd7070Spatrick     &Context->Idents.get("class_getSuperclass");
2459e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2460e5dd7070Spatrick   ArgTys.push_back(Context->getObjCClassType());
2461e5dd7070Spatrick   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2462e5dd7070Spatrick                                                 ArgTys);
2463e5dd7070Spatrick   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2464e5dd7070Spatrick                                                    SourceLocation(),
2465e5dd7070Spatrick                                                    SourceLocation(),
2466e5dd7070Spatrick                                                    getSuperClassIdent,
2467e5dd7070Spatrick                                                    getClassType, nullptr,
2468e5dd7070Spatrick                                                    SC_Extern);
2469e5dd7070Spatrick }
2470e5dd7070Spatrick 
2471e5dd7070Spatrick // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
SynthGetMetaClassFunctionDecl()2472e5dd7070Spatrick void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2473e5dd7070Spatrick   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2474e5dd7070Spatrick   SmallVector<QualType, 16> ArgTys;
2475e5dd7070Spatrick   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2476e5dd7070Spatrick   QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2477e5dd7070Spatrick                                                 ArgTys);
2478e5dd7070Spatrick   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2479e5dd7070Spatrick                                                   SourceLocation(),
2480e5dd7070Spatrick                                                   SourceLocation(),
2481e5dd7070Spatrick                                                   getClassIdent, getClassType,
2482e5dd7070Spatrick                                                   nullptr, SC_Extern);
2483e5dd7070Spatrick }
2484e5dd7070Spatrick 
RewriteObjCStringLiteral(ObjCStringLiteral * Exp)2485e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2486e5dd7070Spatrick   assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2487e5dd7070Spatrick   QualType strType = getConstantStringStructType();
2488e5dd7070Spatrick 
2489e5dd7070Spatrick   std::string S = "__NSConstantStringImpl_";
2490e5dd7070Spatrick 
2491e5dd7070Spatrick   std::string tmpName = InFileName;
2492e5dd7070Spatrick   unsigned i;
2493e5dd7070Spatrick   for (i=0; i < tmpName.length(); i++) {
2494e5dd7070Spatrick     char c = tmpName.at(i);
2495e5dd7070Spatrick     // replace any non-alphanumeric characters with '_'.
2496e5dd7070Spatrick     if (!isAlphanumeric(c))
2497e5dd7070Spatrick       tmpName[i] = '_';
2498e5dd7070Spatrick   }
2499e5dd7070Spatrick   S += tmpName;
2500e5dd7070Spatrick   S += "_";
2501e5dd7070Spatrick   S += utostr(NumObjCStringLiterals++);
2502e5dd7070Spatrick 
2503e5dd7070Spatrick   Preamble += "static __NSConstantStringImpl " + S;
2504e5dd7070Spatrick   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2505e5dd7070Spatrick   Preamble += "0x000007c8,"; // utf8_str
2506e5dd7070Spatrick   // The pretty printer for StringLiteral handles escape characters properly.
2507e5dd7070Spatrick   std::string prettyBufS;
2508e5dd7070Spatrick   llvm::raw_string_ostream prettyBuf(prettyBufS);
2509e5dd7070Spatrick   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2510e5dd7070Spatrick   Preamble += prettyBuf.str();
2511e5dd7070Spatrick   Preamble += ",";
2512e5dd7070Spatrick   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2513e5dd7070Spatrick 
2514e5dd7070Spatrick   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2515e5dd7070Spatrick                                    SourceLocation(), &Context->Idents.get(S),
2516e5dd7070Spatrick                                    strType, nullptr, SC_Static);
2517e5dd7070Spatrick   DeclRefExpr *DRE = new (Context)
2518e5dd7070Spatrick       DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2519ec727ea7Spatrick   Expr *Unop = UnaryOperator::Create(
2520ec727ea7Spatrick       const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
2521a9ac8606Spatrick       Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
2522ec727ea7Spatrick       SourceLocation(), false, FPOptionsOverride());
2523e5dd7070Spatrick   // cast to NSConstantString *
2524e5dd7070Spatrick   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2525e5dd7070Spatrick                                             CK_CPointerToObjCPointerCast, Unop);
2526e5dd7070Spatrick   ReplaceStmt(Exp, cast);
2527e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2528e5dd7070Spatrick   return cast;
2529e5dd7070Spatrick }
2530e5dd7070Spatrick 
2531e5dd7070Spatrick // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
getSuperStructType()2532e5dd7070Spatrick QualType RewriteObjC::getSuperStructType() {
2533e5dd7070Spatrick   if (!SuperStructDecl) {
2534e5dd7070Spatrick     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2535e5dd7070Spatrick                                          SourceLocation(), SourceLocation(),
2536e5dd7070Spatrick                                          &Context->Idents.get("objc_super"));
2537e5dd7070Spatrick     QualType FieldTypes[2];
2538e5dd7070Spatrick 
2539e5dd7070Spatrick     // struct objc_object *receiver;
2540e5dd7070Spatrick     FieldTypes[0] = Context->getObjCIdType();
2541e5dd7070Spatrick     // struct objc_class *super;
2542e5dd7070Spatrick     FieldTypes[1] = Context->getObjCClassType();
2543e5dd7070Spatrick 
2544e5dd7070Spatrick     // Create fields
2545e5dd7070Spatrick     for (unsigned i = 0; i < 2; ++i) {
2546e5dd7070Spatrick       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2547e5dd7070Spatrick                                                  SourceLocation(),
2548e5dd7070Spatrick                                                  SourceLocation(), nullptr,
2549e5dd7070Spatrick                                                  FieldTypes[i], nullptr,
2550e5dd7070Spatrick                                                  /*BitWidth=*/nullptr,
2551e5dd7070Spatrick                                                  /*Mutable=*/false,
2552e5dd7070Spatrick                                                  ICIS_NoInit));
2553e5dd7070Spatrick     }
2554e5dd7070Spatrick 
2555e5dd7070Spatrick     SuperStructDecl->completeDefinition();
2556e5dd7070Spatrick   }
2557e5dd7070Spatrick   return Context->getTagDeclType(SuperStructDecl);
2558e5dd7070Spatrick }
2559e5dd7070Spatrick 
getConstantStringStructType()2560e5dd7070Spatrick QualType RewriteObjC::getConstantStringStructType() {
2561e5dd7070Spatrick   if (!ConstantStringDecl) {
2562e5dd7070Spatrick     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2563e5dd7070Spatrick                                             SourceLocation(), SourceLocation(),
2564e5dd7070Spatrick                          &Context->Idents.get("__NSConstantStringImpl"));
2565e5dd7070Spatrick     QualType FieldTypes[4];
2566e5dd7070Spatrick 
2567e5dd7070Spatrick     // struct objc_object *receiver;
2568e5dd7070Spatrick     FieldTypes[0] = Context->getObjCIdType();
2569e5dd7070Spatrick     // int flags;
2570e5dd7070Spatrick     FieldTypes[1] = Context->IntTy;
2571e5dd7070Spatrick     // char *str;
2572e5dd7070Spatrick     FieldTypes[2] = Context->getPointerType(Context->CharTy);
2573e5dd7070Spatrick     // long length;
2574e5dd7070Spatrick     FieldTypes[3] = Context->LongTy;
2575e5dd7070Spatrick 
2576e5dd7070Spatrick     // Create fields
2577e5dd7070Spatrick     for (unsigned i = 0; i < 4; ++i) {
2578e5dd7070Spatrick       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2579e5dd7070Spatrick                                                     ConstantStringDecl,
2580e5dd7070Spatrick                                                     SourceLocation(),
2581e5dd7070Spatrick                                                     SourceLocation(), nullptr,
2582e5dd7070Spatrick                                                     FieldTypes[i], nullptr,
2583e5dd7070Spatrick                                                     /*BitWidth=*/nullptr,
2584e5dd7070Spatrick                                                     /*Mutable=*/true,
2585e5dd7070Spatrick                                                     ICIS_NoInit));
2586e5dd7070Spatrick     }
2587e5dd7070Spatrick 
2588e5dd7070Spatrick     ConstantStringDecl->completeDefinition();
2589e5dd7070Spatrick   }
2590e5dd7070Spatrick   return Context->getTagDeclType(ConstantStringDecl);
2591e5dd7070Spatrick }
2592e5dd7070Spatrick 
SynthMsgSendStretCallExpr(FunctionDecl * MsgSendStretFlavor,QualType msgSendType,QualType returnType,SmallVectorImpl<QualType> & ArgTypes,SmallVectorImpl<Expr * > & MsgExprs,ObjCMethodDecl * Method)2593e5dd7070Spatrick CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2594e5dd7070Spatrick                                                 QualType msgSendType,
2595e5dd7070Spatrick                                                 QualType returnType,
2596e5dd7070Spatrick                                                 SmallVectorImpl<QualType> &ArgTypes,
2597e5dd7070Spatrick                                                 SmallVectorImpl<Expr*> &MsgExprs,
2598e5dd7070Spatrick                                                 ObjCMethodDecl *Method) {
2599e5dd7070Spatrick   // Create a reference to the objc_msgSend_stret() declaration.
2600e5dd7070Spatrick   DeclRefExpr *STDRE =
2601e5dd7070Spatrick       new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
2602e5dd7070Spatrick                                 msgSendType, VK_LValue, SourceLocation());
2603e5dd7070Spatrick   // Need to cast objc_msgSend_stret to "void *" (see above comment).
2604e5dd7070Spatrick   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2605e5dd7070Spatrick                                   Context->getPointerType(Context->VoidTy),
2606e5dd7070Spatrick                                   CK_BitCast, STDRE);
2607e5dd7070Spatrick   // Now do the "normal" pointer to function cast.
2608e5dd7070Spatrick   QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2609e5dd7070Spatrick                                             Method ? Method->isVariadic()
2610e5dd7070Spatrick                                                    : false);
2611e5dd7070Spatrick   castType = Context->getPointerType(castType);
2612e5dd7070Spatrick   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2613e5dd7070Spatrick                                             cast);
2614e5dd7070Spatrick 
2615e5dd7070Spatrick   // Don't forget the parens to enforce the proper binding.
2616e5dd7070Spatrick   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2617e5dd7070Spatrick 
2618e5dd7070Spatrick   const auto *FT = msgSendType->castAs<FunctionType>();
2619a9ac8606Spatrick   CallExpr *STCE =
2620a9ac8606Spatrick       CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue,
2621a9ac8606Spatrick                        SourceLocation(), FPOptionsOverride());
2622e5dd7070Spatrick   return STCE;
2623e5dd7070Spatrick }
2624e5dd7070Spatrick 
SynthMessageExpr(ObjCMessageExpr * Exp,SourceLocation StartLoc,SourceLocation EndLoc)2625e5dd7070Spatrick Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2626e5dd7070Spatrick                                     SourceLocation StartLoc,
2627e5dd7070Spatrick                                     SourceLocation EndLoc) {
2628e5dd7070Spatrick   if (!SelGetUidFunctionDecl)
2629e5dd7070Spatrick     SynthSelGetUidFunctionDecl();
2630e5dd7070Spatrick   if (!MsgSendFunctionDecl)
2631e5dd7070Spatrick     SynthMsgSendFunctionDecl();
2632e5dd7070Spatrick   if (!MsgSendSuperFunctionDecl)
2633e5dd7070Spatrick     SynthMsgSendSuperFunctionDecl();
2634e5dd7070Spatrick   if (!MsgSendStretFunctionDecl)
2635e5dd7070Spatrick     SynthMsgSendStretFunctionDecl();
2636e5dd7070Spatrick   if (!MsgSendSuperStretFunctionDecl)
2637e5dd7070Spatrick     SynthMsgSendSuperStretFunctionDecl();
2638e5dd7070Spatrick   if (!MsgSendFpretFunctionDecl)
2639e5dd7070Spatrick     SynthMsgSendFpretFunctionDecl();
2640e5dd7070Spatrick   if (!GetClassFunctionDecl)
2641e5dd7070Spatrick     SynthGetClassFunctionDecl();
2642e5dd7070Spatrick   if (!GetSuperClassFunctionDecl)
2643e5dd7070Spatrick     SynthGetSuperClassFunctionDecl();
2644e5dd7070Spatrick   if (!GetMetaClassFunctionDecl)
2645e5dd7070Spatrick     SynthGetMetaClassFunctionDecl();
2646e5dd7070Spatrick 
2647e5dd7070Spatrick   // default to objc_msgSend().
2648e5dd7070Spatrick   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2649e5dd7070Spatrick   // May need to use objc_msgSend_stret() as well.
2650e5dd7070Spatrick   FunctionDecl *MsgSendStretFlavor = nullptr;
2651e5dd7070Spatrick   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2652e5dd7070Spatrick     QualType resultType = mDecl->getReturnType();
2653e5dd7070Spatrick     if (resultType->isRecordType())
2654e5dd7070Spatrick       MsgSendStretFlavor = MsgSendStretFunctionDecl;
2655e5dd7070Spatrick     else if (resultType->isRealFloatingType())
2656e5dd7070Spatrick       MsgSendFlavor = MsgSendFpretFunctionDecl;
2657e5dd7070Spatrick   }
2658e5dd7070Spatrick 
2659e5dd7070Spatrick   // Synthesize a call to objc_msgSend().
2660e5dd7070Spatrick   SmallVector<Expr*, 8> MsgExprs;
2661e5dd7070Spatrick   switch (Exp->getReceiverKind()) {
2662e5dd7070Spatrick   case ObjCMessageExpr::SuperClass: {
2663e5dd7070Spatrick     MsgSendFlavor = MsgSendSuperFunctionDecl;
2664e5dd7070Spatrick     if (MsgSendStretFlavor)
2665e5dd7070Spatrick       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2666e5dd7070Spatrick     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2667e5dd7070Spatrick 
2668e5dd7070Spatrick     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2669e5dd7070Spatrick 
2670e5dd7070Spatrick     SmallVector<Expr*, 4> InitExprs;
2671e5dd7070Spatrick 
2672e5dd7070Spatrick     // set the receiver to self, the first argument to all methods.
2673a9ac8606Spatrick     InitExprs.push_back(NoTypeInfoCStyleCastExpr(
2674a9ac8606Spatrick         Context, Context->getObjCIdType(), CK_BitCast,
2675a9ac8606Spatrick         new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
2676a9ac8606Spatrick                                   Context->getObjCIdType(), VK_PRValue,
2677a9ac8606Spatrick                                   SourceLocation()))); // set the 'receiver'.
2678e5dd7070Spatrick 
2679e5dd7070Spatrick     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2680e5dd7070Spatrick     SmallVector<Expr*, 8> ClsExprs;
2681e5dd7070Spatrick     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2682e5dd7070Spatrick     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683e5dd7070Spatrick                                                  ClsExprs, StartLoc, EndLoc);
2684e5dd7070Spatrick     // (Class)objc_getClass("CurrentClass")
2685e5dd7070Spatrick     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2686e5dd7070Spatrick                                              Context->getObjCClassType(),
2687e5dd7070Spatrick                                              CK_BitCast, Cls);
2688e5dd7070Spatrick     ClsExprs.clear();
2689e5dd7070Spatrick     ClsExprs.push_back(ArgExpr);
2690e5dd7070Spatrick     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2691e5dd7070Spatrick                                        StartLoc, EndLoc);
2692e5dd7070Spatrick     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2693e5dd7070Spatrick     // To turn off a warning, type-cast to 'id'
2694e5dd7070Spatrick     InitExprs.push_back( // set 'super class', using class_getSuperclass().
2695e5dd7070Spatrick                         NoTypeInfoCStyleCastExpr(Context,
2696e5dd7070Spatrick                                                  Context->getObjCIdType(),
2697e5dd7070Spatrick                                                  CK_BitCast, Cls));
2698e5dd7070Spatrick     // struct objc_super
2699e5dd7070Spatrick     QualType superType = getSuperStructType();
2700e5dd7070Spatrick     Expr *SuperRep;
2701e5dd7070Spatrick 
2702e5dd7070Spatrick     if (LangOpts.MicrosoftExt) {
2703e5dd7070Spatrick       SynthSuperConstructorFunctionDecl();
2704e5dd7070Spatrick       // Simulate a constructor call...
2705e5dd7070Spatrick       DeclRefExpr *DRE = new (Context)
2706e5dd7070Spatrick           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2707e5dd7070Spatrick                       VK_LValue, SourceLocation());
2708a9ac8606Spatrick       SuperRep =
2709a9ac8606Spatrick           CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2710a9ac8606Spatrick                            SourceLocation(), FPOptionsOverride());
2711e5dd7070Spatrick       // The code for super is a little tricky to prevent collision with
2712e5dd7070Spatrick       // the structure definition in the header. The rewriter has it's own
2713e5dd7070Spatrick       // internal definition (__rw_objc_super) that is uses. This is why
2714e5dd7070Spatrick       // we need the cast below. For example:
2715e5dd7070Spatrick       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2716e5dd7070Spatrick       //
2717ec727ea7Spatrick       SuperRep = UnaryOperator::Create(
2718ec727ea7Spatrick           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2719a9ac8606Spatrick           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
2720ec727ea7Spatrick           SourceLocation(), false, FPOptionsOverride());
2721e5dd7070Spatrick       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2722e5dd7070Spatrick                                           Context->getPointerType(superType),
2723e5dd7070Spatrick                                           CK_BitCast, SuperRep);
2724e5dd7070Spatrick     } else {
2725e5dd7070Spatrick       // (struct objc_super) { <exprs from above> }
2726e5dd7070Spatrick       InitListExpr *ILE =
2727e5dd7070Spatrick         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2728e5dd7070Spatrick                                    SourceLocation());
2729e5dd7070Spatrick       TypeSourceInfo *superTInfo
2730e5dd7070Spatrick         = Context->getTrivialTypeSourceInfo(superType);
2731e5dd7070Spatrick       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2732e5dd7070Spatrick                                                    superType, VK_LValue,
2733e5dd7070Spatrick                                                    ILE, false);
2734e5dd7070Spatrick       // struct objc_super *
2735ec727ea7Spatrick       SuperRep = UnaryOperator::Create(
2736ec727ea7Spatrick           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2737a9ac8606Spatrick           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
2738ec727ea7Spatrick           SourceLocation(), false, FPOptionsOverride());
2739e5dd7070Spatrick     }
2740e5dd7070Spatrick     MsgExprs.push_back(SuperRep);
2741e5dd7070Spatrick     break;
2742e5dd7070Spatrick   }
2743e5dd7070Spatrick 
2744e5dd7070Spatrick   case ObjCMessageExpr::Class: {
2745e5dd7070Spatrick     SmallVector<Expr*, 8> ClsExprs;
2746e5dd7070Spatrick     auto *Class =
2747e5dd7070Spatrick         Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
2748e5dd7070Spatrick     IdentifierInfo *clsName = Class->getIdentifier();
2749e5dd7070Spatrick     ClsExprs.push_back(getStringLiteral(clsName->getName()));
2750e5dd7070Spatrick     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2751e5dd7070Spatrick                                                  StartLoc, EndLoc);
2752e5dd7070Spatrick     MsgExprs.push_back(Cls);
2753e5dd7070Spatrick     break;
2754e5dd7070Spatrick   }
2755e5dd7070Spatrick 
2756e5dd7070Spatrick   case ObjCMessageExpr::SuperInstance:{
2757e5dd7070Spatrick     MsgSendFlavor = MsgSendSuperFunctionDecl;
2758e5dd7070Spatrick     if (MsgSendStretFlavor)
2759e5dd7070Spatrick       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2760e5dd7070Spatrick     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2761e5dd7070Spatrick     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2762e5dd7070Spatrick     SmallVector<Expr*, 4> InitExprs;
2763e5dd7070Spatrick 
2764a9ac8606Spatrick     InitExprs.push_back(NoTypeInfoCStyleCastExpr(
2765a9ac8606Spatrick         Context, Context->getObjCIdType(), CK_BitCast,
2766a9ac8606Spatrick         new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
2767a9ac8606Spatrick                                   Context->getObjCIdType(), VK_PRValue,
2768a9ac8606Spatrick                                   SourceLocation()))); // set the 'receiver'.
2769e5dd7070Spatrick 
2770e5dd7070Spatrick     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2771e5dd7070Spatrick     SmallVector<Expr*, 8> ClsExprs;
2772e5dd7070Spatrick     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2773e5dd7070Spatrick     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2774e5dd7070Spatrick                                                  StartLoc, EndLoc);
2775e5dd7070Spatrick     // (Class)objc_getClass("CurrentClass")
2776e5dd7070Spatrick     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2777e5dd7070Spatrick                                                  Context->getObjCClassType(),
2778e5dd7070Spatrick                                                  CK_BitCast, Cls);
2779e5dd7070Spatrick     ClsExprs.clear();
2780e5dd7070Spatrick     ClsExprs.push_back(ArgExpr);
2781e5dd7070Spatrick     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2782e5dd7070Spatrick                                        StartLoc, EndLoc);
2783e5dd7070Spatrick 
2784e5dd7070Spatrick     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2785e5dd7070Spatrick     // To turn off a warning, type-cast to 'id'
2786e5dd7070Spatrick     InitExprs.push_back(
2787e5dd7070Spatrick       // set 'super class', using class_getSuperclass().
2788e5dd7070Spatrick       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2789e5dd7070Spatrick                                CK_BitCast, Cls));
2790e5dd7070Spatrick     // struct objc_super
2791e5dd7070Spatrick     QualType superType = getSuperStructType();
2792e5dd7070Spatrick     Expr *SuperRep;
2793e5dd7070Spatrick 
2794e5dd7070Spatrick     if (LangOpts.MicrosoftExt) {
2795e5dd7070Spatrick       SynthSuperConstructorFunctionDecl();
2796e5dd7070Spatrick       // Simulate a constructor call...
2797e5dd7070Spatrick       DeclRefExpr *DRE = new (Context)
2798e5dd7070Spatrick           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2799e5dd7070Spatrick                       VK_LValue, SourceLocation());
2800a9ac8606Spatrick       SuperRep =
2801a9ac8606Spatrick           CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
2802a9ac8606Spatrick                            SourceLocation(), FPOptionsOverride());
2803e5dd7070Spatrick       // The code for super is a little tricky to prevent collision with
2804e5dd7070Spatrick       // the structure definition in the header. The rewriter has it's own
2805e5dd7070Spatrick       // internal definition (__rw_objc_super) that is uses. This is why
2806e5dd7070Spatrick       // we need the cast below. For example:
2807e5dd7070Spatrick       // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2808e5dd7070Spatrick       //
2809ec727ea7Spatrick       SuperRep = UnaryOperator::Create(
2810ec727ea7Spatrick           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
2811a9ac8606Spatrick           Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
2812ec727ea7Spatrick           SourceLocation(), false, FPOptionsOverride());
2813e5dd7070Spatrick       SuperRep = NoTypeInfoCStyleCastExpr(Context,
2814e5dd7070Spatrick                                Context->getPointerType(superType),
2815e5dd7070Spatrick                                CK_BitCast, SuperRep);
2816e5dd7070Spatrick     } else {
2817e5dd7070Spatrick       // (struct objc_super) { <exprs from above> }
2818e5dd7070Spatrick       InitListExpr *ILE =
2819e5dd7070Spatrick         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2820e5dd7070Spatrick                                    SourceLocation());
2821e5dd7070Spatrick       TypeSourceInfo *superTInfo
2822e5dd7070Spatrick         = Context->getTrivialTypeSourceInfo(superType);
2823a9ac8606Spatrick       SuperRep = new (Context) CompoundLiteralExpr(
2824a9ac8606Spatrick           SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
2825e5dd7070Spatrick     }
2826e5dd7070Spatrick     MsgExprs.push_back(SuperRep);
2827e5dd7070Spatrick     break;
2828e5dd7070Spatrick   }
2829e5dd7070Spatrick 
2830e5dd7070Spatrick   case ObjCMessageExpr::Instance: {
2831e5dd7070Spatrick     // Remove all type-casts because it may contain objc-style types; e.g.
2832e5dd7070Spatrick     // Foo<Proto> *.
2833e5dd7070Spatrick     Expr *recExpr = Exp->getInstanceReceiver();
2834e5dd7070Spatrick     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2835e5dd7070Spatrick       recExpr = CE->getSubExpr();
2836e5dd7070Spatrick     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2837e5dd7070Spatrick                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2838e5dd7070Spatrick                                      ? CK_BlockPointerToObjCPointerCast
2839e5dd7070Spatrick                                      : CK_CPointerToObjCPointerCast;
2840e5dd7070Spatrick 
2841e5dd7070Spatrick     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2842e5dd7070Spatrick                                        CK, recExpr);
2843e5dd7070Spatrick     MsgExprs.push_back(recExpr);
2844e5dd7070Spatrick     break;
2845e5dd7070Spatrick   }
2846e5dd7070Spatrick   }
2847e5dd7070Spatrick 
2848e5dd7070Spatrick   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2849e5dd7070Spatrick   SmallVector<Expr*, 8> SelExprs;
2850e5dd7070Spatrick   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2851e5dd7070Spatrick   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2852e5dd7070Spatrick                                                   SelExprs, StartLoc, EndLoc);
2853e5dd7070Spatrick   MsgExprs.push_back(SelExp);
2854e5dd7070Spatrick 
2855e5dd7070Spatrick   // Now push any user supplied arguments.
2856e5dd7070Spatrick   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2857e5dd7070Spatrick     Expr *userExpr = Exp->getArg(i);
2858e5dd7070Spatrick     // Make all implicit casts explicit...ICE comes in handy:-)
2859e5dd7070Spatrick     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2860e5dd7070Spatrick       // Reuse the ICE type, it is exactly what the doctor ordered.
2861e5dd7070Spatrick       QualType type = ICE->getType();
2862e5dd7070Spatrick       if (needToScanForQualifiers(type))
2863e5dd7070Spatrick         type = Context->getObjCIdType();
2864e5dd7070Spatrick       // Make sure we convert "type (^)(...)" to "type (*)(...)".
2865e5dd7070Spatrick       (void)convertBlockPointerToFunctionPointer(type);
2866e5dd7070Spatrick       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2867e5dd7070Spatrick       CastKind CK;
2868e5dd7070Spatrick       if (SubExpr->getType()->isIntegralType(*Context) &&
2869e5dd7070Spatrick           type->isBooleanType()) {
2870e5dd7070Spatrick         CK = CK_IntegralToBoolean;
2871e5dd7070Spatrick       } else if (type->isObjCObjectPointerType()) {
2872e5dd7070Spatrick         if (SubExpr->getType()->isBlockPointerType()) {
2873e5dd7070Spatrick           CK = CK_BlockPointerToObjCPointerCast;
2874e5dd7070Spatrick         } else if (SubExpr->getType()->isPointerType()) {
2875e5dd7070Spatrick           CK = CK_CPointerToObjCPointerCast;
2876e5dd7070Spatrick         } else {
2877e5dd7070Spatrick           CK = CK_BitCast;
2878e5dd7070Spatrick         }
2879e5dd7070Spatrick       } else {
2880e5dd7070Spatrick         CK = CK_BitCast;
2881e5dd7070Spatrick       }
2882e5dd7070Spatrick 
2883e5dd7070Spatrick       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2884e5dd7070Spatrick     }
2885e5dd7070Spatrick     // Make id<P...> cast into an 'id' cast.
2886e5dd7070Spatrick     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2887e5dd7070Spatrick       if (CE->getType()->isObjCQualifiedIdType()) {
2888e5dd7070Spatrick         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2889e5dd7070Spatrick           userExpr = CE->getSubExpr();
2890e5dd7070Spatrick         CastKind CK;
2891e5dd7070Spatrick         if (userExpr->getType()->isIntegralType(*Context)) {
2892e5dd7070Spatrick           CK = CK_IntegralToPointer;
2893e5dd7070Spatrick         } else if (userExpr->getType()->isBlockPointerType()) {
2894e5dd7070Spatrick           CK = CK_BlockPointerToObjCPointerCast;
2895e5dd7070Spatrick         } else if (userExpr->getType()->isPointerType()) {
2896e5dd7070Spatrick           CK = CK_CPointerToObjCPointerCast;
2897e5dd7070Spatrick         } else {
2898e5dd7070Spatrick           CK = CK_BitCast;
2899e5dd7070Spatrick         }
2900e5dd7070Spatrick         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2901e5dd7070Spatrick                                             CK, userExpr);
2902e5dd7070Spatrick       }
2903e5dd7070Spatrick     }
2904e5dd7070Spatrick     MsgExprs.push_back(userExpr);
2905e5dd7070Spatrick     // We've transferred the ownership to MsgExprs. For now, we *don't* null
2906e5dd7070Spatrick     // out the argument in the original expression (since we aren't deleting
2907e5dd7070Spatrick     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2908e5dd7070Spatrick     //Exp->setArg(i, 0);
2909e5dd7070Spatrick   }
2910e5dd7070Spatrick   // Generate the funky cast.
2911e5dd7070Spatrick   CastExpr *cast;
2912e5dd7070Spatrick   SmallVector<QualType, 8> ArgTypes;
2913e5dd7070Spatrick   QualType returnType;
2914e5dd7070Spatrick 
2915e5dd7070Spatrick   // Push 'id' and 'SEL', the 2 implicit arguments.
2916e5dd7070Spatrick   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2917e5dd7070Spatrick     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2918e5dd7070Spatrick   else
2919e5dd7070Spatrick     ArgTypes.push_back(Context->getObjCIdType());
2920e5dd7070Spatrick   ArgTypes.push_back(Context->getObjCSelType());
2921e5dd7070Spatrick   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2922e5dd7070Spatrick     // Push any user argument types.
2923e5dd7070Spatrick     for (const auto *PI : OMD->parameters()) {
2924e5dd7070Spatrick       QualType t = PI->getType()->isObjCQualifiedIdType()
2925e5dd7070Spatrick                      ? Context->getObjCIdType()
2926e5dd7070Spatrick                      : PI->getType();
2927e5dd7070Spatrick       // Make sure we convert "t (^)(...)" to "t (*)(...)".
2928e5dd7070Spatrick       (void)convertBlockPointerToFunctionPointer(t);
2929e5dd7070Spatrick       ArgTypes.push_back(t);
2930e5dd7070Spatrick     }
2931e5dd7070Spatrick     returnType = Exp->getType();
2932e5dd7070Spatrick     convertToUnqualifiedObjCType(returnType);
2933e5dd7070Spatrick     (void)convertBlockPointerToFunctionPointer(returnType);
2934e5dd7070Spatrick   } else {
2935e5dd7070Spatrick     returnType = Context->getObjCIdType();
2936e5dd7070Spatrick   }
2937e5dd7070Spatrick   // Get the type, we will need to reference it in a couple spots.
2938e5dd7070Spatrick   QualType msgSendType = MsgSendFlavor->getType();
2939e5dd7070Spatrick 
2940e5dd7070Spatrick   // Create a reference to the objc_msgSend() declaration.
2941e5dd7070Spatrick   DeclRefExpr *DRE = new (Context) DeclRefExpr(
2942e5dd7070Spatrick       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2943e5dd7070Spatrick 
2944e5dd7070Spatrick   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2945e5dd7070Spatrick   // If we don't do this cast, we get the following bizarre warning/note:
2946e5dd7070Spatrick   // xx.m:13: warning: function called through a non-compatible type
2947e5dd7070Spatrick   // xx.m:13: note: if this code is reached, the program will abort
2948e5dd7070Spatrick   cast = NoTypeInfoCStyleCastExpr(Context,
2949e5dd7070Spatrick                                   Context->getPointerType(Context->VoidTy),
2950e5dd7070Spatrick                                   CK_BitCast, DRE);
2951e5dd7070Spatrick 
2952e5dd7070Spatrick   // Now do the "normal" pointer to function cast.
2953e5dd7070Spatrick   // If we don't have a method decl, force a variadic cast.
2954e5dd7070Spatrick   const ObjCMethodDecl *MD = Exp->getMethodDecl();
2955e5dd7070Spatrick   QualType castType =
2956e5dd7070Spatrick     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
2957e5dd7070Spatrick   castType = Context->getPointerType(castType);
2958e5dd7070Spatrick   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2959e5dd7070Spatrick                                   cast);
2960e5dd7070Spatrick 
2961e5dd7070Spatrick   // Don't forget the parens to enforce the proper binding.
2962e5dd7070Spatrick   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2963e5dd7070Spatrick 
2964e5dd7070Spatrick   const auto *FT = msgSendType->castAs<FunctionType>();
2965e5dd7070Spatrick   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2966a9ac8606Spatrick                                   VK_PRValue, EndLoc, FPOptionsOverride());
2967e5dd7070Spatrick   Stmt *ReplacingStmt = CE;
2968e5dd7070Spatrick   if (MsgSendStretFlavor) {
2969e5dd7070Spatrick     // We have the method which returns a struct/union. Must also generate
2970e5dd7070Spatrick     // call to objc_msgSend_stret and hang both varieties on a conditional
2971e5dd7070Spatrick     // expression which dictate which one to envoke depending on size of
2972e5dd7070Spatrick     // method's return type.
2973e5dd7070Spatrick 
2974e5dd7070Spatrick     CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2975e5dd7070Spatrick                                                msgSendType, returnType,
2976e5dd7070Spatrick                                                ArgTypes, MsgExprs,
2977e5dd7070Spatrick                                                Exp->getMethodDecl());
2978e5dd7070Spatrick 
2979e5dd7070Spatrick     // Build sizeof(returnType)
2980e5dd7070Spatrick     UnaryExprOrTypeTraitExpr *sizeofExpr =
2981e5dd7070Spatrick        new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2982e5dd7070Spatrick                                  Context->getTrivialTypeSourceInfo(returnType),
2983e5dd7070Spatrick                                  Context->getSizeType(), SourceLocation(),
2984e5dd7070Spatrick                                  SourceLocation());
2985e5dd7070Spatrick     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2986e5dd7070Spatrick     // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2987e5dd7070Spatrick     // For X86 it is more complicated and some kind of target specific routine
2988e5dd7070Spatrick     // is needed to decide what to do.
2989e5dd7070Spatrick     unsigned IntSize =
2990e5dd7070Spatrick       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2991e5dd7070Spatrick     IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2992e5dd7070Spatrick                                                    llvm::APInt(IntSize, 8),
2993e5dd7070Spatrick                                                    Context->IntTy,
2994e5dd7070Spatrick                                                    SourceLocation());
2995ec727ea7Spatrick     BinaryOperator *lessThanExpr = BinaryOperator::Create(
2996a9ac8606Spatrick         *Context, sizeofExpr, limit, BO_LE, Context->IntTy, VK_PRValue,
2997ec727ea7Spatrick         OK_Ordinary, SourceLocation(), FPOptionsOverride());
2998e5dd7070Spatrick     // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2999a9ac8606Spatrick     ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
3000a9ac8606Spatrick         lessThanExpr, SourceLocation(), CE, SourceLocation(), STCE, returnType,
3001a9ac8606Spatrick         VK_PRValue, OK_Ordinary);
3002e5dd7070Spatrick     ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3003e5dd7070Spatrick                                             CondExpr);
3004e5dd7070Spatrick   }
3005e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3006e5dd7070Spatrick   return ReplacingStmt;
3007e5dd7070Spatrick }
3008e5dd7070Spatrick 
RewriteMessageExpr(ObjCMessageExpr * Exp)3009e5dd7070Spatrick Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3010e5dd7070Spatrick   Stmt *ReplacingStmt =
3011e5dd7070Spatrick       SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3012e5dd7070Spatrick 
3013e5dd7070Spatrick   // Now do the actual rewrite.
3014e5dd7070Spatrick   ReplaceStmt(Exp, ReplacingStmt);
3015e5dd7070Spatrick 
3016e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3017e5dd7070Spatrick   return ReplacingStmt;
3018e5dd7070Spatrick }
3019e5dd7070Spatrick 
3020e5dd7070Spatrick // typedef struct objc_object Protocol;
getProtocolType()3021e5dd7070Spatrick QualType RewriteObjC::getProtocolType() {
3022e5dd7070Spatrick   if (!ProtocolTypeDecl) {
3023e5dd7070Spatrick     TypeSourceInfo *TInfo
3024e5dd7070Spatrick       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3025e5dd7070Spatrick     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3026e5dd7070Spatrick                                            SourceLocation(), SourceLocation(),
3027e5dd7070Spatrick                                            &Context->Idents.get("Protocol"),
3028e5dd7070Spatrick                                            TInfo);
3029e5dd7070Spatrick   }
3030e5dd7070Spatrick   return Context->getTypeDeclType(ProtocolTypeDecl);
3031e5dd7070Spatrick }
3032e5dd7070Spatrick 
3033e5dd7070Spatrick /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3034e5dd7070Spatrick /// a synthesized/forward data reference (to the protocol's metadata).
3035e5dd7070Spatrick /// The forward references (and metadata) are generated in
3036e5dd7070Spatrick /// RewriteObjC::HandleTranslationUnit().
RewriteObjCProtocolExpr(ObjCProtocolExpr * Exp)3037e5dd7070Spatrick Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3038e5dd7070Spatrick   std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3039e5dd7070Spatrick   IdentifierInfo *ID = &Context->Idents.get(Name);
3040e5dd7070Spatrick   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3041e5dd7070Spatrick                                 SourceLocation(), ID, getProtocolType(),
3042e5dd7070Spatrick                                 nullptr, SC_Extern);
3043e5dd7070Spatrick   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3044e5dd7070Spatrick       *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3045ec727ea7Spatrick   Expr *DerefExpr = UnaryOperator::Create(
3046ec727ea7Spatrick       const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
3047a9ac8606Spatrick       Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
3048ec727ea7Spatrick       SourceLocation(), false, FPOptionsOverride());
3049e5dd7070Spatrick   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3050e5dd7070Spatrick                                                 CK_BitCast,
3051e5dd7070Spatrick                                                 DerefExpr);
3052e5dd7070Spatrick   ReplaceStmt(Exp, castExpr);
3053e5dd7070Spatrick   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3054e5dd7070Spatrick   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3055e5dd7070Spatrick   return castExpr;
3056e5dd7070Spatrick }
3057e5dd7070Spatrick 
BufferContainsPPDirectives(const char * startBuf,const char * endBuf)3058e5dd7070Spatrick bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3059e5dd7070Spatrick                                              const char *endBuf) {
3060e5dd7070Spatrick   while (startBuf < endBuf) {
3061e5dd7070Spatrick     if (*startBuf == '#') {
3062e5dd7070Spatrick       // Skip whitespace.
3063e5dd7070Spatrick       for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3064e5dd7070Spatrick         ;
3065e5dd7070Spatrick       if (!strncmp(startBuf, "if", strlen("if")) ||
3066e5dd7070Spatrick           !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3067e5dd7070Spatrick           !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3068e5dd7070Spatrick           !strncmp(startBuf, "define", strlen("define")) ||
3069e5dd7070Spatrick           !strncmp(startBuf, "undef", strlen("undef")) ||
3070e5dd7070Spatrick           !strncmp(startBuf, "else", strlen("else")) ||
3071e5dd7070Spatrick           !strncmp(startBuf, "elif", strlen("elif")) ||
3072e5dd7070Spatrick           !strncmp(startBuf, "endif", strlen("endif")) ||
3073e5dd7070Spatrick           !strncmp(startBuf, "pragma", strlen("pragma")) ||
3074e5dd7070Spatrick           !strncmp(startBuf, "include", strlen("include")) ||
3075e5dd7070Spatrick           !strncmp(startBuf, "import", strlen("import")) ||
3076e5dd7070Spatrick           !strncmp(startBuf, "include_next", strlen("include_next")))
3077e5dd7070Spatrick         return true;
3078e5dd7070Spatrick     }
3079e5dd7070Spatrick     startBuf++;
3080e5dd7070Spatrick   }
3081e5dd7070Spatrick   return false;
3082e5dd7070Spatrick }
3083e5dd7070Spatrick 
3084e5dd7070Spatrick /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3085e5dd7070Spatrick /// an objective-c class with ivars.
RewriteObjCInternalStruct(ObjCInterfaceDecl * CDecl,std::string & Result)3086e5dd7070Spatrick void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3087e5dd7070Spatrick                                                std::string &Result) {
3088e5dd7070Spatrick   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3089e5dd7070Spatrick   assert(CDecl->getName() != "" &&
3090e5dd7070Spatrick          "Name missing in SynthesizeObjCInternalStruct");
3091e5dd7070Spatrick   // Do not synthesize more than once.
3092e5dd7070Spatrick   if (ObjCSynthesizedStructs.count(CDecl))
3093e5dd7070Spatrick     return;
3094e5dd7070Spatrick   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3095e5dd7070Spatrick   int NumIvars = CDecl->ivar_size();
3096e5dd7070Spatrick   SourceLocation LocStart = CDecl->getBeginLoc();
3097e5dd7070Spatrick   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3098e5dd7070Spatrick 
3099e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(LocStart);
3100e5dd7070Spatrick   const char *endBuf = SM->getCharacterData(LocEnd);
3101e5dd7070Spatrick 
3102e5dd7070Spatrick   // If no ivars and no root or if its root, directly or indirectly,
3103e5dd7070Spatrick   // have no ivars (thus not synthesized) then no need to synthesize this class.
3104e5dd7070Spatrick   if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3105e5dd7070Spatrick       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3106e5dd7070Spatrick     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3107e5dd7070Spatrick     ReplaceText(LocStart, endBuf-startBuf, Result);
3108e5dd7070Spatrick     return;
3109e5dd7070Spatrick   }
3110e5dd7070Spatrick 
3111e5dd7070Spatrick   // FIXME: This has potential of causing problem. If
3112e5dd7070Spatrick   // SynthesizeObjCInternalStruct is ever called recursively.
3113e5dd7070Spatrick   Result += "\nstruct ";
3114e5dd7070Spatrick   Result += CDecl->getNameAsString();
3115e5dd7070Spatrick   if (LangOpts.MicrosoftExt)
3116e5dd7070Spatrick     Result += "_IMPL";
3117e5dd7070Spatrick 
3118e5dd7070Spatrick   if (NumIvars > 0) {
3119e5dd7070Spatrick     const char *cursor = strchr(startBuf, '{');
3120e5dd7070Spatrick     assert((cursor && endBuf)
3121e5dd7070Spatrick            && "SynthesizeObjCInternalStruct - malformed @interface");
3122e5dd7070Spatrick     // If the buffer contains preprocessor directives, we do more fine-grained
3123e5dd7070Spatrick     // rewrites. This is intended to fix code that looks like (which occurs in
3124e5dd7070Spatrick     // NSURL.h, for example):
3125e5dd7070Spatrick     //
3126e5dd7070Spatrick     // #ifdef XYZ
3127e5dd7070Spatrick     // @interface Foo : NSObject
3128e5dd7070Spatrick     // #else
3129e5dd7070Spatrick     // @interface FooBar : NSObject
3130e5dd7070Spatrick     // #endif
3131e5dd7070Spatrick     // {
3132e5dd7070Spatrick     //    int i;
3133e5dd7070Spatrick     // }
3134e5dd7070Spatrick     // @end
3135e5dd7070Spatrick     //
3136e5dd7070Spatrick     // This clause is segregated to avoid breaking the common case.
3137e5dd7070Spatrick     if (BufferContainsPPDirectives(startBuf, cursor)) {
3138e5dd7070Spatrick       SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3139e5dd7070Spatrick                                   CDecl->getAtStartLoc();
3140e5dd7070Spatrick       const char *endHeader = SM->getCharacterData(L);
3141e5dd7070Spatrick       endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3142e5dd7070Spatrick 
3143e5dd7070Spatrick       if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3144e5dd7070Spatrick         // advance to the end of the referenced protocols.
3145e5dd7070Spatrick         while (endHeader < cursor && *endHeader != '>') endHeader++;
3146e5dd7070Spatrick         endHeader++;
3147e5dd7070Spatrick       }
3148e5dd7070Spatrick       // rewrite the original header
3149e5dd7070Spatrick       ReplaceText(LocStart, endHeader-startBuf, Result);
3150e5dd7070Spatrick     } else {
3151e5dd7070Spatrick       // rewrite the original header *without* disturbing the '{'
3152e5dd7070Spatrick       ReplaceText(LocStart, cursor-startBuf, Result);
3153e5dd7070Spatrick     }
3154e5dd7070Spatrick     if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3155e5dd7070Spatrick       Result = "\n    struct ";
3156e5dd7070Spatrick       Result += RCDecl->getNameAsString();
3157e5dd7070Spatrick       Result += "_IMPL ";
3158e5dd7070Spatrick       Result += RCDecl->getNameAsString();
3159e5dd7070Spatrick       Result += "_IVARS;\n";
3160e5dd7070Spatrick 
3161e5dd7070Spatrick       // insert the super class structure definition.
3162e5dd7070Spatrick       SourceLocation OnePastCurly =
3163e5dd7070Spatrick         LocStart.getLocWithOffset(cursor-startBuf+1);
3164e5dd7070Spatrick       InsertText(OnePastCurly, Result);
3165e5dd7070Spatrick     }
3166e5dd7070Spatrick     cursor++; // past '{'
3167e5dd7070Spatrick 
3168e5dd7070Spatrick     // Now comment out any visibility specifiers.
3169e5dd7070Spatrick     while (cursor < endBuf) {
3170e5dd7070Spatrick       if (*cursor == '@') {
3171e5dd7070Spatrick         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3172e5dd7070Spatrick         // Skip whitespace.
3173e5dd7070Spatrick         for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3174e5dd7070Spatrick           /*scan*/;
3175e5dd7070Spatrick 
3176e5dd7070Spatrick         // FIXME: presence of @public, etc. inside comment results in
3177e5dd7070Spatrick         // this transformation as well, which is still correct c-code.
3178e5dd7070Spatrick         if (!strncmp(cursor, "public", strlen("public")) ||
3179e5dd7070Spatrick             !strncmp(cursor, "private", strlen("private")) ||
3180e5dd7070Spatrick             !strncmp(cursor, "package", strlen("package")) ||
3181e5dd7070Spatrick             !strncmp(cursor, "protected", strlen("protected")))
3182e5dd7070Spatrick           InsertText(atLoc, "// ");
3183e5dd7070Spatrick       }
3184e5dd7070Spatrick       // FIXME: If there are cases where '<' is used in ivar declaration part
3185e5dd7070Spatrick       // of user code, then scan the ivar list and use needToScanForQualifiers
3186e5dd7070Spatrick       // for type checking.
3187e5dd7070Spatrick       else if (*cursor == '<') {
3188e5dd7070Spatrick         SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3189e5dd7070Spatrick         InsertText(atLoc, "/* ");
3190e5dd7070Spatrick         cursor = strchr(cursor, '>');
3191e5dd7070Spatrick         cursor++;
3192e5dd7070Spatrick         atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3193e5dd7070Spatrick         InsertText(atLoc, " */");
3194e5dd7070Spatrick       } else if (*cursor == '^') { // rewrite block specifier.
3195e5dd7070Spatrick         SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3196e5dd7070Spatrick         ReplaceText(caretLoc, 1, "*");
3197e5dd7070Spatrick       }
3198e5dd7070Spatrick       cursor++;
3199e5dd7070Spatrick     }
3200e5dd7070Spatrick     // Don't forget to add a ';'!!
3201e5dd7070Spatrick     InsertText(LocEnd.getLocWithOffset(1), ";");
3202e5dd7070Spatrick   } else { // we don't have any instance variables - insert super struct.
3203e5dd7070Spatrick     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3204e5dd7070Spatrick     Result += " {\n    struct ";
3205e5dd7070Spatrick     Result += RCDecl->getNameAsString();
3206e5dd7070Spatrick     Result += "_IMPL ";
3207e5dd7070Spatrick     Result += RCDecl->getNameAsString();
3208e5dd7070Spatrick     Result += "_IVARS;\n};\n";
3209e5dd7070Spatrick     ReplaceText(LocStart, endBuf-startBuf, Result);
3210e5dd7070Spatrick   }
3211e5dd7070Spatrick   // Mark this struct as having been generated.
3212e5dd7070Spatrick   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3213e5dd7070Spatrick     llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3214e5dd7070Spatrick }
3215e5dd7070Spatrick 
3216e5dd7070Spatrick //===----------------------------------------------------------------------===//
3217e5dd7070Spatrick // Meta Data Emission
3218e5dd7070Spatrick //===----------------------------------------------------------------------===//
3219e5dd7070Spatrick 
3220e5dd7070Spatrick /// RewriteImplementations - This routine rewrites all method implementations
3221e5dd7070Spatrick /// and emits meta-data.
3222e5dd7070Spatrick 
RewriteImplementations()3223e5dd7070Spatrick void RewriteObjC::RewriteImplementations() {
3224e5dd7070Spatrick   int ClsDefCount = ClassImplementation.size();
3225e5dd7070Spatrick   int CatDefCount = CategoryImplementation.size();
3226e5dd7070Spatrick 
3227e5dd7070Spatrick   // Rewrite implemented methods
3228e5dd7070Spatrick   for (int i = 0; i < ClsDefCount; i++)
3229e5dd7070Spatrick     RewriteImplementationDecl(ClassImplementation[i]);
3230e5dd7070Spatrick 
3231e5dd7070Spatrick   for (int i = 0; i < CatDefCount; i++)
3232e5dd7070Spatrick     RewriteImplementationDecl(CategoryImplementation[i]);
3233e5dd7070Spatrick }
3234e5dd7070Spatrick 
RewriteByRefString(std::string & ResultStr,const std::string & Name,ValueDecl * VD,bool def)3235e5dd7070Spatrick void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3236e5dd7070Spatrick                                      const std::string &Name,
3237e5dd7070Spatrick                                      ValueDecl *VD, bool def) {
3238e5dd7070Spatrick   assert(BlockByRefDeclNo.count(VD) &&
3239e5dd7070Spatrick          "RewriteByRefString: ByRef decl missing");
3240e5dd7070Spatrick   if (def)
3241e5dd7070Spatrick     ResultStr += "struct ";
3242e5dd7070Spatrick   ResultStr += "__Block_byref_" + Name +
3243e5dd7070Spatrick     "_" + utostr(BlockByRefDeclNo[VD]) ;
3244e5dd7070Spatrick }
3245e5dd7070Spatrick 
HasLocalVariableExternalStorage(ValueDecl * VD)3246e5dd7070Spatrick static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3247e5dd7070Spatrick   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3248e5dd7070Spatrick     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3249e5dd7070Spatrick   return false;
3250e5dd7070Spatrick }
3251e5dd7070Spatrick 
SynthesizeBlockFunc(BlockExpr * CE,int i,StringRef funcName,std::string Tag)3252e5dd7070Spatrick std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3253e5dd7070Spatrick                                                    StringRef funcName,
3254e5dd7070Spatrick                                                    std::string Tag) {
3255e5dd7070Spatrick   const FunctionType *AFT = CE->getFunctionType();
3256e5dd7070Spatrick   QualType RT = AFT->getReturnType();
3257e5dd7070Spatrick   std::string StructRef = "struct " + Tag;
3258e5dd7070Spatrick   std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3259e5dd7070Spatrick                   funcName.str() + "_" + "block_func_" + utostr(i);
3260e5dd7070Spatrick 
3261e5dd7070Spatrick   BlockDecl *BD = CE->getBlockDecl();
3262e5dd7070Spatrick 
3263e5dd7070Spatrick   if (isa<FunctionNoProtoType>(AFT)) {
3264e5dd7070Spatrick     // No user-supplied arguments. Still need to pass in a pointer to the
3265e5dd7070Spatrick     // block (to reference imported block decl refs).
3266e5dd7070Spatrick     S += "(" + StructRef + " *__cself)";
3267e5dd7070Spatrick   } else if (BD->param_empty()) {
3268e5dd7070Spatrick     S += "(" + StructRef + " *__cself)";
3269e5dd7070Spatrick   } else {
3270e5dd7070Spatrick     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3271e5dd7070Spatrick     assert(FT && "SynthesizeBlockFunc: No function proto");
3272e5dd7070Spatrick     S += '(';
3273e5dd7070Spatrick     // first add the implicit argument.
3274e5dd7070Spatrick     S += StructRef + " *__cself, ";
3275e5dd7070Spatrick     std::string ParamStr;
3276e5dd7070Spatrick     for (BlockDecl::param_iterator AI = BD->param_begin(),
3277e5dd7070Spatrick          E = BD->param_end(); AI != E; ++AI) {
3278e5dd7070Spatrick       if (AI != BD->param_begin()) S += ", ";
3279e5dd7070Spatrick       ParamStr = (*AI)->getNameAsString();
3280e5dd7070Spatrick       QualType QT = (*AI)->getType();
3281e5dd7070Spatrick       (void)convertBlockPointerToFunctionPointer(QT);
3282e5dd7070Spatrick       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3283e5dd7070Spatrick       S += ParamStr;
3284e5dd7070Spatrick     }
3285e5dd7070Spatrick     if (FT->isVariadic()) {
3286e5dd7070Spatrick       if (!BD->param_empty()) S += ", ";
3287e5dd7070Spatrick       S += "...";
3288e5dd7070Spatrick     }
3289e5dd7070Spatrick     S += ')';
3290e5dd7070Spatrick   }
3291e5dd7070Spatrick   S += " {\n";
3292e5dd7070Spatrick 
3293e5dd7070Spatrick   // Create local declarations to avoid rewriting all closure decl ref exprs.
3294e5dd7070Spatrick   // First, emit a declaration for all "by ref" decls.
3295e5dd7070Spatrick   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3296e5dd7070Spatrick        E = BlockByRefDecls.end(); I != E; ++I) {
3297e5dd7070Spatrick     S += "  ";
3298e5dd7070Spatrick     std::string Name = (*I)->getNameAsString();
3299e5dd7070Spatrick     std::string TypeString;
3300e5dd7070Spatrick     RewriteByRefString(TypeString, Name, (*I));
3301e5dd7070Spatrick     TypeString += " *";
3302e5dd7070Spatrick     Name = TypeString + Name;
3303e5dd7070Spatrick     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3304e5dd7070Spatrick   }
3305e5dd7070Spatrick   // Next, emit a declaration for all "by copy" declarations.
3306e5dd7070Spatrick   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3307e5dd7070Spatrick        E = BlockByCopyDecls.end(); I != E; ++I) {
3308e5dd7070Spatrick     S += "  ";
3309e5dd7070Spatrick     // Handle nested closure invocation. For example:
3310e5dd7070Spatrick     //
3311e5dd7070Spatrick     //   void (^myImportedClosure)(void);
3312e5dd7070Spatrick     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3313e5dd7070Spatrick     //
3314e5dd7070Spatrick     //   void (^anotherClosure)(void);
3315e5dd7070Spatrick     //   anotherClosure = ^(void) {
3316e5dd7070Spatrick     //     myImportedClosure(); // import and invoke the closure
3317e5dd7070Spatrick     //   };
3318e5dd7070Spatrick     //
3319e5dd7070Spatrick     if (isTopLevelBlockPointerType((*I)->getType())) {
3320e5dd7070Spatrick       RewriteBlockPointerTypeVariable(S, (*I));
3321e5dd7070Spatrick       S += " = (";
3322e5dd7070Spatrick       RewriteBlockPointerType(S, (*I)->getType());
3323e5dd7070Spatrick       S += ")";
3324e5dd7070Spatrick       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3325e5dd7070Spatrick     }
3326e5dd7070Spatrick     else {
3327e5dd7070Spatrick       std::string Name = (*I)->getNameAsString();
3328e5dd7070Spatrick       QualType QT = (*I)->getType();
3329e5dd7070Spatrick       if (HasLocalVariableExternalStorage(*I))
3330e5dd7070Spatrick         QT = Context->getPointerType(QT);
3331e5dd7070Spatrick       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3332e5dd7070Spatrick       S += Name + " = __cself->" +
3333e5dd7070Spatrick                               (*I)->getNameAsString() + "; // bound by copy\n";
3334e5dd7070Spatrick     }
3335e5dd7070Spatrick   }
3336e5dd7070Spatrick   std::string RewrittenStr = RewrittenBlockExprs[CE];
3337e5dd7070Spatrick   const char *cstr = RewrittenStr.c_str();
3338e5dd7070Spatrick   while (*cstr++ != '{') ;
3339e5dd7070Spatrick   S += cstr;
3340e5dd7070Spatrick   S += "\n";
3341e5dd7070Spatrick   return S;
3342e5dd7070Spatrick }
3343e5dd7070Spatrick 
SynthesizeBlockHelperFuncs(BlockExpr * CE,int i,StringRef funcName,std::string Tag)3344e5dd7070Spatrick std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3345e5dd7070Spatrick                                                    StringRef funcName,
3346e5dd7070Spatrick                                                    std::string Tag) {
3347e5dd7070Spatrick   std::string StructRef = "struct " + Tag;
3348e5dd7070Spatrick   std::string S = "static void __";
3349e5dd7070Spatrick 
3350e5dd7070Spatrick   S += funcName;
3351e5dd7070Spatrick   S += "_block_copy_" + utostr(i);
3352e5dd7070Spatrick   S += "(" + StructRef;
3353e5dd7070Spatrick   S += "*dst, " + StructRef;
3354e5dd7070Spatrick   S += "*src) {";
3355e5dd7070Spatrick   for (ValueDecl *VD : ImportedBlockDecls) {
3356e5dd7070Spatrick     S += "_Block_object_assign((void*)&dst->";
3357e5dd7070Spatrick     S += VD->getNameAsString();
3358e5dd7070Spatrick     S += ", (void*)src->";
3359e5dd7070Spatrick     S += VD->getNameAsString();
3360e5dd7070Spatrick     if (BlockByRefDeclsPtrSet.count(VD))
3361e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3362e5dd7070Spatrick     else if (VD->getType()->isBlockPointerType())
3363e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3364e5dd7070Spatrick     else
3365e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3366e5dd7070Spatrick   }
3367e5dd7070Spatrick   S += "}\n";
3368e5dd7070Spatrick 
3369e5dd7070Spatrick   S += "\nstatic void __";
3370e5dd7070Spatrick   S += funcName;
3371e5dd7070Spatrick   S += "_block_dispose_" + utostr(i);
3372e5dd7070Spatrick   S += "(" + StructRef;
3373e5dd7070Spatrick   S += "*src) {";
3374e5dd7070Spatrick   for (ValueDecl *VD : ImportedBlockDecls) {
3375e5dd7070Spatrick     S += "_Block_object_dispose((void*)src->";
3376e5dd7070Spatrick     S += VD->getNameAsString();
3377e5dd7070Spatrick     if (BlockByRefDeclsPtrSet.count(VD))
3378e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3379e5dd7070Spatrick     else if (VD->getType()->isBlockPointerType())
3380e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3381e5dd7070Spatrick     else
3382e5dd7070Spatrick       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3383e5dd7070Spatrick   }
3384e5dd7070Spatrick   S += "}\n";
3385e5dd7070Spatrick   return S;
3386e5dd7070Spatrick }
3387e5dd7070Spatrick 
SynthesizeBlockImpl(BlockExpr * CE,std::string Tag,std::string Desc)3388e5dd7070Spatrick std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3389e5dd7070Spatrick                                              std::string Desc) {
3390e5dd7070Spatrick   std::string S = "\nstruct " + Tag;
3391e5dd7070Spatrick   std::string Constructor = "  " + Tag;
3392e5dd7070Spatrick 
3393e5dd7070Spatrick   S += " {\n  struct __block_impl impl;\n";
3394e5dd7070Spatrick   S += "  struct " + Desc;
3395e5dd7070Spatrick   S += "* Desc;\n";
3396e5dd7070Spatrick 
3397e5dd7070Spatrick   Constructor += "(void *fp, "; // Invoke function pointer.
3398e5dd7070Spatrick   Constructor += "struct " + Desc; // Descriptor pointer.
3399e5dd7070Spatrick   Constructor += " *desc";
3400e5dd7070Spatrick 
3401e5dd7070Spatrick   if (BlockDeclRefs.size()) {
3402e5dd7070Spatrick     // Output all "by copy" declarations.
3403e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3404e5dd7070Spatrick          E = BlockByCopyDecls.end(); I != E; ++I) {
3405e5dd7070Spatrick       S += "  ";
3406e5dd7070Spatrick       std::string FieldName = (*I)->getNameAsString();
3407e5dd7070Spatrick       std::string ArgName = "_" + FieldName;
3408e5dd7070Spatrick       // Handle nested closure invocation. For example:
3409e5dd7070Spatrick       //
3410e5dd7070Spatrick       //   void (^myImportedBlock)(void);
3411e5dd7070Spatrick       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3412e5dd7070Spatrick       //
3413e5dd7070Spatrick       //   void (^anotherBlock)(void);
3414e5dd7070Spatrick       //   anotherBlock = ^(void) {
3415e5dd7070Spatrick       //     myImportedBlock(); // import and invoke the closure
3416e5dd7070Spatrick       //   };
3417e5dd7070Spatrick       //
3418e5dd7070Spatrick       if (isTopLevelBlockPointerType((*I)->getType())) {
3419e5dd7070Spatrick         S += "struct __block_impl *";
3420e5dd7070Spatrick         Constructor += ", void *" + ArgName;
3421e5dd7070Spatrick       } else {
3422e5dd7070Spatrick         QualType QT = (*I)->getType();
3423e5dd7070Spatrick         if (HasLocalVariableExternalStorage(*I))
3424e5dd7070Spatrick           QT = Context->getPointerType(QT);
3425e5dd7070Spatrick         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3426e5dd7070Spatrick         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3427e5dd7070Spatrick         Constructor += ", " + ArgName;
3428e5dd7070Spatrick       }
3429e5dd7070Spatrick       S += FieldName + ";\n";
3430e5dd7070Spatrick     }
3431e5dd7070Spatrick     // Output all "by ref" declarations.
3432e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3433e5dd7070Spatrick          E = BlockByRefDecls.end(); I != E; ++I) {
3434e5dd7070Spatrick       S += "  ";
3435e5dd7070Spatrick       std::string FieldName = (*I)->getNameAsString();
3436e5dd7070Spatrick       std::string ArgName = "_" + FieldName;
3437e5dd7070Spatrick       {
3438e5dd7070Spatrick         std::string TypeString;
3439e5dd7070Spatrick         RewriteByRefString(TypeString, FieldName, (*I));
3440e5dd7070Spatrick         TypeString += " *";
3441e5dd7070Spatrick         FieldName = TypeString + FieldName;
3442e5dd7070Spatrick         ArgName = TypeString + ArgName;
3443e5dd7070Spatrick         Constructor += ", " + ArgName;
3444e5dd7070Spatrick       }
3445e5dd7070Spatrick       S += FieldName + "; // by ref\n";
3446e5dd7070Spatrick     }
3447e5dd7070Spatrick     // Finish writing the constructor.
3448e5dd7070Spatrick     Constructor += ", int flags=0)";
3449e5dd7070Spatrick     // Initialize all "by copy" arguments.
3450e5dd7070Spatrick     bool firsTime = true;
3451e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3452e5dd7070Spatrick          E = BlockByCopyDecls.end(); I != E; ++I) {
3453e5dd7070Spatrick       std::string Name = (*I)->getNameAsString();
3454e5dd7070Spatrick         if (firsTime) {
3455e5dd7070Spatrick           Constructor += " : ";
3456e5dd7070Spatrick           firsTime = false;
3457e5dd7070Spatrick         }
3458e5dd7070Spatrick         else
3459e5dd7070Spatrick           Constructor += ", ";
3460e5dd7070Spatrick         if (isTopLevelBlockPointerType((*I)->getType()))
3461e5dd7070Spatrick           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3462e5dd7070Spatrick         else
3463e5dd7070Spatrick           Constructor += Name + "(_" + Name + ")";
3464e5dd7070Spatrick     }
3465e5dd7070Spatrick     // Initialize all "by ref" arguments.
3466e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3467e5dd7070Spatrick          E = BlockByRefDecls.end(); I != E; ++I) {
3468e5dd7070Spatrick       std::string Name = (*I)->getNameAsString();
3469e5dd7070Spatrick       if (firsTime) {
3470e5dd7070Spatrick         Constructor += " : ";
3471e5dd7070Spatrick         firsTime = false;
3472e5dd7070Spatrick       }
3473e5dd7070Spatrick       else
3474e5dd7070Spatrick         Constructor += ", ";
3475e5dd7070Spatrick       Constructor += Name + "(_" + Name + "->__forwarding)";
3476e5dd7070Spatrick     }
3477e5dd7070Spatrick 
3478e5dd7070Spatrick     Constructor += " {\n";
3479e5dd7070Spatrick     if (GlobalVarDecl)
3480e5dd7070Spatrick       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3481e5dd7070Spatrick     else
3482e5dd7070Spatrick       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3483e5dd7070Spatrick     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3484e5dd7070Spatrick 
3485e5dd7070Spatrick     Constructor += "    Desc = desc;\n";
3486e5dd7070Spatrick   } else {
3487e5dd7070Spatrick     // Finish writing the constructor.
3488e5dd7070Spatrick     Constructor += ", int flags=0) {\n";
3489e5dd7070Spatrick     if (GlobalVarDecl)
3490e5dd7070Spatrick       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3491e5dd7070Spatrick     else
3492e5dd7070Spatrick       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3493e5dd7070Spatrick     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3494e5dd7070Spatrick     Constructor += "    Desc = desc;\n";
3495e5dd7070Spatrick   }
3496e5dd7070Spatrick   Constructor += "  ";
3497e5dd7070Spatrick   Constructor += "}\n";
3498e5dd7070Spatrick   S += Constructor;
3499e5dd7070Spatrick   S += "};\n";
3500e5dd7070Spatrick   return S;
3501e5dd7070Spatrick }
3502e5dd7070Spatrick 
SynthesizeBlockDescriptor(std::string DescTag,std::string ImplTag,int i,StringRef FunName,unsigned hasCopy)3503e5dd7070Spatrick std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3504e5dd7070Spatrick                                                    std::string ImplTag, int i,
3505e5dd7070Spatrick                                                    StringRef FunName,
3506e5dd7070Spatrick                                                    unsigned hasCopy) {
3507e5dd7070Spatrick   std::string S = "\nstatic struct " + DescTag;
3508e5dd7070Spatrick 
3509e5dd7070Spatrick   S += " {\n  unsigned long reserved;\n";
3510e5dd7070Spatrick   S += "  unsigned long Block_size;\n";
3511e5dd7070Spatrick   if (hasCopy) {
3512e5dd7070Spatrick     S += "  void (*copy)(struct ";
3513e5dd7070Spatrick     S += ImplTag; S += "*, struct ";
3514e5dd7070Spatrick     S += ImplTag; S += "*);\n";
3515e5dd7070Spatrick 
3516e5dd7070Spatrick     S += "  void (*dispose)(struct ";
3517e5dd7070Spatrick     S += ImplTag; S += "*);\n";
3518e5dd7070Spatrick   }
3519e5dd7070Spatrick   S += "} ";
3520e5dd7070Spatrick 
3521e5dd7070Spatrick   S += DescTag + "_DATA = { 0, sizeof(struct ";
3522e5dd7070Spatrick   S += ImplTag + ")";
3523e5dd7070Spatrick   if (hasCopy) {
3524e5dd7070Spatrick     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3525e5dd7070Spatrick     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3526e5dd7070Spatrick   }
3527e5dd7070Spatrick   S += "};\n";
3528e5dd7070Spatrick   return S;
3529e5dd7070Spatrick }
3530e5dd7070Spatrick 
SynthesizeBlockLiterals(SourceLocation FunLocStart,StringRef FunName)3531e5dd7070Spatrick void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3532e5dd7070Spatrick                                           StringRef FunName) {
3533e5dd7070Spatrick   // Insert declaration for the function in which block literal is used.
3534e5dd7070Spatrick   if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3535e5dd7070Spatrick     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3536e5dd7070Spatrick   bool RewriteSC = (GlobalVarDecl &&
3537e5dd7070Spatrick                     !Blocks.empty() &&
3538e5dd7070Spatrick                     GlobalVarDecl->getStorageClass() == SC_Static &&
3539e5dd7070Spatrick                     GlobalVarDecl->getType().getCVRQualifiers());
3540e5dd7070Spatrick   if (RewriteSC) {
3541e5dd7070Spatrick     std::string SC(" void __");
3542e5dd7070Spatrick     SC += GlobalVarDecl->getNameAsString();
3543e5dd7070Spatrick     SC += "() {}";
3544e5dd7070Spatrick     InsertText(FunLocStart, SC);
3545e5dd7070Spatrick   }
3546e5dd7070Spatrick 
3547e5dd7070Spatrick   // Insert closures that were part of the function.
3548e5dd7070Spatrick   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3549e5dd7070Spatrick     CollectBlockDeclRefInfo(Blocks[i]);
3550e5dd7070Spatrick     // Need to copy-in the inner copied-in variables not actually used in this
3551e5dd7070Spatrick     // block.
3552e5dd7070Spatrick     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3553e5dd7070Spatrick       DeclRefExpr *Exp = InnerDeclRefs[count++];
3554e5dd7070Spatrick       ValueDecl *VD = Exp->getDecl();
3555e5dd7070Spatrick       BlockDeclRefs.push_back(Exp);
3556e5dd7070Spatrick       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3557e5dd7070Spatrick         BlockByCopyDeclsPtrSet.insert(VD);
3558e5dd7070Spatrick         BlockByCopyDecls.push_back(VD);
3559e5dd7070Spatrick       }
3560e5dd7070Spatrick       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3561e5dd7070Spatrick         BlockByRefDeclsPtrSet.insert(VD);
3562e5dd7070Spatrick         BlockByRefDecls.push_back(VD);
3563e5dd7070Spatrick       }
3564e5dd7070Spatrick       // imported objects in the inner blocks not used in the outer
3565e5dd7070Spatrick       // blocks must be copied/disposed in the outer block as well.
3566e5dd7070Spatrick       if (VD->hasAttr<BlocksAttr>() ||
3567e5dd7070Spatrick           VD->getType()->isObjCObjectPointerType() ||
3568e5dd7070Spatrick           VD->getType()->isBlockPointerType())
3569e5dd7070Spatrick         ImportedBlockDecls.insert(VD);
3570e5dd7070Spatrick     }
3571e5dd7070Spatrick 
3572e5dd7070Spatrick     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3573e5dd7070Spatrick     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3574e5dd7070Spatrick 
3575e5dd7070Spatrick     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3576e5dd7070Spatrick 
3577e5dd7070Spatrick     InsertText(FunLocStart, CI);
3578e5dd7070Spatrick 
3579e5dd7070Spatrick     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3580e5dd7070Spatrick 
3581e5dd7070Spatrick     InsertText(FunLocStart, CF);
3582e5dd7070Spatrick 
3583e5dd7070Spatrick     if (ImportedBlockDecls.size()) {
3584e5dd7070Spatrick       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3585e5dd7070Spatrick       InsertText(FunLocStart, HF);
3586e5dd7070Spatrick     }
3587e5dd7070Spatrick     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3588e5dd7070Spatrick                                                ImportedBlockDecls.size() > 0);
3589e5dd7070Spatrick     InsertText(FunLocStart, BD);
3590e5dd7070Spatrick 
3591e5dd7070Spatrick     BlockDeclRefs.clear();
3592e5dd7070Spatrick     BlockByRefDecls.clear();
3593e5dd7070Spatrick     BlockByRefDeclsPtrSet.clear();
3594e5dd7070Spatrick     BlockByCopyDecls.clear();
3595e5dd7070Spatrick     BlockByCopyDeclsPtrSet.clear();
3596e5dd7070Spatrick     ImportedBlockDecls.clear();
3597e5dd7070Spatrick   }
3598e5dd7070Spatrick   if (RewriteSC) {
3599e5dd7070Spatrick     // Must insert any 'const/volatile/static here. Since it has been
3600e5dd7070Spatrick     // removed as result of rewriting of block literals.
3601e5dd7070Spatrick     std::string SC;
3602e5dd7070Spatrick     if (GlobalVarDecl->getStorageClass() == SC_Static)
3603e5dd7070Spatrick       SC = "static ";
3604e5dd7070Spatrick     if (GlobalVarDecl->getType().isConstQualified())
3605e5dd7070Spatrick       SC += "const ";
3606e5dd7070Spatrick     if (GlobalVarDecl->getType().isVolatileQualified())
3607e5dd7070Spatrick       SC += "volatile ";
3608e5dd7070Spatrick     if (GlobalVarDecl->getType().isRestrictQualified())
3609e5dd7070Spatrick       SC += "restrict ";
3610e5dd7070Spatrick     InsertText(FunLocStart, SC);
3611e5dd7070Spatrick   }
3612e5dd7070Spatrick 
3613e5dd7070Spatrick   Blocks.clear();
3614e5dd7070Spatrick   InnerDeclRefsCount.clear();
3615e5dd7070Spatrick   InnerDeclRefs.clear();
3616e5dd7070Spatrick   RewrittenBlockExprs.clear();
3617e5dd7070Spatrick }
3618e5dd7070Spatrick 
InsertBlockLiteralsWithinFunction(FunctionDecl * FD)3619e5dd7070Spatrick void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3620e5dd7070Spatrick   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3621e5dd7070Spatrick   StringRef FuncName = FD->getName();
3622e5dd7070Spatrick 
3623e5dd7070Spatrick   SynthesizeBlockLiterals(FunLocStart, FuncName);
3624e5dd7070Spatrick }
3625e5dd7070Spatrick 
BuildUniqueMethodName(std::string & Name,ObjCMethodDecl * MD)3626e5dd7070Spatrick static void BuildUniqueMethodName(std::string &Name,
3627e5dd7070Spatrick                                   ObjCMethodDecl *MD) {
3628e5dd7070Spatrick   ObjCInterfaceDecl *IFace = MD->getClassInterface();
3629ec727ea7Spatrick   Name = std::string(IFace->getName());
3630e5dd7070Spatrick   Name += "__" + MD->getSelector().getAsString();
3631e5dd7070Spatrick   // Convert colons to underscores.
3632e5dd7070Spatrick   std::string::size_type loc = 0;
3633e5dd7070Spatrick   while ((loc = Name.find(':', loc)) != std::string::npos)
3634e5dd7070Spatrick     Name.replace(loc, 1, "_");
3635e5dd7070Spatrick }
3636e5dd7070Spatrick 
InsertBlockLiteralsWithinMethod(ObjCMethodDecl * MD)3637e5dd7070Spatrick void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3638e5dd7070Spatrick   // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3639e5dd7070Spatrick   // SourceLocation FunLocStart = MD->getBeginLoc();
3640e5dd7070Spatrick   SourceLocation FunLocStart = MD->getBeginLoc();
3641e5dd7070Spatrick   std::string FuncName;
3642e5dd7070Spatrick   BuildUniqueMethodName(FuncName, MD);
3643e5dd7070Spatrick   SynthesizeBlockLiterals(FunLocStart, FuncName);
3644e5dd7070Spatrick }
3645e5dd7070Spatrick 
GetBlockDeclRefExprs(Stmt * S)3646e5dd7070Spatrick void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3647e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
3648e5dd7070Spatrick     if (SubStmt) {
3649e5dd7070Spatrick       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3650e5dd7070Spatrick         GetBlockDeclRefExprs(CBE->getBody());
3651e5dd7070Spatrick       else
3652e5dd7070Spatrick         GetBlockDeclRefExprs(SubStmt);
3653e5dd7070Spatrick     }
3654e5dd7070Spatrick   // Handle specific things.
3655e5dd7070Spatrick   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3656e5dd7070Spatrick     if (DRE->refersToEnclosingVariableOrCapture() ||
3657e5dd7070Spatrick         HasLocalVariableExternalStorage(DRE->getDecl()))
3658e5dd7070Spatrick       // FIXME: Handle enums.
3659e5dd7070Spatrick       BlockDeclRefs.push_back(DRE);
3660e5dd7070Spatrick }
3661e5dd7070Spatrick 
GetInnerBlockDeclRefExprs(Stmt * S,SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs,llvm::SmallPtrSetImpl<const DeclContext * > & InnerContexts)3662e5dd7070Spatrick void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3663e5dd7070Spatrick                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3664e5dd7070Spatrick                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3665e5dd7070Spatrick   for (Stmt *SubStmt : S->children())
3666e5dd7070Spatrick     if (SubStmt) {
3667e5dd7070Spatrick       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3668e5dd7070Spatrick         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3669e5dd7070Spatrick         GetInnerBlockDeclRefExprs(CBE->getBody(),
3670e5dd7070Spatrick                                   InnerBlockDeclRefs,
3671e5dd7070Spatrick                                   InnerContexts);
3672e5dd7070Spatrick       }
3673e5dd7070Spatrick       else
3674e5dd7070Spatrick         GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3675e5dd7070Spatrick     }
3676e5dd7070Spatrick   // Handle specific things.
3677e5dd7070Spatrick   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3678e5dd7070Spatrick     if (DRE->refersToEnclosingVariableOrCapture() ||
3679e5dd7070Spatrick         HasLocalVariableExternalStorage(DRE->getDecl())) {
3680e5dd7070Spatrick       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3681e5dd7070Spatrick         InnerBlockDeclRefs.push_back(DRE);
3682e5dd7070Spatrick       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3683e5dd7070Spatrick         if (Var->isFunctionOrMethodVarDecl())
3684e5dd7070Spatrick           ImportedLocalExternalDecls.insert(Var);
3685e5dd7070Spatrick     }
3686e5dd7070Spatrick   }
3687e5dd7070Spatrick }
3688e5dd7070Spatrick 
3689e5dd7070Spatrick /// convertFunctionTypeOfBlocks - This routine converts a function type
3690e5dd7070Spatrick /// whose result type may be a block pointer or whose argument type(s)
3691e5dd7070Spatrick /// might be block pointers to an equivalent function type replacing
3692e5dd7070Spatrick /// all block pointers to function pointers.
convertFunctionTypeOfBlocks(const FunctionType * FT)3693e5dd7070Spatrick QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3694e5dd7070Spatrick   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3695e5dd7070Spatrick   // FTP will be null for closures that don't take arguments.
3696e5dd7070Spatrick   // Generate a funky cast.
3697e5dd7070Spatrick   SmallVector<QualType, 8> ArgTypes;
3698e5dd7070Spatrick   QualType Res = FT->getReturnType();
3699e5dd7070Spatrick   bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3700e5dd7070Spatrick 
3701e5dd7070Spatrick   if (FTP) {
3702e5dd7070Spatrick     for (auto &I : FTP->param_types()) {
3703e5dd7070Spatrick       QualType t = I;
3704e5dd7070Spatrick       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3705e5dd7070Spatrick       if (convertBlockPointerToFunctionPointer(t))
3706e5dd7070Spatrick         HasBlockType = true;
3707e5dd7070Spatrick       ArgTypes.push_back(t);
3708e5dd7070Spatrick     }
3709e5dd7070Spatrick   }
3710e5dd7070Spatrick   QualType FuncType;
3711e5dd7070Spatrick   // FIXME. Does this work if block takes no argument but has a return type
3712e5dd7070Spatrick   // which is of block type?
3713e5dd7070Spatrick   if (HasBlockType)
3714e5dd7070Spatrick     FuncType = getSimpleFunctionType(Res, ArgTypes);
3715e5dd7070Spatrick   else FuncType = QualType(FT, 0);
3716e5dd7070Spatrick   return FuncType;
3717e5dd7070Spatrick }
3718e5dd7070Spatrick 
SynthesizeBlockCall(CallExpr * Exp,const Expr * BlockExp)3719e5dd7070Spatrick Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3720e5dd7070Spatrick   // Navigate to relevant type information.
3721e5dd7070Spatrick   const BlockPointerType *CPT = nullptr;
3722e5dd7070Spatrick 
3723e5dd7070Spatrick   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3724e5dd7070Spatrick     CPT = DRE->getType()->getAs<BlockPointerType>();
3725e5dd7070Spatrick   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3726e5dd7070Spatrick     CPT = MExpr->getType()->getAs<BlockPointerType>();
3727e5dd7070Spatrick   }
3728e5dd7070Spatrick   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3729e5dd7070Spatrick     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3730e5dd7070Spatrick   }
3731e5dd7070Spatrick   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3732e5dd7070Spatrick     CPT = IEXPR->getType()->getAs<BlockPointerType>();
3733e5dd7070Spatrick   else if (const ConditionalOperator *CEXPR =
3734e5dd7070Spatrick             dyn_cast<ConditionalOperator>(BlockExp)) {
3735e5dd7070Spatrick     Expr *LHSExp = CEXPR->getLHS();
3736e5dd7070Spatrick     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3737e5dd7070Spatrick     Expr *RHSExp = CEXPR->getRHS();
3738e5dd7070Spatrick     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3739e5dd7070Spatrick     Expr *CONDExp = CEXPR->getCond();
3740a9ac8606Spatrick     ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
3741a9ac8606Spatrick         CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
3742a9ac8606Spatrick         cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
3743e5dd7070Spatrick     return CondExpr;
3744e5dd7070Spatrick   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3745e5dd7070Spatrick     CPT = IRE->getType()->getAs<BlockPointerType>();
3746e5dd7070Spatrick   } else if (const PseudoObjectExpr *POE
3747e5dd7070Spatrick                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3748e5dd7070Spatrick     CPT = POE->getType()->castAs<BlockPointerType>();
3749e5dd7070Spatrick   } else {
3750e5dd7070Spatrick     assert(false && "RewriteBlockClass: Bad type");
3751e5dd7070Spatrick   }
3752e5dd7070Spatrick   assert(CPT && "RewriteBlockClass: Bad type");
3753e5dd7070Spatrick   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3754e5dd7070Spatrick   assert(FT && "RewriteBlockClass: Bad type");
3755e5dd7070Spatrick   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3756e5dd7070Spatrick   // FTP will be null for closures that don't take arguments.
3757e5dd7070Spatrick 
3758e5dd7070Spatrick   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3759e5dd7070Spatrick                                       SourceLocation(), SourceLocation(),
3760e5dd7070Spatrick                                       &Context->Idents.get("__block_impl"));
3761e5dd7070Spatrick   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3762e5dd7070Spatrick 
3763e5dd7070Spatrick   // Generate a funky cast.
3764e5dd7070Spatrick   SmallVector<QualType, 8> ArgTypes;
3765e5dd7070Spatrick 
3766e5dd7070Spatrick   // Push the block argument type.
3767e5dd7070Spatrick   ArgTypes.push_back(PtrBlock);
3768e5dd7070Spatrick   if (FTP) {
3769e5dd7070Spatrick     for (auto &I : FTP->param_types()) {
3770e5dd7070Spatrick       QualType t = I;
3771e5dd7070Spatrick       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3772e5dd7070Spatrick       if (!convertBlockPointerToFunctionPointer(t))
3773e5dd7070Spatrick         convertToUnqualifiedObjCType(t);
3774e5dd7070Spatrick       ArgTypes.push_back(t);
3775e5dd7070Spatrick     }
3776e5dd7070Spatrick   }
3777e5dd7070Spatrick   // Now do the pointer to function cast.
3778e5dd7070Spatrick   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3779e5dd7070Spatrick 
3780e5dd7070Spatrick   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3781e5dd7070Spatrick 
3782e5dd7070Spatrick   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3783e5dd7070Spatrick                                                CK_BitCast,
3784e5dd7070Spatrick                                                const_cast<Expr*>(BlockExp));
3785e5dd7070Spatrick   // Don't forget the parens to enforce the proper binding.
3786e5dd7070Spatrick   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3787e5dd7070Spatrick                                           BlkCast);
3788e5dd7070Spatrick   //PE->dump();
3789e5dd7070Spatrick 
3790e5dd7070Spatrick   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3791e5dd7070Spatrick                                     SourceLocation(),
3792e5dd7070Spatrick                                     &Context->Idents.get("FuncPtr"),
3793e5dd7070Spatrick                                     Context->VoidPtrTy, nullptr,
3794e5dd7070Spatrick                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3795e5dd7070Spatrick                                     ICIS_NoInit);
3796e5dd7070Spatrick   MemberExpr *ME = MemberExpr::CreateImplicit(
3797e5dd7070Spatrick       *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
3798e5dd7070Spatrick 
3799e5dd7070Spatrick   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3800e5dd7070Spatrick                                                 CK_BitCast, ME);
3801e5dd7070Spatrick   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3802e5dd7070Spatrick 
3803e5dd7070Spatrick   SmallVector<Expr*, 8> BlkExprs;
3804e5dd7070Spatrick   // Add the implicit argument.
3805e5dd7070Spatrick   BlkExprs.push_back(BlkCast);
3806e5dd7070Spatrick   // Add the user arguments.
3807e5dd7070Spatrick   for (CallExpr::arg_iterator I = Exp->arg_begin(),
3808e5dd7070Spatrick        E = Exp->arg_end(); I != E; ++I) {
3809e5dd7070Spatrick     BlkExprs.push_back(*I);
3810e5dd7070Spatrick   }
3811a9ac8606Spatrick   CallExpr *CE =
3812a9ac8606Spatrick       CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
3813a9ac8606Spatrick                        SourceLocation(), FPOptionsOverride());
3814e5dd7070Spatrick   return CE;
3815e5dd7070Spatrick }
3816e5dd7070Spatrick 
3817e5dd7070Spatrick // We need to return the rewritten expression to handle cases where the
3818e5dd7070Spatrick // BlockDeclRefExpr is embedded in another expression being rewritten.
3819e5dd7070Spatrick // For example:
3820e5dd7070Spatrick //
3821e5dd7070Spatrick // int main() {
3822e5dd7070Spatrick //    __block Foo *f;
3823e5dd7070Spatrick //    __block int i;
3824e5dd7070Spatrick //
3825e5dd7070Spatrick //    void (^myblock)() = ^() {
3826e5dd7070Spatrick //        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3827e5dd7070Spatrick //        i = 77;
3828e5dd7070Spatrick //    };
3829e5dd7070Spatrick //}
RewriteBlockDeclRefExpr(DeclRefExpr * DeclRefExp)3830e5dd7070Spatrick Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3831e5dd7070Spatrick   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3832e5dd7070Spatrick   // for each DeclRefExp where BYREFVAR is name of the variable.
3833e5dd7070Spatrick   ValueDecl *VD = DeclRefExp->getDecl();
3834e5dd7070Spatrick   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3835e5dd7070Spatrick                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3836e5dd7070Spatrick 
3837e5dd7070Spatrick   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3838e5dd7070Spatrick                                     SourceLocation(),
3839e5dd7070Spatrick                                     &Context->Idents.get("__forwarding"),
3840e5dd7070Spatrick                                     Context->VoidPtrTy, nullptr,
3841e5dd7070Spatrick                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
3842e5dd7070Spatrick                                     ICIS_NoInit);
3843e5dd7070Spatrick   MemberExpr *ME =
3844e5dd7070Spatrick       MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
3845e5dd7070Spatrick                                  FD->getType(), VK_LValue, OK_Ordinary);
3846e5dd7070Spatrick 
3847e5dd7070Spatrick   StringRef Name = VD->getName();
3848e5dd7070Spatrick   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3849e5dd7070Spatrick                          &Context->Idents.get(Name),
3850e5dd7070Spatrick                          Context->VoidPtrTy, nullptr,
3851e5dd7070Spatrick                          /*BitWidth=*/nullptr, /*Mutable=*/true,
3852e5dd7070Spatrick                          ICIS_NoInit);
3853e5dd7070Spatrick   ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
3854e5dd7070Spatrick                                   VK_LValue, OK_Ordinary);
3855e5dd7070Spatrick 
3856e5dd7070Spatrick   // Need parens to enforce precedence.
3857e5dd7070Spatrick   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3858e5dd7070Spatrick                                           DeclRefExp->getExprLoc(),
3859e5dd7070Spatrick                                           ME);
3860e5dd7070Spatrick   ReplaceStmt(DeclRefExp, PE);
3861e5dd7070Spatrick   return PE;
3862e5dd7070Spatrick }
3863e5dd7070Spatrick 
3864e5dd7070Spatrick // Rewrites the imported local variable V with external storage
3865e5dd7070Spatrick // (static, extern, etc.) as *V
3866e5dd7070Spatrick //
RewriteLocalVariableExternalStorage(DeclRefExpr * DRE)3867e5dd7070Spatrick Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3868e5dd7070Spatrick   ValueDecl *VD = DRE->getDecl();
3869e5dd7070Spatrick   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3870e5dd7070Spatrick     if (!ImportedLocalExternalDecls.count(Var))
3871e5dd7070Spatrick       return DRE;
3872ec727ea7Spatrick   Expr *Exp = UnaryOperator::Create(
3873ec727ea7Spatrick       const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
3874ec727ea7Spatrick       VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
3875e5dd7070Spatrick   // Need parens to enforce precedence.
3876e5dd7070Spatrick   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3877e5dd7070Spatrick                                           Exp);
3878e5dd7070Spatrick   ReplaceStmt(DRE, PE);
3879e5dd7070Spatrick   return PE;
3880e5dd7070Spatrick }
3881e5dd7070Spatrick 
RewriteCastExpr(CStyleCastExpr * CE)3882e5dd7070Spatrick void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3883e5dd7070Spatrick   SourceLocation LocStart = CE->getLParenLoc();
3884e5dd7070Spatrick   SourceLocation LocEnd = CE->getRParenLoc();
3885e5dd7070Spatrick 
3886e5dd7070Spatrick   // Need to avoid trying to rewrite synthesized casts.
3887e5dd7070Spatrick   if (LocStart.isInvalid())
3888e5dd7070Spatrick     return;
3889e5dd7070Spatrick   // Need to avoid trying to rewrite casts contained in macros.
3890e5dd7070Spatrick   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3891e5dd7070Spatrick     return;
3892e5dd7070Spatrick 
3893e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(LocStart);
3894e5dd7070Spatrick   const char *endBuf = SM->getCharacterData(LocEnd);
3895e5dd7070Spatrick   QualType QT = CE->getType();
3896e5dd7070Spatrick   const Type* TypePtr = QT->getAs<Type>();
3897e5dd7070Spatrick   if (isa<TypeOfExprType>(TypePtr)) {
3898e5dd7070Spatrick     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3899e5dd7070Spatrick     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3900e5dd7070Spatrick     std::string TypeAsString = "(";
3901e5dd7070Spatrick     RewriteBlockPointerType(TypeAsString, QT);
3902e5dd7070Spatrick     TypeAsString += ")";
3903e5dd7070Spatrick     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3904e5dd7070Spatrick     return;
3905e5dd7070Spatrick   }
3906e5dd7070Spatrick   // advance the location to startArgList.
3907e5dd7070Spatrick   const char *argPtr = startBuf;
3908e5dd7070Spatrick 
3909e5dd7070Spatrick   while (*argPtr++ && (argPtr < endBuf)) {
3910e5dd7070Spatrick     switch (*argPtr) {
3911e5dd7070Spatrick     case '^':
3912e5dd7070Spatrick       // Replace the '^' with '*'.
3913e5dd7070Spatrick       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3914e5dd7070Spatrick       ReplaceText(LocStart, 1, "*");
3915e5dd7070Spatrick       break;
3916e5dd7070Spatrick     }
3917e5dd7070Spatrick   }
3918e5dd7070Spatrick }
3919e5dd7070Spatrick 
RewriteBlockPointerFunctionArgs(FunctionDecl * FD)3920e5dd7070Spatrick void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3921e5dd7070Spatrick   SourceLocation DeclLoc = FD->getLocation();
3922e5dd7070Spatrick   unsigned parenCount = 0;
3923e5dd7070Spatrick 
3924e5dd7070Spatrick   // We have 1 or more arguments that have closure pointers.
3925e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(DeclLoc);
3926e5dd7070Spatrick   const char *startArgList = strchr(startBuf, '(');
3927e5dd7070Spatrick 
3928e5dd7070Spatrick   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3929e5dd7070Spatrick 
3930e5dd7070Spatrick   parenCount++;
3931e5dd7070Spatrick   // advance the location to startArgList.
3932e5dd7070Spatrick   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3933e5dd7070Spatrick   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3934e5dd7070Spatrick 
3935e5dd7070Spatrick   const char *argPtr = startArgList;
3936e5dd7070Spatrick 
3937e5dd7070Spatrick   while (*argPtr++ && parenCount) {
3938e5dd7070Spatrick     switch (*argPtr) {
3939e5dd7070Spatrick     case '^':
3940e5dd7070Spatrick       // Replace the '^' with '*'.
3941e5dd7070Spatrick       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3942e5dd7070Spatrick       ReplaceText(DeclLoc, 1, "*");
3943e5dd7070Spatrick       break;
3944e5dd7070Spatrick     case '(':
3945e5dd7070Spatrick       parenCount++;
3946e5dd7070Spatrick       break;
3947e5dd7070Spatrick     case ')':
3948e5dd7070Spatrick       parenCount--;
3949e5dd7070Spatrick       break;
3950e5dd7070Spatrick     }
3951e5dd7070Spatrick   }
3952e5dd7070Spatrick }
3953e5dd7070Spatrick 
PointerTypeTakesAnyBlockArguments(QualType QT)3954e5dd7070Spatrick bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3955e5dd7070Spatrick   const FunctionProtoType *FTP;
3956e5dd7070Spatrick   const PointerType *PT = QT->getAs<PointerType>();
3957e5dd7070Spatrick   if (PT) {
3958e5dd7070Spatrick     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3959e5dd7070Spatrick   } else {
3960e5dd7070Spatrick     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3961e5dd7070Spatrick     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3962e5dd7070Spatrick     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3963e5dd7070Spatrick   }
3964e5dd7070Spatrick   if (FTP) {
3965e5dd7070Spatrick     for (const auto &I : FTP->param_types())
3966e5dd7070Spatrick       if (isTopLevelBlockPointerType(I))
3967e5dd7070Spatrick         return true;
3968e5dd7070Spatrick   }
3969e5dd7070Spatrick   return false;
3970e5dd7070Spatrick }
3971e5dd7070Spatrick 
PointerTypeTakesAnyObjCQualifiedType(QualType QT)3972e5dd7070Spatrick bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3973e5dd7070Spatrick   const FunctionProtoType *FTP;
3974e5dd7070Spatrick   const PointerType *PT = QT->getAs<PointerType>();
3975e5dd7070Spatrick   if (PT) {
3976e5dd7070Spatrick     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3977e5dd7070Spatrick   } else {
3978e5dd7070Spatrick     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3979e5dd7070Spatrick     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3980e5dd7070Spatrick     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3981e5dd7070Spatrick   }
3982e5dd7070Spatrick   if (FTP) {
3983e5dd7070Spatrick     for (const auto &I : FTP->param_types()) {
3984e5dd7070Spatrick       if (I->isObjCQualifiedIdType())
3985e5dd7070Spatrick         return true;
3986e5dd7070Spatrick       if (I->isObjCObjectPointerType() &&
3987e5dd7070Spatrick           I->getPointeeType()->isObjCQualifiedInterfaceType())
3988e5dd7070Spatrick         return true;
3989e5dd7070Spatrick     }
3990e5dd7070Spatrick 
3991e5dd7070Spatrick   }
3992e5dd7070Spatrick   return false;
3993e5dd7070Spatrick }
3994e5dd7070Spatrick 
GetExtentOfArgList(const char * Name,const char * & LParen,const char * & RParen)3995e5dd7070Spatrick void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3996e5dd7070Spatrick                                      const char *&RParen) {
3997e5dd7070Spatrick   const char *argPtr = strchr(Name, '(');
3998e5dd7070Spatrick   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3999e5dd7070Spatrick 
4000e5dd7070Spatrick   LParen = argPtr; // output the start.
4001e5dd7070Spatrick   argPtr++; // skip past the left paren.
4002e5dd7070Spatrick   unsigned parenCount = 1;
4003e5dd7070Spatrick 
4004e5dd7070Spatrick   while (*argPtr && parenCount) {
4005e5dd7070Spatrick     switch (*argPtr) {
4006e5dd7070Spatrick     case '(': parenCount++; break;
4007e5dd7070Spatrick     case ')': parenCount--; break;
4008e5dd7070Spatrick     default: break;
4009e5dd7070Spatrick     }
4010e5dd7070Spatrick     if (parenCount) argPtr++;
4011e5dd7070Spatrick   }
4012e5dd7070Spatrick   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4013e5dd7070Spatrick   RParen = argPtr; // output the end
4014e5dd7070Spatrick }
4015e5dd7070Spatrick 
RewriteBlockPointerDecl(NamedDecl * ND)4016e5dd7070Spatrick void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4017e5dd7070Spatrick   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4018e5dd7070Spatrick     RewriteBlockPointerFunctionArgs(FD);
4019e5dd7070Spatrick     return;
4020e5dd7070Spatrick   }
4021e5dd7070Spatrick   // Handle Variables and Typedefs.
4022e5dd7070Spatrick   SourceLocation DeclLoc = ND->getLocation();
4023e5dd7070Spatrick   QualType DeclT;
4024e5dd7070Spatrick   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4025e5dd7070Spatrick     DeclT = VD->getType();
4026e5dd7070Spatrick   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4027e5dd7070Spatrick     DeclT = TDD->getUnderlyingType();
4028e5dd7070Spatrick   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4029e5dd7070Spatrick     DeclT = FD->getType();
4030e5dd7070Spatrick   else
4031e5dd7070Spatrick     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4032e5dd7070Spatrick 
4033e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(DeclLoc);
4034e5dd7070Spatrick   const char *endBuf = startBuf;
4035e5dd7070Spatrick   // scan backward (from the decl location) for the end of the previous decl.
4036e5dd7070Spatrick   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4037e5dd7070Spatrick     startBuf--;
4038e5dd7070Spatrick   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4039e5dd7070Spatrick   std::string buf;
4040e5dd7070Spatrick   unsigned OrigLength=0;
4041e5dd7070Spatrick   // *startBuf != '^' if we are dealing with a pointer to function that
4042e5dd7070Spatrick   // may take block argument types (which will be handled below).
4043e5dd7070Spatrick   if (*startBuf == '^') {
4044e5dd7070Spatrick     // Replace the '^' with '*', computing a negative offset.
4045e5dd7070Spatrick     buf = '*';
4046e5dd7070Spatrick     startBuf++;
4047e5dd7070Spatrick     OrigLength++;
4048e5dd7070Spatrick   }
4049e5dd7070Spatrick   while (*startBuf != ')') {
4050e5dd7070Spatrick     buf += *startBuf;
4051e5dd7070Spatrick     startBuf++;
4052e5dd7070Spatrick     OrigLength++;
4053e5dd7070Spatrick   }
4054e5dd7070Spatrick   buf += ')';
4055e5dd7070Spatrick   OrigLength++;
4056e5dd7070Spatrick 
4057e5dd7070Spatrick   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4058e5dd7070Spatrick       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4059e5dd7070Spatrick     // Replace the '^' with '*' for arguments.
4060e5dd7070Spatrick     // Replace id<P> with id/*<>*/
4061e5dd7070Spatrick     DeclLoc = ND->getLocation();
4062e5dd7070Spatrick     startBuf = SM->getCharacterData(DeclLoc);
4063e5dd7070Spatrick     const char *argListBegin, *argListEnd;
4064e5dd7070Spatrick     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4065e5dd7070Spatrick     while (argListBegin < argListEnd) {
4066e5dd7070Spatrick       if (*argListBegin == '^')
4067e5dd7070Spatrick         buf += '*';
4068e5dd7070Spatrick       else if (*argListBegin ==  '<') {
4069e5dd7070Spatrick         buf += "/*";
4070e5dd7070Spatrick         buf += *argListBegin++;
4071e5dd7070Spatrick         OrigLength++;
4072e5dd7070Spatrick         while (*argListBegin != '>') {
4073e5dd7070Spatrick           buf += *argListBegin++;
4074e5dd7070Spatrick           OrigLength++;
4075e5dd7070Spatrick         }
4076e5dd7070Spatrick         buf += *argListBegin;
4077e5dd7070Spatrick         buf += "*/";
4078e5dd7070Spatrick       }
4079e5dd7070Spatrick       else
4080e5dd7070Spatrick         buf += *argListBegin;
4081e5dd7070Spatrick       argListBegin++;
4082e5dd7070Spatrick       OrigLength++;
4083e5dd7070Spatrick     }
4084e5dd7070Spatrick     buf += ')';
4085e5dd7070Spatrick     OrigLength++;
4086e5dd7070Spatrick   }
4087e5dd7070Spatrick   ReplaceText(Start, OrigLength, buf);
4088e5dd7070Spatrick }
4089e5dd7070Spatrick 
4090e5dd7070Spatrick /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4091e5dd7070Spatrick /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4092e5dd7070Spatrick ///                    struct Block_byref_id_object *src) {
4093e5dd7070Spatrick ///  _Block_object_assign (&_dest->object, _src->object,
4094e5dd7070Spatrick ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4095e5dd7070Spatrick ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4096e5dd7070Spatrick ///  _Block_object_assign(&_dest->object, _src->object,
4097e5dd7070Spatrick ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4098e5dd7070Spatrick ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4099e5dd7070Spatrick /// }
4100e5dd7070Spatrick /// And:
4101e5dd7070Spatrick /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4102e5dd7070Spatrick ///  _Block_object_dispose(_src->object,
4103e5dd7070Spatrick ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4104e5dd7070Spatrick ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4105e5dd7070Spatrick ///  _Block_object_dispose(_src->object,
4106e5dd7070Spatrick ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4107e5dd7070Spatrick ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4108e5dd7070Spatrick /// }
4109e5dd7070Spatrick 
SynthesizeByrefCopyDestroyHelper(VarDecl * VD,int flag)4110e5dd7070Spatrick std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4111e5dd7070Spatrick                                                           int flag) {
4112e5dd7070Spatrick   std::string S;
4113e5dd7070Spatrick   if (CopyDestroyCache.count(flag))
4114e5dd7070Spatrick     return S;
4115e5dd7070Spatrick   CopyDestroyCache.insert(flag);
4116e5dd7070Spatrick   S = "static void __Block_byref_id_object_copy_";
4117e5dd7070Spatrick   S += utostr(flag);
4118e5dd7070Spatrick   S += "(void *dst, void *src) {\n";
4119e5dd7070Spatrick 
4120e5dd7070Spatrick   // offset into the object pointer is computed as:
4121e5dd7070Spatrick   // void * + void* + int + int + void* + void *
4122e5dd7070Spatrick   unsigned IntSize =
4123e5dd7070Spatrick   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4124e5dd7070Spatrick   unsigned VoidPtrSize =
4125e5dd7070Spatrick   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4126e5dd7070Spatrick 
4127e5dd7070Spatrick   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4128e5dd7070Spatrick   S += " _Block_object_assign((char*)dst + ";
4129e5dd7070Spatrick   S += utostr(offset);
4130e5dd7070Spatrick   S += ", *(void * *) ((char*)src + ";
4131e5dd7070Spatrick   S += utostr(offset);
4132e5dd7070Spatrick   S += "), ";
4133e5dd7070Spatrick   S += utostr(flag);
4134e5dd7070Spatrick   S += ");\n}\n";
4135e5dd7070Spatrick 
4136e5dd7070Spatrick   S += "static void __Block_byref_id_object_dispose_";
4137e5dd7070Spatrick   S += utostr(flag);
4138e5dd7070Spatrick   S += "(void *src) {\n";
4139e5dd7070Spatrick   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4140e5dd7070Spatrick   S += utostr(offset);
4141e5dd7070Spatrick   S += "), ";
4142e5dd7070Spatrick   S += utostr(flag);
4143e5dd7070Spatrick   S += ");\n}\n";
4144e5dd7070Spatrick   return S;
4145e5dd7070Spatrick }
4146e5dd7070Spatrick 
4147e5dd7070Spatrick /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4148e5dd7070Spatrick /// the declaration into:
4149e5dd7070Spatrick /// struct __Block_byref_ND {
4150e5dd7070Spatrick /// void *__isa;                  // NULL for everything except __weak pointers
4151e5dd7070Spatrick /// struct __Block_byref_ND *__forwarding;
4152e5dd7070Spatrick /// int32_t __flags;
4153e5dd7070Spatrick /// int32_t __size;
4154e5dd7070Spatrick /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4155e5dd7070Spatrick /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4156e5dd7070Spatrick /// typex ND;
4157e5dd7070Spatrick /// };
4158e5dd7070Spatrick ///
4159e5dd7070Spatrick /// It then replaces declaration of ND variable with:
4160e5dd7070Spatrick /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4161e5dd7070Spatrick ///                               __size=sizeof(struct __Block_byref_ND),
4162e5dd7070Spatrick ///                               ND=initializer-if-any};
4163e5dd7070Spatrick ///
4164e5dd7070Spatrick ///
RewriteByRefVar(VarDecl * ND)4165e5dd7070Spatrick void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4166e5dd7070Spatrick   // Insert declaration for the function in which block literal is
4167e5dd7070Spatrick   // used.
4168e5dd7070Spatrick   if (CurFunctionDeclToDeclareForBlock)
4169e5dd7070Spatrick     RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4170e5dd7070Spatrick   int flag = 0;
4171e5dd7070Spatrick   int isa = 0;
4172e5dd7070Spatrick   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4173e5dd7070Spatrick   if (DeclLoc.isInvalid())
4174e5dd7070Spatrick     // If type location is missing, it is because of missing type (a warning).
4175e5dd7070Spatrick     // Use variable's location which is good for this case.
4176e5dd7070Spatrick     DeclLoc = ND->getLocation();
4177e5dd7070Spatrick   const char *startBuf = SM->getCharacterData(DeclLoc);
4178e5dd7070Spatrick   SourceLocation X = ND->getEndLoc();
4179e5dd7070Spatrick   X = SM->getExpansionLoc(X);
4180e5dd7070Spatrick   const char *endBuf = SM->getCharacterData(X);
4181e5dd7070Spatrick   std::string Name(ND->getNameAsString());
4182e5dd7070Spatrick   std::string ByrefType;
4183e5dd7070Spatrick   RewriteByRefString(ByrefType, Name, ND, true);
4184e5dd7070Spatrick   ByrefType += " {\n";
4185e5dd7070Spatrick   ByrefType += "  void *__isa;\n";
4186e5dd7070Spatrick   RewriteByRefString(ByrefType, Name, ND);
4187e5dd7070Spatrick   ByrefType += " *__forwarding;\n";
4188e5dd7070Spatrick   ByrefType += " int __flags;\n";
4189e5dd7070Spatrick   ByrefType += " int __size;\n";
4190e5dd7070Spatrick   // Add void *__Block_byref_id_object_copy;
4191e5dd7070Spatrick   // void *__Block_byref_id_object_dispose; if needed.
4192e5dd7070Spatrick   QualType Ty = ND->getType();
4193e5dd7070Spatrick   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4194e5dd7070Spatrick   if (HasCopyAndDispose) {
4195e5dd7070Spatrick     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4196e5dd7070Spatrick     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4197e5dd7070Spatrick   }
4198e5dd7070Spatrick 
4199e5dd7070Spatrick   QualType T = Ty;
4200e5dd7070Spatrick   (void)convertBlockPointerToFunctionPointer(T);
4201e5dd7070Spatrick   T.getAsStringInternal(Name, Context->getPrintingPolicy());
4202e5dd7070Spatrick 
4203e5dd7070Spatrick   ByrefType += " " + Name + ";\n";
4204e5dd7070Spatrick   ByrefType += "};\n";
4205e5dd7070Spatrick   // Insert this type in global scope. It is needed by helper function.
4206e5dd7070Spatrick   SourceLocation FunLocStart;
4207e5dd7070Spatrick   if (CurFunctionDef)
4208e5dd7070Spatrick      FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4209e5dd7070Spatrick   else {
4210e5dd7070Spatrick     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4211e5dd7070Spatrick     FunLocStart = CurMethodDef->getBeginLoc();
4212e5dd7070Spatrick   }
4213e5dd7070Spatrick   InsertText(FunLocStart, ByrefType);
4214e5dd7070Spatrick   if (Ty.isObjCGCWeak()) {
4215e5dd7070Spatrick     flag |= BLOCK_FIELD_IS_WEAK;
4216e5dd7070Spatrick     isa = 1;
4217e5dd7070Spatrick   }
4218e5dd7070Spatrick 
4219e5dd7070Spatrick   if (HasCopyAndDispose) {
4220e5dd7070Spatrick     flag = BLOCK_BYREF_CALLER;
4221e5dd7070Spatrick     QualType Ty = ND->getType();
4222e5dd7070Spatrick     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4223e5dd7070Spatrick     if (Ty->isBlockPointerType())
4224e5dd7070Spatrick       flag |= BLOCK_FIELD_IS_BLOCK;
4225e5dd7070Spatrick     else
4226e5dd7070Spatrick       flag |= BLOCK_FIELD_IS_OBJECT;
4227e5dd7070Spatrick     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4228e5dd7070Spatrick     if (!HF.empty())
4229e5dd7070Spatrick       InsertText(FunLocStart, HF);
4230e5dd7070Spatrick   }
4231e5dd7070Spatrick 
4232e5dd7070Spatrick   // struct __Block_byref_ND ND =
4233e5dd7070Spatrick   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4234e5dd7070Spatrick   //  initializer-if-any};
4235e5dd7070Spatrick   bool hasInit = (ND->getInit() != nullptr);
4236e5dd7070Spatrick   unsigned flags = 0;
4237e5dd7070Spatrick   if (HasCopyAndDispose)
4238e5dd7070Spatrick     flags |= BLOCK_HAS_COPY_DISPOSE;
4239e5dd7070Spatrick   Name = ND->getNameAsString();
4240e5dd7070Spatrick   ByrefType.clear();
4241e5dd7070Spatrick   RewriteByRefString(ByrefType, Name, ND);
4242e5dd7070Spatrick   std::string ForwardingCastType("(");
4243e5dd7070Spatrick   ForwardingCastType += ByrefType + " *)";
4244e5dd7070Spatrick   if (!hasInit) {
4245e5dd7070Spatrick     ByrefType += " " + Name + " = {(void*)";
4246e5dd7070Spatrick     ByrefType += utostr(isa);
4247e5dd7070Spatrick     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4248e5dd7070Spatrick     ByrefType += utostr(flags);
4249e5dd7070Spatrick     ByrefType += ", ";
4250e5dd7070Spatrick     ByrefType += "sizeof(";
4251e5dd7070Spatrick     RewriteByRefString(ByrefType, Name, ND);
4252e5dd7070Spatrick     ByrefType += ")";
4253e5dd7070Spatrick     if (HasCopyAndDispose) {
4254e5dd7070Spatrick       ByrefType += ", __Block_byref_id_object_copy_";
4255e5dd7070Spatrick       ByrefType += utostr(flag);
4256e5dd7070Spatrick       ByrefType += ", __Block_byref_id_object_dispose_";
4257e5dd7070Spatrick       ByrefType += utostr(flag);
4258e5dd7070Spatrick     }
4259e5dd7070Spatrick     ByrefType += "};\n";
4260e5dd7070Spatrick     unsigned nameSize = Name.size();
4261e5dd7070Spatrick     // for block or function pointer declaration. Name is already
4262e5dd7070Spatrick     // part of the declaration.
4263e5dd7070Spatrick     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4264e5dd7070Spatrick       nameSize = 1;
4265e5dd7070Spatrick     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4266e5dd7070Spatrick   }
4267e5dd7070Spatrick   else {
4268e5dd7070Spatrick     SourceLocation startLoc;
4269e5dd7070Spatrick     Expr *E = ND->getInit();
4270e5dd7070Spatrick     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4271e5dd7070Spatrick       startLoc = ECE->getLParenLoc();
4272e5dd7070Spatrick     else
4273e5dd7070Spatrick       startLoc = E->getBeginLoc();
4274e5dd7070Spatrick     startLoc = SM->getExpansionLoc(startLoc);
4275e5dd7070Spatrick     endBuf = SM->getCharacterData(startLoc);
4276e5dd7070Spatrick     ByrefType += " " + Name;
4277e5dd7070Spatrick     ByrefType += " = {(void*)";
4278e5dd7070Spatrick     ByrefType += utostr(isa);
4279e5dd7070Spatrick     ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4280e5dd7070Spatrick     ByrefType += utostr(flags);
4281e5dd7070Spatrick     ByrefType += ", ";
4282e5dd7070Spatrick     ByrefType += "sizeof(";
4283e5dd7070Spatrick     RewriteByRefString(ByrefType, Name, ND);
4284e5dd7070Spatrick     ByrefType += "), ";
4285e5dd7070Spatrick     if (HasCopyAndDispose) {
4286e5dd7070Spatrick       ByrefType += "__Block_byref_id_object_copy_";
4287e5dd7070Spatrick       ByrefType += utostr(flag);
4288e5dd7070Spatrick       ByrefType += ", __Block_byref_id_object_dispose_";
4289e5dd7070Spatrick       ByrefType += utostr(flag);
4290e5dd7070Spatrick       ByrefType += ", ";
4291e5dd7070Spatrick     }
4292e5dd7070Spatrick     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4293e5dd7070Spatrick 
4294e5dd7070Spatrick     // Complete the newly synthesized compound expression by inserting a right
4295e5dd7070Spatrick     // curly brace before the end of the declaration.
4296e5dd7070Spatrick     // FIXME: This approach avoids rewriting the initializer expression. It
4297e5dd7070Spatrick     // also assumes there is only one declarator. For example, the following
4298e5dd7070Spatrick     // isn't currently supported by this routine (in general):
4299e5dd7070Spatrick     //
4300e5dd7070Spatrick     // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4301e5dd7070Spatrick     //
4302e5dd7070Spatrick     const char *startInitializerBuf = SM->getCharacterData(startLoc);
4303e5dd7070Spatrick     const char *semiBuf = strchr(startInitializerBuf, ';');
4304e5dd7070Spatrick     assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4305e5dd7070Spatrick     SourceLocation semiLoc =
4306e5dd7070Spatrick       startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4307e5dd7070Spatrick 
4308e5dd7070Spatrick     InsertText(semiLoc, "}");
4309e5dd7070Spatrick   }
4310e5dd7070Spatrick }
4311e5dd7070Spatrick 
CollectBlockDeclRefInfo(BlockExpr * Exp)4312e5dd7070Spatrick void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4313e5dd7070Spatrick   // Add initializers for any closure decl refs.
4314e5dd7070Spatrick   GetBlockDeclRefExprs(Exp->getBody());
4315e5dd7070Spatrick   if (BlockDeclRefs.size()) {
4316e5dd7070Spatrick     // Unique all "by copy" declarations.
4317e5dd7070Spatrick     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4318e5dd7070Spatrick       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4319e5dd7070Spatrick         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4320e5dd7070Spatrick           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4321e5dd7070Spatrick           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4322e5dd7070Spatrick         }
4323e5dd7070Spatrick       }
4324e5dd7070Spatrick     // Unique all "by ref" declarations.
4325e5dd7070Spatrick     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4326e5dd7070Spatrick       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4327e5dd7070Spatrick         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4328e5dd7070Spatrick           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4329e5dd7070Spatrick           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4330e5dd7070Spatrick         }
4331e5dd7070Spatrick       }
4332e5dd7070Spatrick     // Find any imported blocks...they will need special attention.
4333e5dd7070Spatrick     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4334e5dd7070Spatrick       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4335e5dd7070Spatrick           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4336e5dd7070Spatrick           BlockDeclRefs[i]->getType()->isBlockPointerType())
4337e5dd7070Spatrick         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4338e5dd7070Spatrick   }
4339e5dd7070Spatrick }
4340e5dd7070Spatrick 
SynthBlockInitFunctionDecl(StringRef name)4341e5dd7070Spatrick FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4342e5dd7070Spatrick   IdentifierInfo *ID = &Context->Idents.get(name);
4343e5dd7070Spatrick   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4344e5dd7070Spatrick   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4345e5dd7070Spatrick                               SourceLocation(), ID, FType, nullptr, SC_Extern,
4346e5dd7070Spatrick                               false, false);
4347e5dd7070Spatrick }
4348e5dd7070Spatrick 
SynthBlockInitExpr(BlockExpr * Exp,const SmallVectorImpl<DeclRefExpr * > & InnerBlockDeclRefs)4349e5dd7070Spatrick Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4350e5dd7070Spatrick                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4351e5dd7070Spatrick   const BlockDecl *block = Exp->getBlockDecl();
4352e5dd7070Spatrick   Blocks.push_back(Exp);
4353e5dd7070Spatrick 
4354e5dd7070Spatrick   CollectBlockDeclRefInfo(Exp);
4355e5dd7070Spatrick 
4356e5dd7070Spatrick   // Add inner imported variables now used in current block.
4357e5dd7070Spatrick  int countOfInnerDecls = 0;
4358e5dd7070Spatrick   if (!InnerBlockDeclRefs.empty()) {
4359e5dd7070Spatrick     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4360e5dd7070Spatrick       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4361e5dd7070Spatrick       ValueDecl *VD = Exp->getDecl();
4362e5dd7070Spatrick       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4363e5dd7070Spatrick       // We need to save the copied-in variables in nested
4364e5dd7070Spatrick       // blocks because it is needed at the end for some of the API generations.
4365e5dd7070Spatrick       // See SynthesizeBlockLiterals routine.
4366e5dd7070Spatrick         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4367e5dd7070Spatrick         BlockDeclRefs.push_back(Exp);
4368e5dd7070Spatrick         BlockByCopyDeclsPtrSet.insert(VD);
4369e5dd7070Spatrick         BlockByCopyDecls.push_back(VD);
4370e5dd7070Spatrick       }
4371e5dd7070Spatrick       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4372e5dd7070Spatrick         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4373e5dd7070Spatrick         BlockDeclRefs.push_back(Exp);
4374e5dd7070Spatrick         BlockByRefDeclsPtrSet.insert(VD);
4375e5dd7070Spatrick         BlockByRefDecls.push_back(VD);
4376e5dd7070Spatrick       }
4377e5dd7070Spatrick     }
4378e5dd7070Spatrick     // Find any imported blocks...they will need special attention.
4379e5dd7070Spatrick     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4380e5dd7070Spatrick       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4381e5dd7070Spatrick           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4382e5dd7070Spatrick           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4383e5dd7070Spatrick         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4384e5dd7070Spatrick   }
4385e5dd7070Spatrick   InnerDeclRefsCount.push_back(countOfInnerDecls);
4386e5dd7070Spatrick 
4387e5dd7070Spatrick   std::string FuncName;
4388e5dd7070Spatrick 
4389e5dd7070Spatrick   if (CurFunctionDef)
4390e5dd7070Spatrick     FuncName = CurFunctionDef->getNameAsString();
4391e5dd7070Spatrick   else if (CurMethodDef)
4392e5dd7070Spatrick     BuildUniqueMethodName(FuncName, CurMethodDef);
4393e5dd7070Spatrick   else if (GlobalVarDecl)
4394e5dd7070Spatrick     FuncName = std::string(GlobalVarDecl->getNameAsString());
4395e5dd7070Spatrick 
4396e5dd7070Spatrick   std::string BlockNumber = utostr(Blocks.size()-1);
4397e5dd7070Spatrick 
4398e5dd7070Spatrick   std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4399e5dd7070Spatrick   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4400e5dd7070Spatrick 
4401e5dd7070Spatrick   // Get a pointer to the function type so we can cast appropriately.
4402e5dd7070Spatrick   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4403e5dd7070Spatrick   QualType FType = Context->getPointerType(BFT);
4404e5dd7070Spatrick 
4405e5dd7070Spatrick   FunctionDecl *FD;
4406e5dd7070Spatrick   Expr *NewRep;
4407e5dd7070Spatrick 
4408e5dd7070Spatrick   // Simulate a constructor call...
4409e5dd7070Spatrick   FD = SynthBlockInitFunctionDecl(Tag);
4410e5dd7070Spatrick   DeclRefExpr *DRE = new (Context)
4411a9ac8606Spatrick       DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation());
4412e5dd7070Spatrick 
4413e5dd7070Spatrick   SmallVector<Expr*, 4> InitExprs;
4414e5dd7070Spatrick 
4415e5dd7070Spatrick   // Initialize the block function.
4416e5dd7070Spatrick   FD = SynthBlockInitFunctionDecl(Func);
4417e5dd7070Spatrick   DeclRefExpr *Arg = new (Context) DeclRefExpr(
4418e5dd7070Spatrick       *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
4419e5dd7070Spatrick   CastExpr *castExpr =
4420e5dd7070Spatrick       NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
4421e5dd7070Spatrick   InitExprs.push_back(castExpr);
4422e5dd7070Spatrick 
4423e5dd7070Spatrick   // Initialize the block descriptor.
4424e5dd7070Spatrick   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4425e5dd7070Spatrick 
4426e5dd7070Spatrick   VarDecl *NewVD = VarDecl::Create(
4427e5dd7070Spatrick       *Context, TUDecl, SourceLocation(), SourceLocation(),
4428e5dd7070Spatrick       &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4429ec727ea7Spatrick   UnaryOperator *DescRefExpr = UnaryOperator::Create(
4430ec727ea7Spatrick       const_cast<ASTContext &>(*Context),
4431e5dd7070Spatrick       new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
4432e5dd7070Spatrick                                 VK_LValue, SourceLocation()),
4433a9ac8606Spatrick       UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
4434ec727ea7Spatrick       OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
4435e5dd7070Spatrick   InitExprs.push_back(DescRefExpr);
4436e5dd7070Spatrick 
4437e5dd7070Spatrick   // Add initializers for any closure decl refs.
4438e5dd7070Spatrick   if (BlockDeclRefs.size()) {
4439e5dd7070Spatrick     Expr *Exp;
4440e5dd7070Spatrick     // Output all "by copy" declarations.
4441e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4442e5dd7070Spatrick          E = BlockByCopyDecls.end(); I != E; ++I) {
4443e5dd7070Spatrick       if (isObjCType((*I)->getType())) {
4444e5dd7070Spatrick         // FIXME: Conform to ABI ([[obj retain] autorelease]).
4445e5dd7070Spatrick         FD = SynthBlockInitFunctionDecl((*I)->getName());
4446e5dd7070Spatrick         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4447e5dd7070Spatrick                                         VK_LValue, SourceLocation());
4448e5dd7070Spatrick         if (HasLocalVariableExternalStorage(*I)) {
4449e5dd7070Spatrick           QualType QT = (*I)->getType();
4450e5dd7070Spatrick           QT = Context->getPointerType(QT);
4451a9ac8606Spatrick           Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
4452a9ac8606Spatrick                                       UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
4453a9ac8606Spatrick                                       SourceLocation(), false,
4454a9ac8606Spatrick                                       FPOptionsOverride());
4455e5dd7070Spatrick         }
4456e5dd7070Spatrick       } else if (isTopLevelBlockPointerType((*I)->getType())) {
4457e5dd7070Spatrick         FD = SynthBlockInitFunctionDecl((*I)->getName());
4458e5dd7070Spatrick         Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4459e5dd7070Spatrick                                         VK_LValue, SourceLocation());
4460e5dd7070Spatrick         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
4461e5dd7070Spatrick                                        Arg);
4462e5dd7070Spatrick       } else {
4463e5dd7070Spatrick         FD = SynthBlockInitFunctionDecl((*I)->getName());
4464e5dd7070Spatrick         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4465e5dd7070Spatrick                                         VK_LValue, SourceLocation());
4466e5dd7070Spatrick         if (HasLocalVariableExternalStorage(*I)) {
4467e5dd7070Spatrick           QualType QT = (*I)->getType();
4468e5dd7070Spatrick           QT = Context->getPointerType(QT);
4469a9ac8606Spatrick           Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
4470a9ac8606Spatrick                                       UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
4471a9ac8606Spatrick                                       SourceLocation(), false,
4472a9ac8606Spatrick                                       FPOptionsOverride());
4473e5dd7070Spatrick         }
4474e5dd7070Spatrick       }
4475e5dd7070Spatrick       InitExprs.push_back(Exp);
4476e5dd7070Spatrick     }
4477e5dd7070Spatrick     // Output all "by ref" declarations.
4478e5dd7070Spatrick     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4479e5dd7070Spatrick          E = BlockByRefDecls.end(); I != E; ++I) {
4480e5dd7070Spatrick       ValueDecl *ND = (*I);
4481e5dd7070Spatrick       std::string Name(ND->getNameAsString());
4482e5dd7070Spatrick       std::string RecName;
4483e5dd7070Spatrick       RewriteByRefString(RecName, Name, ND, true);
4484e5dd7070Spatrick       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4485e5dd7070Spatrick                                                 + sizeof("struct"));
4486e5dd7070Spatrick       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4487e5dd7070Spatrick                                           SourceLocation(), SourceLocation(),
4488e5dd7070Spatrick                                           II);
4489e5dd7070Spatrick       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4490e5dd7070Spatrick       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4491e5dd7070Spatrick 
4492e5dd7070Spatrick       FD = SynthBlockInitFunctionDecl((*I)->getName());
4493e5dd7070Spatrick       Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4494e5dd7070Spatrick                                       VK_LValue, SourceLocation());
4495e5dd7070Spatrick       bool isNestedCapturedVar = false;
4496e5dd7070Spatrick       if (block)
4497e5dd7070Spatrick         for (const auto &CI : block->captures()) {
4498e5dd7070Spatrick           const VarDecl *variable = CI.getVariable();
4499e5dd7070Spatrick           if (variable == ND && CI.isNested()) {
4500e5dd7070Spatrick             assert (CI.isByRef() &&
4501e5dd7070Spatrick                     "SynthBlockInitExpr - captured block variable is not byref");
4502e5dd7070Spatrick             isNestedCapturedVar = true;
4503e5dd7070Spatrick             break;
4504e5dd7070Spatrick           }
4505e5dd7070Spatrick         }
4506e5dd7070Spatrick       // captured nested byref variable has its address passed. Do not take
4507e5dd7070Spatrick       // its address again.
4508e5dd7070Spatrick       if (!isNestedCapturedVar)
4509ec727ea7Spatrick         Exp = UnaryOperator::Create(
4510ec727ea7Spatrick             const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
4511a9ac8606Spatrick             Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary,
4512ec727ea7Spatrick             SourceLocation(), false, FPOptionsOverride());
4513e5dd7070Spatrick       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4514e5dd7070Spatrick       InitExprs.push_back(Exp);
4515e5dd7070Spatrick     }
4516e5dd7070Spatrick   }
4517e5dd7070Spatrick   if (ImportedBlockDecls.size()) {
4518e5dd7070Spatrick     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4519e5dd7070Spatrick     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4520e5dd7070Spatrick     unsigned IntSize =
4521e5dd7070Spatrick       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4522e5dd7070Spatrick     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4523e5dd7070Spatrick                                            Context->IntTy, SourceLocation());
4524e5dd7070Spatrick     InitExprs.push_back(FlagExp);
4525e5dd7070Spatrick   }
4526e5dd7070Spatrick   NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4527a9ac8606Spatrick                             SourceLocation(), FPOptionsOverride());
4528ec727ea7Spatrick   NewRep = UnaryOperator::Create(
4529ec727ea7Spatrick       const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
4530a9ac8606Spatrick       Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary,
4531ec727ea7Spatrick       SourceLocation(), false, FPOptionsOverride());
4532e5dd7070Spatrick   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4533e5dd7070Spatrick                                     NewRep);
4534e5dd7070Spatrick   BlockDeclRefs.clear();
4535e5dd7070Spatrick   BlockByRefDecls.clear();
4536e5dd7070Spatrick   BlockByRefDeclsPtrSet.clear();
4537e5dd7070Spatrick   BlockByCopyDecls.clear();
4538e5dd7070Spatrick   BlockByCopyDeclsPtrSet.clear();
4539e5dd7070Spatrick   ImportedBlockDecls.clear();
4540e5dd7070Spatrick   return NewRep;
4541e5dd7070Spatrick }
4542e5dd7070Spatrick 
IsDeclStmtInForeachHeader(DeclStmt * DS)4543e5dd7070Spatrick bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4544e5dd7070Spatrick   if (const ObjCForCollectionStmt * CS =
4545e5dd7070Spatrick       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4546e5dd7070Spatrick         return CS->getElement() == DS;
4547e5dd7070Spatrick   return false;
4548e5dd7070Spatrick }
4549e5dd7070Spatrick 
4550e5dd7070Spatrick //===----------------------------------------------------------------------===//
4551e5dd7070Spatrick // Function Body / Expression rewriting
4552e5dd7070Spatrick //===----------------------------------------------------------------------===//
4553e5dd7070Spatrick 
RewriteFunctionBodyOrGlobalInitializer(Stmt * S)4554e5dd7070Spatrick Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4555e5dd7070Spatrick   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4556e5dd7070Spatrick       isa<DoStmt>(S) || isa<ForStmt>(S))
4557e5dd7070Spatrick     Stmts.push_back(S);
4558e5dd7070Spatrick   else if (isa<ObjCForCollectionStmt>(S)) {
4559e5dd7070Spatrick     Stmts.push_back(S);
4560e5dd7070Spatrick     ObjCBcLabelNo.push_back(++BcLabelCount);
4561e5dd7070Spatrick   }
4562e5dd7070Spatrick 
4563e5dd7070Spatrick   // Pseudo-object operations and ivar references need special
4564e5dd7070Spatrick   // treatment because we're going to recursively rewrite them.
4565e5dd7070Spatrick   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4566e5dd7070Spatrick     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4567e5dd7070Spatrick       return RewritePropertyOrImplicitSetter(PseudoOp);
4568e5dd7070Spatrick     } else {
4569e5dd7070Spatrick       return RewritePropertyOrImplicitGetter(PseudoOp);
4570e5dd7070Spatrick     }
4571e5dd7070Spatrick   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4572e5dd7070Spatrick     return RewriteObjCIvarRefExpr(IvarRefExpr);
4573e5dd7070Spatrick   }
4574e5dd7070Spatrick 
4575e5dd7070Spatrick   SourceRange OrigStmtRange = S->getSourceRange();
4576e5dd7070Spatrick 
4577e5dd7070Spatrick   // Perform a bottom up rewrite of all children.
4578e5dd7070Spatrick   for (Stmt *&childStmt : S->children())
4579e5dd7070Spatrick     if (childStmt) {
4580e5dd7070Spatrick       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4581e5dd7070Spatrick       if (newStmt) {
4582e5dd7070Spatrick         childStmt = newStmt;
4583e5dd7070Spatrick       }
4584e5dd7070Spatrick     }
4585e5dd7070Spatrick 
4586e5dd7070Spatrick   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4587e5dd7070Spatrick     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4588e5dd7070Spatrick     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4589e5dd7070Spatrick     InnerContexts.insert(BE->getBlockDecl());
4590e5dd7070Spatrick     ImportedLocalExternalDecls.clear();
4591e5dd7070Spatrick     GetInnerBlockDeclRefExprs(BE->getBody(),
4592e5dd7070Spatrick                               InnerBlockDeclRefs, InnerContexts);
4593e5dd7070Spatrick     // Rewrite the block body in place.
4594e5dd7070Spatrick     Stmt *SaveCurrentBody = CurrentBody;
4595e5dd7070Spatrick     CurrentBody = BE->getBody();
4596e5dd7070Spatrick     PropParentMap = nullptr;
4597e5dd7070Spatrick     // block literal on rhs of a property-dot-sytax assignment
4598e5dd7070Spatrick     // must be replaced by its synthesize ast so getRewrittenText
4599e5dd7070Spatrick     // works as expected. In this case, what actually ends up on RHS
4600e5dd7070Spatrick     // is the blockTranscribed which is the helper function for the
4601e5dd7070Spatrick     // block literal; as in: self.c = ^() {[ace ARR];};
4602e5dd7070Spatrick     bool saveDisableReplaceStmt = DisableReplaceStmt;
4603e5dd7070Spatrick     DisableReplaceStmt = false;
4604e5dd7070Spatrick     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4605e5dd7070Spatrick     DisableReplaceStmt = saveDisableReplaceStmt;
4606e5dd7070Spatrick     CurrentBody = SaveCurrentBody;
4607e5dd7070Spatrick     PropParentMap = nullptr;
4608e5dd7070Spatrick     ImportedLocalExternalDecls.clear();
4609e5dd7070Spatrick     // Now we snarf the rewritten text and stash it away for later use.
4610e5dd7070Spatrick     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4611e5dd7070Spatrick     RewrittenBlockExprs[BE] = Str;
4612e5dd7070Spatrick 
4613e5dd7070Spatrick     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4614e5dd7070Spatrick 
4615e5dd7070Spatrick     //blockTranscribed->dump();
4616e5dd7070Spatrick     ReplaceStmt(S, blockTranscribed);
4617e5dd7070Spatrick     return blockTranscribed;
4618e5dd7070Spatrick   }
4619e5dd7070Spatrick   // Handle specific things.
4620e5dd7070Spatrick   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4621e5dd7070Spatrick     return RewriteAtEncode(AtEncode);
4622e5dd7070Spatrick 
4623e5dd7070Spatrick   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4624e5dd7070Spatrick     return RewriteAtSelector(AtSelector);
4625e5dd7070Spatrick 
4626e5dd7070Spatrick   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4627e5dd7070Spatrick     return RewriteObjCStringLiteral(AtString);
4628e5dd7070Spatrick 
4629e5dd7070Spatrick   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4630e5dd7070Spatrick #if 0
4631e5dd7070Spatrick     // Before we rewrite it, put the original message expression in a comment.
4632e5dd7070Spatrick     SourceLocation startLoc = MessExpr->getBeginLoc();
4633e5dd7070Spatrick     SourceLocation endLoc = MessExpr->getEndLoc();
4634e5dd7070Spatrick 
4635e5dd7070Spatrick     const char *startBuf = SM->getCharacterData(startLoc);
4636e5dd7070Spatrick     const char *endBuf = SM->getCharacterData(endLoc);
4637e5dd7070Spatrick 
4638e5dd7070Spatrick     std::string messString;
4639e5dd7070Spatrick     messString += "// ";
4640e5dd7070Spatrick     messString.append(startBuf, endBuf-startBuf+1);
4641e5dd7070Spatrick     messString += "\n";
4642e5dd7070Spatrick 
4643e5dd7070Spatrick     // FIXME: Missing definition of
4644e5dd7070Spatrick     // InsertText(clang::SourceLocation, char const*, unsigned int).
4645e5dd7070Spatrick     // InsertText(startLoc, messString);
4646e5dd7070Spatrick     // Tried this, but it didn't work either...
4647e5dd7070Spatrick     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4648e5dd7070Spatrick #endif
4649e5dd7070Spatrick     return RewriteMessageExpr(MessExpr);
4650e5dd7070Spatrick   }
4651e5dd7070Spatrick 
4652e5dd7070Spatrick   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4653e5dd7070Spatrick     return RewriteObjCTryStmt(StmtTry);
4654e5dd7070Spatrick 
4655e5dd7070Spatrick   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4656e5dd7070Spatrick     return RewriteObjCSynchronizedStmt(StmtTry);
4657e5dd7070Spatrick 
4658e5dd7070Spatrick   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4659e5dd7070Spatrick     return RewriteObjCThrowStmt(StmtThrow);
4660e5dd7070Spatrick 
4661e5dd7070Spatrick   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4662e5dd7070Spatrick     return RewriteObjCProtocolExpr(ProtocolExp);
4663e5dd7070Spatrick 
4664e5dd7070Spatrick   if (ObjCForCollectionStmt *StmtForCollection =
4665e5dd7070Spatrick         dyn_cast<ObjCForCollectionStmt>(S))
4666e5dd7070Spatrick     return RewriteObjCForCollectionStmt(StmtForCollection,
4667e5dd7070Spatrick                                         OrigStmtRange.getEnd());
4668e5dd7070Spatrick   if (BreakStmt *StmtBreakStmt =
4669e5dd7070Spatrick       dyn_cast<BreakStmt>(S))
4670e5dd7070Spatrick     return RewriteBreakStmt(StmtBreakStmt);
4671e5dd7070Spatrick   if (ContinueStmt *StmtContinueStmt =
4672e5dd7070Spatrick       dyn_cast<ContinueStmt>(S))
4673e5dd7070Spatrick     return RewriteContinueStmt(StmtContinueStmt);
4674e5dd7070Spatrick 
4675e5dd7070Spatrick   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4676e5dd7070Spatrick   // and cast exprs.
4677e5dd7070Spatrick   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4678e5dd7070Spatrick     // FIXME: What we're doing here is modifying the type-specifier that
4679e5dd7070Spatrick     // precedes the first Decl.  In the future the DeclGroup should have
4680e5dd7070Spatrick     // a separate type-specifier that we can rewrite.
4681e5dd7070Spatrick     // NOTE: We need to avoid rewriting the DeclStmt if it is within
4682e5dd7070Spatrick     // the context of an ObjCForCollectionStmt. For example:
4683e5dd7070Spatrick     //   NSArray *someArray;
4684e5dd7070Spatrick     //   for (id <FooProtocol> index in someArray) ;
4685e5dd7070Spatrick     // This is because RewriteObjCForCollectionStmt() does textual rewriting
4686e5dd7070Spatrick     // and it depends on the original text locations/positions.
4687e5dd7070Spatrick     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4688e5dd7070Spatrick       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4689e5dd7070Spatrick 
4690e5dd7070Spatrick     // Blocks rewrite rules.
4691e5dd7070Spatrick     for (auto *SD : DS->decls()) {
4692e5dd7070Spatrick       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4693e5dd7070Spatrick         if (isTopLevelBlockPointerType(ND->getType()))
4694e5dd7070Spatrick           RewriteBlockPointerDecl(ND);
4695e5dd7070Spatrick         else if (ND->getType()->isFunctionPointerType())
4696e5dd7070Spatrick           CheckFunctionPointerDecl(ND->getType(), ND);
4697e5dd7070Spatrick         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4698e5dd7070Spatrick           if (VD->hasAttr<BlocksAttr>()) {
4699e5dd7070Spatrick             static unsigned uniqueByrefDeclCount = 0;
4700e5dd7070Spatrick             assert(!BlockByRefDeclNo.count(ND) &&
4701e5dd7070Spatrick               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4702e5dd7070Spatrick             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4703e5dd7070Spatrick             RewriteByRefVar(VD);
4704e5dd7070Spatrick           }
4705e5dd7070Spatrick           else
4706e5dd7070Spatrick             RewriteTypeOfDecl(VD);
4707e5dd7070Spatrick         }
4708e5dd7070Spatrick       }
4709e5dd7070Spatrick       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4710e5dd7070Spatrick         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4711e5dd7070Spatrick           RewriteBlockPointerDecl(TD);
4712e5dd7070Spatrick         else if (TD->getUnderlyingType()->isFunctionPointerType())
4713e5dd7070Spatrick           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4714e5dd7070Spatrick       }
4715e5dd7070Spatrick     }
4716e5dd7070Spatrick   }
4717e5dd7070Spatrick 
4718e5dd7070Spatrick   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4719e5dd7070Spatrick     RewriteObjCQualifiedInterfaceTypes(CE);
4720e5dd7070Spatrick 
4721e5dd7070Spatrick   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4722e5dd7070Spatrick       isa<DoStmt>(S) || isa<ForStmt>(S)) {
4723e5dd7070Spatrick     assert(!Stmts.empty() && "Statement stack is empty");
4724e5dd7070Spatrick     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4725e5dd7070Spatrick              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4726e5dd7070Spatrick             && "Statement stack mismatch");
4727e5dd7070Spatrick     Stmts.pop_back();
4728e5dd7070Spatrick   }
4729e5dd7070Spatrick   // Handle blocks rewriting.
4730e5dd7070Spatrick   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4731e5dd7070Spatrick     ValueDecl *VD = DRE->getDecl();
4732e5dd7070Spatrick     if (VD->hasAttr<BlocksAttr>())
4733e5dd7070Spatrick       return RewriteBlockDeclRefExpr(DRE);
4734e5dd7070Spatrick     if (HasLocalVariableExternalStorage(VD))
4735e5dd7070Spatrick       return RewriteLocalVariableExternalStorage(DRE);
4736e5dd7070Spatrick   }
4737e5dd7070Spatrick 
4738e5dd7070Spatrick   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4739e5dd7070Spatrick     if (CE->getCallee()->getType()->isBlockPointerType()) {
4740e5dd7070Spatrick       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4741e5dd7070Spatrick       ReplaceStmt(S, BlockCall);
4742e5dd7070Spatrick       return BlockCall;
4743e5dd7070Spatrick     }
4744e5dd7070Spatrick   }
4745e5dd7070Spatrick   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4746e5dd7070Spatrick     RewriteCastExpr(CE);
4747e5dd7070Spatrick   }
4748e5dd7070Spatrick #if 0
4749e5dd7070Spatrick   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4750e5dd7070Spatrick     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4751e5dd7070Spatrick                                                    ICE->getSubExpr(),
4752e5dd7070Spatrick                                                    SourceLocation());
4753e5dd7070Spatrick     // Get the new text.
4754e5dd7070Spatrick     std::string SStr;
4755e5dd7070Spatrick     llvm::raw_string_ostream Buf(SStr);
4756e5dd7070Spatrick     Replacement->printPretty(Buf);
4757e5dd7070Spatrick     const std::string &Str = Buf.str();
4758e5dd7070Spatrick 
4759e5dd7070Spatrick     printf("CAST = %s\n", &Str[0]);
4760e5dd7070Spatrick     InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
4761e5dd7070Spatrick     delete S;
4762e5dd7070Spatrick     return Replacement;
4763e5dd7070Spatrick   }
4764e5dd7070Spatrick #endif
4765e5dd7070Spatrick   // Return this stmt unmodified.
4766e5dd7070Spatrick   return S;
4767e5dd7070Spatrick }
4768e5dd7070Spatrick 
RewriteRecordBody(RecordDecl * RD)4769e5dd7070Spatrick void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4770e5dd7070Spatrick   for (auto *FD : RD->fields()) {
4771e5dd7070Spatrick     if (isTopLevelBlockPointerType(FD->getType()))
4772e5dd7070Spatrick       RewriteBlockPointerDecl(FD);
4773e5dd7070Spatrick     if (FD->getType()->isObjCQualifiedIdType() ||
4774e5dd7070Spatrick         FD->getType()->isObjCQualifiedInterfaceType())
4775e5dd7070Spatrick       RewriteObjCQualifiedInterfaceTypes(FD);
4776e5dd7070Spatrick   }
4777e5dd7070Spatrick }
4778e5dd7070Spatrick 
4779e5dd7070Spatrick /// HandleDeclInMainFile - This is called for each top-level decl defined in the
4780e5dd7070Spatrick /// main file of the input.
HandleDeclInMainFile(Decl * D)4781e5dd7070Spatrick void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4782e5dd7070Spatrick   switch (D->getKind()) {
4783e5dd7070Spatrick     case Decl::Function: {
4784e5dd7070Spatrick       FunctionDecl *FD = cast<FunctionDecl>(D);
4785e5dd7070Spatrick       if (FD->isOverloadedOperator())
4786e5dd7070Spatrick         return;
4787e5dd7070Spatrick 
4788e5dd7070Spatrick       // Since function prototypes don't have ParmDecl's, we check the function
4789e5dd7070Spatrick       // prototype. This enables us to rewrite function declarations and
4790e5dd7070Spatrick       // definitions using the same code.
4791e5dd7070Spatrick       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4792e5dd7070Spatrick 
4793e5dd7070Spatrick       if (!FD->isThisDeclarationADefinition())
4794e5dd7070Spatrick         break;
4795e5dd7070Spatrick 
4796e5dd7070Spatrick       // FIXME: If this should support Obj-C++, support CXXTryStmt
4797e5dd7070Spatrick       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4798e5dd7070Spatrick         CurFunctionDef = FD;
4799e5dd7070Spatrick         CurFunctionDeclToDeclareForBlock = FD;
4800e5dd7070Spatrick         CurrentBody = Body;
4801e5dd7070Spatrick         Body =
4802e5dd7070Spatrick         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4803e5dd7070Spatrick         FD->setBody(Body);
4804e5dd7070Spatrick         CurrentBody = nullptr;
4805e5dd7070Spatrick         if (PropParentMap) {
4806e5dd7070Spatrick           delete PropParentMap;
4807e5dd7070Spatrick           PropParentMap = nullptr;
4808e5dd7070Spatrick         }
4809e5dd7070Spatrick         // This synthesizes and inserts the block "impl" struct, invoke function,
4810e5dd7070Spatrick         // and any copy/dispose helper functions.
4811e5dd7070Spatrick         InsertBlockLiteralsWithinFunction(FD);
4812e5dd7070Spatrick         CurFunctionDef = nullptr;
4813e5dd7070Spatrick         CurFunctionDeclToDeclareForBlock = nullptr;
4814e5dd7070Spatrick       }
4815e5dd7070Spatrick       break;
4816e5dd7070Spatrick     }
4817e5dd7070Spatrick     case Decl::ObjCMethod: {
4818e5dd7070Spatrick       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4819e5dd7070Spatrick       if (CompoundStmt *Body = MD->getCompoundBody()) {
4820e5dd7070Spatrick         CurMethodDef = MD;
4821e5dd7070Spatrick         CurrentBody = Body;
4822e5dd7070Spatrick         Body =
4823e5dd7070Spatrick           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4824e5dd7070Spatrick         MD->setBody(Body);
4825e5dd7070Spatrick         CurrentBody = nullptr;
4826e5dd7070Spatrick         if (PropParentMap) {
4827e5dd7070Spatrick           delete PropParentMap;
4828e5dd7070Spatrick           PropParentMap = nullptr;
4829e5dd7070Spatrick         }
4830e5dd7070Spatrick         InsertBlockLiteralsWithinMethod(MD);
4831e5dd7070Spatrick         CurMethodDef = nullptr;
4832e5dd7070Spatrick       }
4833e5dd7070Spatrick       break;
4834e5dd7070Spatrick     }
4835e5dd7070Spatrick     case Decl::ObjCImplementation: {
4836e5dd7070Spatrick       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4837e5dd7070Spatrick       ClassImplementation.push_back(CI);
4838e5dd7070Spatrick       break;
4839e5dd7070Spatrick     }
4840e5dd7070Spatrick     case Decl::ObjCCategoryImpl: {
4841e5dd7070Spatrick       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4842e5dd7070Spatrick       CategoryImplementation.push_back(CI);
4843e5dd7070Spatrick       break;
4844e5dd7070Spatrick     }
4845e5dd7070Spatrick     case Decl::Var: {
4846e5dd7070Spatrick       VarDecl *VD = cast<VarDecl>(D);
4847e5dd7070Spatrick       RewriteObjCQualifiedInterfaceTypes(VD);
4848e5dd7070Spatrick       if (isTopLevelBlockPointerType(VD->getType()))
4849e5dd7070Spatrick         RewriteBlockPointerDecl(VD);
4850e5dd7070Spatrick       else if (VD->getType()->isFunctionPointerType()) {
4851e5dd7070Spatrick         CheckFunctionPointerDecl(VD->getType(), VD);
4852e5dd7070Spatrick         if (VD->getInit()) {
4853e5dd7070Spatrick           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4854e5dd7070Spatrick             RewriteCastExpr(CE);
4855e5dd7070Spatrick           }
4856e5dd7070Spatrick         }
4857e5dd7070Spatrick       } else if (VD->getType()->isRecordType()) {
4858e5dd7070Spatrick         RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
4859e5dd7070Spatrick         if (RD->isCompleteDefinition())
4860e5dd7070Spatrick           RewriteRecordBody(RD);
4861e5dd7070Spatrick       }
4862e5dd7070Spatrick       if (VD->getInit()) {
4863e5dd7070Spatrick         GlobalVarDecl = VD;
4864e5dd7070Spatrick         CurrentBody = VD->getInit();
4865e5dd7070Spatrick         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4866e5dd7070Spatrick         CurrentBody = nullptr;
4867e5dd7070Spatrick         if (PropParentMap) {
4868e5dd7070Spatrick           delete PropParentMap;
4869e5dd7070Spatrick           PropParentMap = nullptr;
4870e5dd7070Spatrick         }
4871e5dd7070Spatrick         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4872e5dd7070Spatrick         GlobalVarDecl = nullptr;
4873e5dd7070Spatrick 
4874e5dd7070Spatrick         // This is needed for blocks.
4875e5dd7070Spatrick         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4876e5dd7070Spatrick             RewriteCastExpr(CE);
4877e5dd7070Spatrick         }
4878e5dd7070Spatrick       }
4879e5dd7070Spatrick       break;
4880e5dd7070Spatrick     }
4881e5dd7070Spatrick     case Decl::TypeAlias:
4882e5dd7070Spatrick     case Decl::Typedef: {
4883e5dd7070Spatrick       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4884e5dd7070Spatrick         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4885e5dd7070Spatrick           RewriteBlockPointerDecl(TD);
4886e5dd7070Spatrick         else if (TD->getUnderlyingType()->isFunctionPointerType())
4887e5dd7070Spatrick           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4888e5dd7070Spatrick       }
4889e5dd7070Spatrick       break;
4890e5dd7070Spatrick     }
4891e5dd7070Spatrick     case Decl::CXXRecord:
4892e5dd7070Spatrick     case Decl::Record: {
4893e5dd7070Spatrick       RecordDecl *RD = cast<RecordDecl>(D);
4894e5dd7070Spatrick       if (RD->isCompleteDefinition())
4895e5dd7070Spatrick         RewriteRecordBody(RD);
4896e5dd7070Spatrick       break;
4897e5dd7070Spatrick     }
4898e5dd7070Spatrick     default:
4899e5dd7070Spatrick       break;
4900e5dd7070Spatrick   }
4901e5dd7070Spatrick   // Nothing yet.
4902e5dd7070Spatrick }
4903e5dd7070Spatrick 
HandleTranslationUnit(ASTContext & C)4904e5dd7070Spatrick void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4905e5dd7070Spatrick   if (Diags.hasErrorOccurred())
4906e5dd7070Spatrick     return;
4907e5dd7070Spatrick 
4908e5dd7070Spatrick   RewriteInclude();
4909e5dd7070Spatrick 
4910e5dd7070Spatrick   // Here's a great place to add any extra declarations that may be needed.
4911e5dd7070Spatrick   // Write out meta data for each @protocol(<expr>).
4912e5dd7070Spatrick   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4913e5dd7070Spatrick     RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4914e5dd7070Spatrick 
4915e5dd7070Spatrick   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4916e5dd7070Spatrick   if (ClassImplementation.size() || CategoryImplementation.size())
4917e5dd7070Spatrick     RewriteImplementations();
4918e5dd7070Spatrick 
4919e5dd7070Spatrick   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4920e5dd7070Spatrick   // we are done.
4921e5dd7070Spatrick   if (const RewriteBuffer *RewriteBuf =
4922e5dd7070Spatrick       Rewrite.getRewriteBufferFor(MainFileID)) {
4923e5dd7070Spatrick     //printf("Changed:\n");
4924e5dd7070Spatrick     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4925e5dd7070Spatrick   } else {
4926e5dd7070Spatrick     llvm::errs() << "No changes\n";
4927e5dd7070Spatrick   }
4928e5dd7070Spatrick 
4929e5dd7070Spatrick   if (ClassImplementation.size() || CategoryImplementation.size() ||
4930e5dd7070Spatrick       ProtocolExprDecls.size()) {
4931e5dd7070Spatrick     // Rewrite Objective-c meta data*
4932e5dd7070Spatrick     std::string ResultStr;
4933e5dd7070Spatrick     RewriteMetaDataIntoBuffer(ResultStr);
4934e5dd7070Spatrick     // Emit metadata.
4935e5dd7070Spatrick     *OutFile << ResultStr;
4936e5dd7070Spatrick   }
4937e5dd7070Spatrick   OutFile->flush();
4938e5dd7070Spatrick }
4939e5dd7070Spatrick 
Initialize(ASTContext & context)4940e5dd7070Spatrick void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4941e5dd7070Spatrick   InitializeCommon(context);
4942e5dd7070Spatrick 
4943e5dd7070Spatrick   // declaring objc_selector outside the parameter list removes a silly
4944e5dd7070Spatrick   // scope related warning...
4945e5dd7070Spatrick   if (IsHeader)
4946e5dd7070Spatrick     Preamble = "#pragma once\n";
4947e5dd7070Spatrick   Preamble += "struct objc_selector; struct objc_class;\n";
4948e5dd7070Spatrick   Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4949e5dd7070Spatrick   Preamble += "struct objc_object *superClass; ";
4950e5dd7070Spatrick   if (LangOpts.MicrosoftExt) {
4951e5dd7070Spatrick     // Add a constructor for creating temporary objects.
4952e5dd7070Spatrick     Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4953e5dd7070Spatrick     ": ";
4954e5dd7070Spatrick     Preamble += "object(o), superClass(s) {} ";
4955e5dd7070Spatrick   }
4956e5dd7070Spatrick   Preamble += "};\n";
4957e5dd7070Spatrick   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4958e5dd7070Spatrick   Preamble += "typedef struct objc_object Protocol;\n";
4959e5dd7070Spatrick   Preamble += "#define _REWRITER_typedef_Protocol\n";
4960e5dd7070Spatrick   Preamble += "#endif\n";
4961e5dd7070Spatrick   if (LangOpts.MicrosoftExt) {
4962e5dd7070Spatrick     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4963e5dd7070Spatrick     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4964e5dd7070Spatrick   } else
4965e5dd7070Spatrick     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4966e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4967e5dd7070Spatrick   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4968e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4969e5dd7070Spatrick   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4970e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4971e5dd7070Spatrick   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4972e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4973e5dd7070Spatrick   Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4974e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4975e5dd7070Spatrick   Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4976e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4977e5dd7070Spatrick   Preamble += "(const char *);\n";
4978e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4979e5dd7070Spatrick   Preamble += "(struct objc_class *);\n";
4980e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4981e5dd7070Spatrick   Preamble += "(const char *);\n";
4982e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4983e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4984e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4985e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4986e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4987e5dd7070Spatrick   Preamble += "(struct objc_class *, struct objc_object *);\n";
4988e5dd7070Spatrick   // @synchronized hooks.
4989e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4990e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4991e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4992e5dd7070Spatrick   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4993e5dd7070Spatrick   Preamble += "struct __objcFastEnumerationState {\n\t";
4994e5dd7070Spatrick   Preamble += "unsigned long state;\n\t";
4995e5dd7070Spatrick   Preamble += "void **itemsPtr;\n\t";
4996e5dd7070Spatrick   Preamble += "unsigned long *mutationsPtr;\n\t";
4997e5dd7070Spatrick   Preamble += "unsigned long extra[5];\n};\n";
4998e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
4999e5dd7070Spatrick   Preamble += "#define __FASTENUMERATIONSTATE\n";
5000e5dd7070Spatrick   Preamble += "#endif\n";
5001e5dd7070Spatrick   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5002e5dd7070Spatrick   Preamble += "struct __NSConstantStringImpl {\n";
5003e5dd7070Spatrick   Preamble += "  int *isa;\n";
5004e5dd7070Spatrick   Preamble += "  int flags;\n";
5005e5dd7070Spatrick   Preamble += "  char *str;\n";
5006e5dd7070Spatrick   Preamble += "  long length;\n";
5007e5dd7070Spatrick   Preamble += "};\n";
5008e5dd7070Spatrick   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5009e5dd7070Spatrick   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5010e5dd7070Spatrick   Preamble += "#else\n";
5011e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5012e5dd7070Spatrick   Preamble += "#endif\n";
5013e5dd7070Spatrick   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5014e5dd7070Spatrick   Preamble += "#endif\n";
5015e5dd7070Spatrick   // Blocks preamble.
5016e5dd7070Spatrick   Preamble += "#ifndef BLOCK_IMPL\n";
5017e5dd7070Spatrick   Preamble += "#define BLOCK_IMPL\n";
5018e5dd7070Spatrick   Preamble += "struct __block_impl {\n";
5019e5dd7070Spatrick   Preamble += "  void *isa;\n";
5020e5dd7070Spatrick   Preamble += "  int Flags;\n";
5021e5dd7070Spatrick   Preamble += "  int Reserved;\n";
5022e5dd7070Spatrick   Preamble += "  void *FuncPtr;\n";
5023e5dd7070Spatrick   Preamble += "};\n";
5024e5dd7070Spatrick   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5025e5dd7070Spatrick   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5026e5dd7070Spatrick   Preamble += "extern \"C\" __declspec(dllexport) "
5027e5dd7070Spatrick   "void _Block_object_assign(void *, const void *, const int);\n";
5028e5dd7070Spatrick   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5029e5dd7070Spatrick   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5030e5dd7070Spatrick   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5031e5dd7070Spatrick   Preamble += "#else\n";
5032e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5033e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5034e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5035e5dd7070Spatrick   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5036e5dd7070Spatrick   Preamble += "#endif\n";
5037e5dd7070Spatrick   Preamble += "#endif\n";
5038e5dd7070Spatrick   if (LangOpts.MicrosoftExt) {
5039e5dd7070Spatrick     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5040e5dd7070Spatrick     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5041e5dd7070Spatrick     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5042e5dd7070Spatrick     Preamble += "#define __attribute__(X)\n";
5043e5dd7070Spatrick     Preamble += "#endif\n";
5044e5dd7070Spatrick     Preamble += "#define __weak\n";
5045e5dd7070Spatrick   }
5046e5dd7070Spatrick   else {
5047e5dd7070Spatrick     Preamble += "#define __block\n";
5048e5dd7070Spatrick     Preamble += "#define __weak\n";
5049e5dd7070Spatrick   }
5050e5dd7070Spatrick   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5051e5dd7070Spatrick   // as this avoids warning in any 64bit/32bit compilation model.
5052e5dd7070Spatrick   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5053e5dd7070Spatrick }
5054e5dd7070Spatrick 
5055e5dd7070Spatrick /// RewriteIvarOffsetComputation - This routine synthesizes computation of
5056e5dd7070Spatrick /// ivar offset.
RewriteIvarOffsetComputation(ObjCIvarDecl * ivar,std::string & Result)5057e5dd7070Spatrick void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5058e5dd7070Spatrick                                                          std::string &Result) {
5059e5dd7070Spatrick   if (ivar->isBitField()) {
5060e5dd7070Spatrick     // FIXME: The hack below doesn't work for bitfields. For now, we simply
5061e5dd7070Spatrick     // place all bitfields at offset 0.
5062e5dd7070Spatrick     Result += "0";
5063e5dd7070Spatrick   } else {
5064e5dd7070Spatrick     Result += "__OFFSETOFIVAR__(struct ";
5065e5dd7070Spatrick     Result += ivar->getContainingInterface()->getNameAsString();
5066e5dd7070Spatrick     if (LangOpts.MicrosoftExt)
5067e5dd7070Spatrick       Result += "_IMPL";
5068e5dd7070Spatrick     Result += ", ";
5069e5dd7070Spatrick     Result += ivar->getNameAsString();
5070e5dd7070Spatrick     Result += ")";
5071e5dd7070Spatrick   }
5072e5dd7070Spatrick }
5073e5dd7070Spatrick 
5074e5dd7070Spatrick /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
RewriteObjCProtocolMetaData(ObjCProtocolDecl * PDecl,StringRef prefix,StringRef ClassName,std::string & Result)5075e5dd7070Spatrick void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5076e5dd7070Spatrick                             ObjCProtocolDecl *PDecl, StringRef prefix,
5077e5dd7070Spatrick                             StringRef ClassName, std::string &Result) {
5078e5dd7070Spatrick   static bool objc_protocol_methods = false;
5079e5dd7070Spatrick 
5080e5dd7070Spatrick   // Output struct protocol_methods holder of method selector and type.
5081e5dd7070Spatrick   if (!objc_protocol_methods && PDecl->hasDefinition()) {
5082e5dd7070Spatrick     /* struct protocol_methods {
5083e5dd7070Spatrick      SEL _cmd;
5084e5dd7070Spatrick      char *method_types;
5085e5dd7070Spatrick      }
5086e5dd7070Spatrick      */
5087e5dd7070Spatrick     Result += "\nstruct _protocol_methods {\n";
5088e5dd7070Spatrick     Result += "\tstruct objc_selector *_cmd;\n";
5089e5dd7070Spatrick     Result += "\tchar *method_types;\n";
5090e5dd7070Spatrick     Result += "};\n";
5091e5dd7070Spatrick 
5092e5dd7070Spatrick     objc_protocol_methods = true;
5093e5dd7070Spatrick   }
5094e5dd7070Spatrick   // Do not synthesize the protocol more than once.
5095e5dd7070Spatrick   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5096e5dd7070Spatrick     return;
5097e5dd7070Spatrick 
5098e5dd7070Spatrick   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5099e5dd7070Spatrick     PDecl = Def;
5100e5dd7070Spatrick 
5101e5dd7070Spatrick   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5102e5dd7070Spatrick     unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5103e5dd7070Spatrick                                         PDecl->instmeth_end());
5104e5dd7070Spatrick     /* struct _objc_protocol_method_list {
5105e5dd7070Spatrick      int protocol_method_count;
5106e5dd7070Spatrick      struct protocol_methods protocols[];
5107e5dd7070Spatrick      }
5108e5dd7070Spatrick      */
5109e5dd7070Spatrick     Result += "\nstatic struct {\n";
5110e5dd7070Spatrick     Result += "\tint protocol_method_count;\n";
5111e5dd7070Spatrick     Result += "\tstruct _protocol_methods protocol_methods[";
5112e5dd7070Spatrick     Result += utostr(NumMethods);
5113e5dd7070Spatrick     Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5114e5dd7070Spatrick     Result += PDecl->getNameAsString();
5115e5dd7070Spatrick     Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5116e5dd7070Spatrick     "{\n\t" + utostr(NumMethods) + "\n";
5117e5dd7070Spatrick 
5118e5dd7070Spatrick     // Output instance methods declared in this protocol.
5119e5dd7070Spatrick     for (ObjCProtocolDecl::instmeth_iterator
5120e5dd7070Spatrick          I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5121e5dd7070Spatrick          I != E; ++I) {
5122e5dd7070Spatrick       if (I == PDecl->instmeth_begin())
5123e5dd7070Spatrick         Result += "\t  ,{{(struct objc_selector *)\"";
5124e5dd7070Spatrick       else
5125e5dd7070Spatrick         Result += "\t  ,{(struct objc_selector *)\"";
5126e5dd7070Spatrick       Result += (*I)->getSelector().getAsString();
5127e5dd7070Spatrick       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5128e5dd7070Spatrick       Result += "\", \"";
5129e5dd7070Spatrick       Result += MethodTypeString;
5130e5dd7070Spatrick       Result += "\"}\n";
5131e5dd7070Spatrick     }
5132e5dd7070Spatrick     Result += "\t }\n};\n";
5133e5dd7070Spatrick   }
5134e5dd7070Spatrick 
5135e5dd7070Spatrick   // Output class methods declared in this protocol.
5136e5dd7070Spatrick   unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5137e5dd7070Spatrick                                       PDecl->classmeth_end());
5138e5dd7070Spatrick   if (NumMethods > 0) {
5139e5dd7070Spatrick     /* struct _objc_protocol_method_list {
5140e5dd7070Spatrick      int protocol_method_count;
5141e5dd7070Spatrick      struct protocol_methods protocols[];
5142e5dd7070Spatrick      }
5143e5dd7070Spatrick      */
5144e5dd7070Spatrick     Result += "\nstatic struct {\n";
5145e5dd7070Spatrick     Result += "\tint protocol_method_count;\n";
5146e5dd7070Spatrick     Result += "\tstruct _protocol_methods protocol_methods[";
5147e5dd7070Spatrick     Result += utostr(NumMethods);
5148e5dd7070Spatrick     Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5149e5dd7070Spatrick     Result += PDecl->getNameAsString();
5150e5dd7070Spatrick     Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5151e5dd7070Spatrick     "{\n\t";
5152e5dd7070Spatrick     Result += utostr(NumMethods);
5153e5dd7070Spatrick     Result += "\n";
5154e5dd7070Spatrick 
5155e5dd7070Spatrick     // Output instance methods declared in this protocol.
5156e5dd7070Spatrick     for (ObjCProtocolDecl::classmeth_iterator
5157e5dd7070Spatrick          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5158e5dd7070Spatrick          I != E; ++I) {
5159e5dd7070Spatrick       if (I == PDecl->classmeth_begin())
5160e5dd7070Spatrick         Result += "\t  ,{{(struct objc_selector *)\"";
5161e5dd7070Spatrick       else
5162e5dd7070Spatrick         Result += "\t  ,{(struct objc_selector *)\"";
5163e5dd7070Spatrick       Result += (*I)->getSelector().getAsString();
5164e5dd7070Spatrick       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5165e5dd7070Spatrick       Result += "\", \"";
5166e5dd7070Spatrick       Result += MethodTypeString;
5167e5dd7070Spatrick       Result += "\"}\n";
5168e5dd7070Spatrick     }
5169e5dd7070Spatrick     Result += "\t }\n};\n";
5170e5dd7070Spatrick   }
5171e5dd7070Spatrick 
5172e5dd7070Spatrick   // Output:
5173e5dd7070Spatrick   /* struct _objc_protocol {
5174e5dd7070Spatrick    // Objective-C 1.0 extensions
5175e5dd7070Spatrick    struct _objc_protocol_extension *isa;
5176e5dd7070Spatrick    char *protocol_name;
5177e5dd7070Spatrick    struct _objc_protocol **protocol_list;
5178e5dd7070Spatrick    struct _objc_protocol_method_list *instance_methods;
5179e5dd7070Spatrick    struct _objc_protocol_method_list *class_methods;
5180e5dd7070Spatrick    };
5181e5dd7070Spatrick    */
5182e5dd7070Spatrick   static bool objc_protocol = false;
5183e5dd7070Spatrick   if (!objc_protocol) {
5184e5dd7070Spatrick     Result += "\nstruct _objc_protocol {\n";
5185e5dd7070Spatrick     Result += "\tstruct _objc_protocol_extension *isa;\n";
5186e5dd7070Spatrick     Result += "\tchar *protocol_name;\n";
5187e5dd7070Spatrick     Result += "\tstruct _objc_protocol **protocol_list;\n";
5188e5dd7070Spatrick     Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5189e5dd7070Spatrick     Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5190e5dd7070Spatrick     Result += "};\n";
5191e5dd7070Spatrick 
5192e5dd7070Spatrick     objc_protocol = true;
5193e5dd7070Spatrick   }
5194e5dd7070Spatrick 
5195e5dd7070Spatrick   Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5196e5dd7070Spatrick   Result += PDecl->getNameAsString();
5197e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5198e5dd7070Spatrick   "{\n\t0, \"";
5199e5dd7070Spatrick   Result += PDecl->getNameAsString();
5200e5dd7070Spatrick   Result += "\", 0, ";
5201e5dd7070Spatrick   if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5202e5dd7070Spatrick     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5203e5dd7070Spatrick     Result += PDecl->getNameAsString();
5204e5dd7070Spatrick     Result += ", ";
5205e5dd7070Spatrick   }
5206e5dd7070Spatrick   else
5207e5dd7070Spatrick     Result += "0, ";
5208e5dd7070Spatrick   if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5209e5dd7070Spatrick     Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5210e5dd7070Spatrick     Result += PDecl->getNameAsString();
5211e5dd7070Spatrick     Result += "\n";
5212e5dd7070Spatrick   }
5213e5dd7070Spatrick   else
5214e5dd7070Spatrick     Result += "0\n";
5215e5dd7070Spatrick   Result += "};\n";
5216e5dd7070Spatrick 
5217e5dd7070Spatrick   // Mark this protocol as having been generated.
5218e5dd7070Spatrick   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5219e5dd7070Spatrick     llvm_unreachable("protocol already synthesized");
5220e5dd7070Spatrick }
5221e5dd7070Spatrick 
RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> & Protocols,StringRef prefix,StringRef ClassName,std::string & Result)5222e5dd7070Spatrick void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5223e5dd7070Spatrick                                 const ObjCList<ObjCProtocolDecl> &Protocols,
5224e5dd7070Spatrick                                 StringRef prefix, StringRef ClassName,
5225e5dd7070Spatrick                                 std::string &Result) {
5226e5dd7070Spatrick   if (Protocols.empty()) return;
5227e5dd7070Spatrick 
5228e5dd7070Spatrick   for (unsigned i = 0; i != Protocols.size(); i++)
5229e5dd7070Spatrick     RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5230e5dd7070Spatrick 
5231e5dd7070Spatrick   // Output the top lovel protocol meta-data for the class.
5232e5dd7070Spatrick   /* struct _objc_protocol_list {
5233e5dd7070Spatrick    struct _objc_protocol_list *next;
5234e5dd7070Spatrick    int    protocol_count;
5235e5dd7070Spatrick    struct _objc_protocol *class_protocols[];
5236e5dd7070Spatrick    }
5237e5dd7070Spatrick    */
5238e5dd7070Spatrick   Result += "\nstatic struct {\n";
5239e5dd7070Spatrick   Result += "\tstruct _objc_protocol_list *next;\n";
5240e5dd7070Spatrick   Result += "\tint    protocol_count;\n";
5241e5dd7070Spatrick   Result += "\tstruct _objc_protocol *class_protocols[";
5242e5dd7070Spatrick   Result += utostr(Protocols.size());
5243e5dd7070Spatrick   Result += "];\n} _OBJC_";
5244e5dd7070Spatrick   Result += prefix;
5245e5dd7070Spatrick   Result += "_PROTOCOLS_";
5246e5dd7070Spatrick   Result += ClassName;
5247e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5248e5dd7070Spatrick   "{\n\t0, ";
5249e5dd7070Spatrick   Result += utostr(Protocols.size());
5250e5dd7070Spatrick   Result += "\n";
5251e5dd7070Spatrick 
5252e5dd7070Spatrick   Result += "\t,{&_OBJC_PROTOCOL_";
5253e5dd7070Spatrick   Result += Protocols[0]->getNameAsString();
5254e5dd7070Spatrick   Result += " \n";
5255e5dd7070Spatrick 
5256e5dd7070Spatrick   for (unsigned i = 1; i != Protocols.size(); i++) {
5257e5dd7070Spatrick     Result += "\t ,&_OBJC_PROTOCOL_";
5258e5dd7070Spatrick     Result += Protocols[i]->getNameAsString();
5259e5dd7070Spatrick     Result += "\n";
5260e5dd7070Spatrick   }
5261e5dd7070Spatrick   Result += "\t }\n};\n";
5262e5dd7070Spatrick }
5263e5dd7070Spatrick 
RewriteObjCClassMetaData(ObjCImplementationDecl * IDecl,std::string & Result)5264e5dd7070Spatrick void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5265e5dd7070Spatrick                                            std::string &Result) {
5266e5dd7070Spatrick   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5267e5dd7070Spatrick 
5268e5dd7070Spatrick   // Explicitly declared @interface's are already synthesized.
5269e5dd7070Spatrick   if (CDecl->isImplicitInterfaceDecl()) {
5270e5dd7070Spatrick     // FIXME: Implementation of a class with no @interface (legacy) does not
5271e5dd7070Spatrick     // produce correct synthesis as yet.
5272e5dd7070Spatrick     RewriteObjCInternalStruct(CDecl, Result);
5273e5dd7070Spatrick   }
5274e5dd7070Spatrick 
5275e5dd7070Spatrick   // Build _objc_ivar_list metadata for classes ivars if needed
5276a9ac8606Spatrick   unsigned NumIvars =
5277a9ac8606Spatrick       !IDecl->ivar_empty() ? IDecl->ivar_size() : CDecl->ivar_size();
5278e5dd7070Spatrick   if (NumIvars > 0) {
5279e5dd7070Spatrick     static bool objc_ivar = false;
5280e5dd7070Spatrick     if (!objc_ivar) {
5281e5dd7070Spatrick       /* struct _objc_ivar {
5282e5dd7070Spatrick        char *ivar_name;
5283e5dd7070Spatrick        char *ivar_type;
5284e5dd7070Spatrick        int ivar_offset;
5285e5dd7070Spatrick        };
5286e5dd7070Spatrick        */
5287e5dd7070Spatrick       Result += "\nstruct _objc_ivar {\n";
5288e5dd7070Spatrick       Result += "\tchar *ivar_name;\n";
5289e5dd7070Spatrick       Result += "\tchar *ivar_type;\n";
5290e5dd7070Spatrick       Result += "\tint ivar_offset;\n";
5291e5dd7070Spatrick       Result += "};\n";
5292e5dd7070Spatrick 
5293e5dd7070Spatrick       objc_ivar = true;
5294e5dd7070Spatrick     }
5295e5dd7070Spatrick 
5296e5dd7070Spatrick     /* struct {
5297e5dd7070Spatrick      int ivar_count;
5298e5dd7070Spatrick      struct _objc_ivar ivar_list[nIvars];
5299e5dd7070Spatrick      };
5300e5dd7070Spatrick      */
5301e5dd7070Spatrick     Result += "\nstatic struct {\n";
5302e5dd7070Spatrick     Result += "\tint ivar_count;\n";
5303e5dd7070Spatrick     Result += "\tstruct _objc_ivar ivar_list[";
5304e5dd7070Spatrick     Result += utostr(NumIvars);
5305e5dd7070Spatrick     Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5306e5dd7070Spatrick     Result += IDecl->getNameAsString();
5307e5dd7070Spatrick     Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5308e5dd7070Spatrick     "{\n\t";
5309e5dd7070Spatrick     Result += utostr(NumIvars);
5310e5dd7070Spatrick     Result += "\n";
5311e5dd7070Spatrick 
5312e5dd7070Spatrick     ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5313e5dd7070Spatrick     SmallVector<ObjCIvarDecl *, 8> IVars;
5314e5dd7070Spatrick     if (!IDecl->ivar_empty()) {
5315e5dd7070Spatrick       for (auto *IV : IDecl->ivars())
5316e5dd7070Spatrick         IVars.push_back(IV);
5317e5dd7070Spatrick       IVI = IDecl->ivar_begin();
5318e5dd7070Spatrick       IVE = IDecl->ivar_end();
5319e5dd7070Spatrick     } else {
5320e5dd7070Spatrick       IVI = CDecl->ivar_begin();
5321e5dd7070Spatrick       IVE = CDecl->ivar_end();
5322e5dd7070Spatrick     }
5323e5dd7070Spatrick     Result += "\t,{{\"";
5324e5dd7070Spatrick     Result += IVI->getNameAsString();
5325e5dd7070Spatrick     Result += "\", \"";
5326e5dd7070Spatrick     std::string TmpString, StrEncoding;
5327e5dd7070Spatrick     Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5328e5dd7070Spatrick     QuoteDoublequotes(TmpString, StrEncoding);
5329e5dd7070Spatrick     Result += StrEncoding;
5330e5dd7070Spatrick     Result += "\", ";
5331e5dd7070Spatrick     RewriteIvarOffsetComputation(*IVI, Result);
5332e5dd7070Spatrick     Result += "}\n";
5333e5dd7070Spatrick     for (++IVI; IVI != IVE; ++IVI) {
5334e5dd7070Spatrick       Result += "\t  ,{\"";
5335e5dd7070Spatrick       Result += IVI->getNameAsString();
5336e5dd7070Spatrick       Result += "\", \"";
5337e5dd7070Spatrick       std::string TmpString, StrEncoding;
5338e5dd7070Spatrick       Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5339e5dd7070Spatrick       QuoteDoublequotes(TmpString, StrEncoding);
5340e5dd7070Spatrick       Result += StrEncoding;
5341e5dd7070Spatrick       Result += "\", ";
5342e5dd7070Spatrick       RewriteIvarOffsetComputation(*IVI, Result);
5343e5dd7070Spatrick       Result += "}\n";
5344e5dd7070Spatrick     }
5345e5dd7070Spatrick 
5346e5dd7070Spatrick     Result += "\t }\n};\n";
5347e5dd7070Spatrick   }
5348e5dd7070Spatrick 
5349e5dd7070Spatrick   // Build _objc_method_list for class's instance methods if needed
5350e5dd7070Spatrick   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5351e5dd7070Spatrick 
5352e5dd7070Spatrick   // If any of our property implementations have associated getters or
5353e5dd7070Spatrick   // setters, produce metadata for them as well.
5354e5dd7070Spatrick   for (const auto *Prop : IDecl->property_impls()) {
5355e5dd7070Spatrick     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5356e5dd7070Spatrick       continue;
5357e5dd7070Spatrick     if (!Prop->getPropertyIvarDecl())
5358e5dd7070Spatrick       continue;
5359e5dd7070Spatrick     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5360e5dd7070Spatrick     if (!PD)
5361e5dd7070Spatrick       continue;
5362e5dd7070Spatrick     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
5363e5dd7070Spatrick       if (!Getter->isDefined())
5364e5dd7070Spatrick         InstanceMethods.push_back(Getter);
5365e5dd7070Spatrick     if (PD->isReadOnly())
5366e5dd7070Spatrick       continue;
5367e5dd7070Spatrick     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
5368e5dd7070Spatrick       if (!Setter->isDefined())
5369e5dd7070Spatrick         InstanceMethods.push_back(Setter);
5370e5dd7070Spatrick   }
5371e5dd7070Spatrick   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5372e5dd7070Spatrick                              true, "", IDecl->getName(), Result);
5373e5dd7070Spatrick 
5374e5dd7070Spatrick   // Build _objc_method_list for class's class methods if needed
5375e5dd7070Spatrick   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5376e5dd7070Spatrick                              false, "", IDecl->getName(), Result);
5377e5dd7070Spatrick 
5378e5dd7070Spatrick   // Protocols referenced in class declaration?
5379e5dd7070Spatrick   RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5380e5dd7070Spatrick                                   "CLASS", CDecl->getName(), Result);
5381e5dd7070Spatrick 
5382e5dd7070Spatrick   // Declaration of class/meta-class metadata
5383e5dd7070Spatrick   /* struct _objc_class {
5384e5dd7070Spatrick    struct _objc_class *isa; // or const char *root_class_name when metadata
5385e5dd7070Spatrick    const char *super_class_name;
5386e5dd7070Spatrick    char *name;
5387e5dd7070Spatrick    long version;
5388e5dd7070Spatrick    long info;
5389e5dd7070Spatrick    long instance_size;
5390e5dd7070Spatrick    struct _objc_ivar_list *ivars;
5391e5dd7070Spatrick    struct _objc_method_list *methods;
5392e5dd7070Spatrick    struct objc_cache *cache;
5393e5dd7070Spatrick    struct objc_protocol_list *protocols;
5394e5dd7070Spatrick    const char *ivar_layout;
5395e5dd7070Spatrick    struct _objc_class_ext  *ext;
5396e5dd7070Spatrick    };
5397e5dd7070Spatrick    */
5398e5dd7070Spatrick   static bool objc_class = false;
5399e5dd7070Spatrick   if (!objc_class) {
5400e5dd7070Spatrick     Result += "\nstruct _objc_class {\n";
5401e5dd7070Spatrick     Result += "\tstruct _objc_class *isa;\n";
5402e5dd7070Spatrick     Result += "\tconst char *super_class_name;\n";
5403e5dd7070Spatrick     Result += "\tchar *name;\n";
5404e5dd7070Spatrick     Result += "\tlong version;\n";
5405e5dd7070Spatrick     Result += "\tlong info;\n";
5406e5dd7070Spatrick     Result += "\tlong instance_size;\n";
5407e5dd7070Spatrick     Result += "\tstruct _objc_ivar_list *ivars;\n";
5408e5dd7070Spatrick     Result += "\tstruct _objc_method_list *methods;\n";
5409e5dd7070Spatrick     Result += "\tstruct objc_cache *cache;\n";
5410e5dd7070Spatrick     Result += "\tstruct _objc_protocol_list *protocols;\n";
5411e5dd7070Spatrick     Result += "\tconst char *ivar_layout;\n";
5412e5dd7070Spatrick     Result += "\tstruct _objc_class_ext  *ext;\n";
5413e5dd7070Spatrick     Result += "};\n";
5414e5dd7070Spatrick     objc_class = true;
5415e5dd7070Spatrick   }
5416e5dd7070Spatrick 
5417e5dd7070Spatrick   // Meta-class metadata generation.
5418e5dd7070Spatrick   ObjCInterfaceDecl *RootClass = nullptr;
5419e5dd7070Spatrick   ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5420e5dd7070Spatrick   while (SuperClass) {
5421e5dd7070Spatrick     RootClass = SuperClass;
5422e5dd7070Spatrick     SuperClass = SuperClass->getSuperClass();
5423e5dd7070Spatrick   }
5424e5dd7070Spatrick   SuperClass = CDecl->getSuperClass();
5425e5dd7070Spatrick 
5426e5dd7070Spatrick   Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5427e5dd7070Spatrick   Result += CDecl->getNameAsString();
5428e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5429e5dd7070Spatrick   "{\n\t(struct _objc_class *)\"";
5430e5dd7070Spatrick   Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5431e5dd7070Spatrick   Result += "\"";
5432e5dd7070Spatrick 
5433e5dd7070Spatrick   if (SuperClass) {
5434e5dd7070Spatrick     Result += ", \"";
5435e5dd7070Spatrick     Result += SuperClass->getNameAsString();
5436e5dd7070Spatrick     Result += "\", \"";
5437e5dd7070Spatrick     Result += CDecl->getNameAsString();
5438e5dd7070Spatrick     Result += "\"";
5439e5dd7070Spatrick   }
5440e5dd7070Spatrick   else {
5441e5dd7070Spatrick     Result += ", 0, \"";
5442e5dd7070Spatrick     Result += CDecl->getNameAsString();
5443e5dd7070Spatrick     Result += "\"";
5444e5dd7070Spatrick   }
5445e5dd7070Spatrick   // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5446e5dd7070Spatrick   // 'info' field is initialized to CLS_META(2) for metaclass
5447e5dd7070Spatrick   Result += ", 0,2, sizeof(struct _objc_class), 0";
5448e5dd7070Spatrick   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5449e5dd7070Spatrick     Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5450e5dd7070Spatrick     Result += IDecl->getNameAsString();
5451e5dd7070Spatrick     Result += "\n";
5452e5dd7070Spatrick   }
5453e5dd7070Spatrick   else
5454e5dd7070Spatrick     Result += ", 0\n";
5455e5dd7070Spatrick   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5456e5dd7070Spatrick     Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5457e5dd7070Spatrick     Result += CDecl->getNameAsString();
5458e5dd7070Spatrick     Result += ",0,0\n";
5459e5dd7070Spatrick   }
5460e5dd7070Spatrick   else
5461e5dd7070Spatrick     Result += "\t,0,0,0,0\n";
5462e5dd7070Spatrick   Result += "};\n";
5463e5dd7070Spatrick 
5464e5dd7070Spatrick   // class metadata generation.
5465e5dd7070Spatrick   Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5466e5dd7070Spatrick   Result += CDecl->getNameAsString();
5467e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5468e5dd7070Spatrick   "{\n\t&_OBJC_METACLASS_";
5469e5dd7070Spatrick   Result += CDecl->getNameAsString();
5470e5dd7070Spatrick   if (SuperClass) {
5471e5dd7070Spatrick     Result += ", \"";
5472e5dd7070Spatrick     Result += SuperClass->getNameAsString();
5473e5dd7070Spatrick     Result += "\", \"";
5474e5dd7070Spatrick     Result += CDecl->getNameAsString();
5475e5dd7070Spatrick     Result += "\"";
5476e5dd7070Spatrick   }
5477e5dd7070Spatrick   else {
5478e5dd7070Spatrick     Result += ", 0, \"";
5479e5dd7070Spatrick     Result += CDecl->getNameAsString();
5480e5dd7070Spatrick     Result += "\"";
5481e5dd7070Spatrick   }
5482e5dd7070Spatrick   // 'info' field is initialized to CLS_CLASS(1) for class
5483e5dd7070Spatrick   Result += ", 0,1";
5484e5dd7070Spatrick   if (!ObjCSynthesizedStructs.count(CDecl))
5485e5dd7070Spatrick     Result += ",0";
5486e5dd7070Spatrick   else {
5487e5dd7070Spatrick     // class has size. Must synthesize its size.
5488e5dd7070Spatrick     Result += ",sizeof(struct ";
5489e5dd7070Spatrick     Result += CDecl->getNameAsString();
5490e5dd7070Spatrick     if (LangOpts.MicrosoftExt)
5491e5dd7070Spatrick       Result += "_IMPL";
5492e5dd7070Spatrick     Result += ")";
5493e5dd7070Spatrick   }
5494e5dd7070Spatrick   if (NumIvars > 0) {
5495e5dd7070Spatrick     Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5496e5dd7070Spatrick     Result += CDecl->getNameAsString();
5497e5dd7070Spatrick     Result += "\n\t";
5498e5dd7070Spatrick   }
5499e5dd7070Spatrick   else
5500e5dd7070Spatrick     Result += ",0";
5501e5dd7070Spatrick   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5502e5dd7070Spatrick     Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5503e5dd7070Spatrick     Result += CDecl->getNameAsString();
5504e5dd7070Spatrick     Result += ", 0\n\t";
5505e5dd7070Spatrick   }
5506e5dd7070Spatrick   else
5507e5dd7070Spatrick     Result += ",0,0";
5508e5dd7070Spatrick   if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5509e5dd7070Spatrick     Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5510e5dd7070Spatrick     Result += CDecl->getNameAsString();
5511e5dd7070Spatrick     Result += ", 0,0\n";
5512e5dd7070Spatrick   }
5513e5dd7070Spatrick   else
5514e5dd7070Spatrick     Result += ",0,0,0\n";
5515e5dd7070Spatrick   Result += "};\n";
5516e5dd7070Spatrick }
5517e5dd7070Spatrick 
RewriteMetaDataIntoBuffer(std::string & Result)5518e5dd7070Spatrick void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5519e5dd7070Spatrick   int ClsDefCount = ClassImplementation.size();
5520e5dd7070Spatrick   int CatDefCount = CategoryImplementation.size();
5521e5dd7070Spatrick 
5522e5dd7070Spatrick   // For each implemented class, write out all its meta data.
5523e5dd7070Spatrick   for (int i = 0; i < ClsDefCount; i++)
5524e5dd7070Spatrick     RewriteObjCClassMetaData(ClassImplementation[i], Result);
5525e5dd7070Spatrick 
5526e5dd7070Spatrick   // For each implemented category, write out all its meta data.
5527e5dd7070Spatrick   for (int i = 0; i < CatDefCount; i++)
5528e5dd7070Spatrick     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5529e5dd7070Spatrick 
5530e5dd7070Spatrick   // Write objc_symtab metadata
5531e5dd7070Spatrick   /*
5532e5dd7070Spatrick    struct _objc_symtab
5533e5dd7070Spatrick    {
5534e5dd7070Spatrick    long sel_ref_cnt;
5535e5dd7070Spatrick    SEL *refs;
5536e5dd7070Spatrick    short cls_def_cnt;
5537e5dd7070Spatrick    short cat_def_cnt;
5538e5dd7070Spatrick    void *defs[cls_def_cnt + cat_def_cnt];
5539e5dd7070Spatrick    };
5540e5dd7070Spatrick    */
5541e5dd7070Spatrick 
5542e5dd7070Spatrick   Result += "\nstruct _objc_symtab {\n";
5543e5dd7070Spatrick   Result += "\tlong sel_ref_cnt;\n";
5544e5dd7070Spatrick   Result += "\tSEL *refs;\n";
5545e5dd7070Spatrick   Result += "\tshort cls_def_cnt;\n";
5546e5dd7070Spatrick   Result += "\tshort cat_def_cnt;\n";
5547e5dd7070Spatrick   Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5548e5dd7070Spatrick   Result += "};\n\n";
5549e5dd7070Spatrick 
5550e5dd7070Spatrick   Result += "static struct _objc_symtab "
5551e5dd7070Spatrick   "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5552e5dd7070Spatrick   Result += "\t0, 0, " + utostr(ClsDefCount)
5553e5dd7070Spatrick   + ", " + utostr(CatDefCount) + "\n";
5554e5dd7070Spatrick   for (int i = 0; i < ClsDefCount; i++) {
5555e5dd7070Spatrick     Result += "\t,&_OBJC_CLASS_";
5556e5dd7070Spatrick     Result += ClassImplementation[i]->getNameAsString();
5557e5dd7070Spatrick     Result += "\n";
5558e5dd7070Spatrick   }
5559e5dd7070Spatrick 
5560e5dd7070Spatrick   for (int i = 0; i < CatDefCount; i++) {
5561e5dd7070Spatrick     Result += "\t,&_OBJC_CATEGORY_";
5562e5dd7070Spatrick     Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5563e5dd7070Spatrick     Result += "_";
5564e5dd7070Spatrick     Result += CategoryImplementation[i]->getNameAsString();
5565e5dd7070Spatrick     Result += "\n";
5566e5dd7070Spatrick   }
5567e5dd7070Spatrick 
5568e5dd7070Spatrick   Result += "};\n\n";
5569e5dd7070Spatrick 
5570e5dd7070Spatrick   // Write objc_module metadata
5571e5dd7070Spatrick 
5572e5dd7070Spatrick   /*
5573e5dd7070Spatrick    struct _objc_module {
5574e5dd7070Spatrick    long version;
5575e5dd7070Spatrick    long size;
5576e5dd7070Spatrick    const char *name;
5577e5dd7070Spatrick    struct _objc_symtab *symtab;
5578e5dd7070Spatrick    }
5579e5dd7070Spatrick    */
5580e5dd7070Spatrick 
5581e5dd7070Spatrick   Result += "\nstruct _objc_module {\n";
5582e5dd7070Spatrick   Result += "\tlong version;\n";
5583e5dd7070Spatrick   Result += "\tlong size;\n";
5584e5dd7070Spatrick   Result += "\tconst char *name;\n";
5585e5dd7070Spatrick   Result += "\tstruct _objc_symtab *symtab;\n";
5586e5dd7070Spatrick   Result += "};\n\n";
5587e5dd7070Spatrick   Result += "static struct _objc_module "
5588e5dd7070Spatrick   "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5589e5dd7070Spatrick   Result += "\t" + utostr(OBJC_ABI_VERSION) +
5590e5dd7070Spatrick   ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5591e5dd7070Spatrick   Result += "};\n\n";
5592e5dd7070Spatrick 
5593e5dd7070Spatrick   if (LangOpts.MicrosoftExt) {
5594e5dd7070Spatrick     if (ProtocolExprDecls.size()) {
5595e5dd7070Spatrick       Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5596e5dd7070Spatrick       Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5597e5dd7070Spatrick       for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5598e5dd7070Spatrick         Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5599e5dd7070Spatrick         Result += ProtDecl->getNameAsString();
5600e5dd7070Spatrick         Result += " = &_OBJC_PROTOCOL_";
5601e5dd7070Spatrick         Result += ProtDecl->getNameAsString();
5602e5dd7070Spatrick         Result += ";\n";
5603e5dd7070Spatrick       }
5604e5dd7070Spatrick       Result += "#pragma data_seg(pop)\n\n";
5605e5dd7070Spatrick     }
5606e5dd7070Spatrick     Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5607e5dd7070Spatrick     Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5608e5dd7070Spatrick     Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5609e5dd7070Spatrick     Result += "&_OBJC_MODULES;\n";
5610e5dd7070Spatrick     Result += "#pragma data_seg(pop)\n\n";
5611e5dd7070Spatrick   }
5612e5dd7070Spatrick }
5613e5dd7070Spatrick 
5614e5dd7070Spatrick /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5615e5dd7070Spatrick /// implementation.
RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl * IDecl,std::string & Result)5616e5dd7070Spatrick void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5617e5dd7070Spatrick                                               std::string &Result) {
5618e5dd7070Spatrick   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5619e5dd7070Spatrick   // Find category declaration for this implementation.
5620e5dd7070Spatrick   ObjCCategoryDecl *CDecl
5621e5dd7070Spatrick     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5622e5dd7070Spatrick 
5623e5dd7070Spatrick   std::string FullCategoryName = ClassDecl->getNameAsString();
5624e5dd7070Spatrick   FullCategoryName += '_';
5625e5dd7070Spatrick   FullCategoryName += IDecl->getNameAsString();
5626e5dd7070Spatrick 
5627e5dd7070Spatrick   // Build _objc_method_list for class's instance methods if needed
5628e5dd7070Spatrick   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5629e5dd7070Spatrick 
5630e5dd7070Spatrick   // If any of our property implementations have associated getters or
5631e5dd7070Spatrick   // setters, produce metadata for them as well.
5632e5dd7070Spatrick   for (const auto *Prop : IDecl->property_impls()) {
5633e5dd7070Spatrick     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5634e5dd7070Spatrick       continue;
5635e5dd7070Spatrick     if (!Prop->getPropertyIvarDecl())
5636e5dd7070Spatrick       continue;
5637e5dd7070Spatrick     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5638e5dd7070Spatrick     if (!PD)
5639e5dd7070Spatrick       continue;
5640e5dd7070Spatrick     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
5641e5dd7070Spatrick       InstanceMethods.push_back(Getter);
5642e5dd7070Spatrick     if (PD->isReadOnly())
5643e5dd7070Spatrick       continue;
5644e5dd7070Spatrick     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
5645e5dd7070Spatrick       InstanceMethods.push_back(Setter);
5646e5dd7070Spatrick   }
5647e5dd7070Spatrick   RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5648e5dd7070Spatrick                              true, "CATEGORY_", FullCategoryName, Result);
5649e5dd7070Spatrick 
5650e5dd7070Spatrick   // Build _objc_method_list for class's class methods if needed
5651e5dd7070Spatrick   RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5652e5dd7070Spatrick                              false, "CATEGORY_", FullCategoryName, Result);
5653e5dd7070Spatrick 
5654e5dd7070Spatrick   // Protocols referenced in class declaration?
5655e5dd7070Spatrick   // Null CDecl is case of a category implementation with no category interface
5656e5dd7070Spatrick   if (CDecl)
5657e5dd7070Spatrick     RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5658e5dd7070Spatrick                                     FullCategoryName, Result);
5659e5dd7070Spatrick   /* struct _objc_category {
5660e5dd7070Spatrick    char *category_name;
5661e5dd7070Spatrick    char *class_name;
5662e5dd7070Spatrick    struct _objc_method_list *instance_methods;
5663e5dd7070Spatrick    struct _objc_method_list *class_methods;
5664e5dd7070Spatrick    struct _objc_protocol_list *protocols;
5665e5dd7070Spatrick    // Objective-C 1.0 extensions
5666e5dd7070Spatrick    uint32_t size;     // sizeof (struct _objc_category)
5667e5dd7070Spatrick    struct _objc_property_list *instance_properties;  // category's own
5668e5dd7070Spatrick    // @property decl.
5669e5dd7070Spatrick    };
5670e5dd7070Spatrick    */
5671e5dd7070Spatrick 
5672e5dd7070Spatrick   static bool objc_category = false;
5673e5dd7070Spatrick   if (!objc_category) {
5674e5dd7070Spatrick     Result += "\nstruct _objc_category {\n";
5675e5dd7070Spatrick     Result += "\tchar *category_name;\n";
5676e5dd7070Spatrick     Result += "\tchar *class_name;\n";
5677e5dd7070Spatrick     Result += "\tstruct _objc_method_list *instance_methods;\n";
5678e5dd7070Spatrick     Result += "\tstruct _objc_method_list *class_methods;\n";
5679e5dd7070Spatrick     Result += "\tstruct _objc_protocol_list *protocols;\n";
5680e5dd7070Spatrick     Result += "\tunsigned int size;\n";
5681e5dd7070Spatrick     Result += "\tstruct _objc_property_list *instance_properties;\n";
5682e5dd7070Spatrick     Result += "};\n";
5683e5dd7070Spatrick     objc_category = true;
5684e5dd7070Spatrick   }
5685e5dd7070Spatrick   Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5686e5dd7070Spatrick   Result += FullCategoryName;
5687e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5688e5dd7070Spatrick   Result += IDecl->getNameAsString();
5689e5dd7070Spatrick   Result += "\"\n\t, \"";
5690e5dd7070Spatrick   Result += ClassDecl->getNameAsString();
5691e5dd7070Spatrick   Result += "\"\n";
5692e5dd7070Spatrick 
5693e5dd7070Spatrick   if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5694e5dd7070Spatrick     Result += "\t, (struct _objc_method_list *)"
5695e5dd7070Spatrick     "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5696e5dd7070Spatrick     Result += FullCategoryName;
5697e5dd7070Spatrick     Result += "\n";
5698e5dd7070Spatrick   }
5699e5dd7070Spatrick   else
5700e5dd7070Spatrick     Result += "\t, 0\n";
5701e5dd7070Spatrick   if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5702e5dd7070Spatrick     Result += "\t, (struct _objc_method_list *)"
5703e5dd7070Spatrick     "&_OBJC_CATEGORY_CLASS_METHODS_";
5704e5dd7070Spatrick     Result += FullCategoryName;
5705e5dd7070Spatrick     Result += "\n";
5706e5dd7070Spatrick   }
5707e5dd7070Spatrick   else
5708e5dd7070Spatrick     Result += "\t, 0\n";
5709e5dd7070Spatrick 
5710e5dd7070Spatrick   if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5711e5dd7070Spatrick     Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5712e5dd7070Spatrick     Result += FullCategoryName;
5713e5dd7070Spatrick     Result += "\n";
5714e5dd7070Spatrick   }
5715e5dd7070Spatrick   else
5716e5dd7070Spatrick     Result += "\t, 0\n";
5717e5dd7070Spatrick   Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5718e5dd7070Spatrick }
5719e5dd7070Spatrick 
5720e5dd7070Spatrick // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5721e5dd7070Spatrick /// class methods.
5722e5dd7070Spatrick template<typename MethodIterator>
RewriteObjCMethodsMetaData(MethodIterator MethodBegin,MethodIterator MethodEnd,bool IsInstanceMethod,StringRef prefix,StringRef ClassName,std::string & Result)5723e5dd7070Spatrick void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5724e5dd7070Spatrick                                              MethodIterator MethodEnd,
5725e5dd7070Spatrick                                              bool IsInstanceMethod,
5726e5dd7070Spatrick                                              StringRef prefix,
5727e5dd7070Spatrick                                              StringRef ClassName,
5728e5dd7070Spatrick                                              std::string &Result) {
5729e5dd7070Spatrick   if (MethodBegin == MethodEnd) return;
5730e5dd7070Spatrick 
5731e5dd7070Spatrick   if (!objc_impl_method) {
5732e5dd7070Spatrick     /* struct _objc_method {
5733e5dd7070Spatrick      SEL _cmd;
5734e5dd7070Spatrick      char *method_types;
5735e5dd7070Spatrick      void *_imp;
5736e5dd7070Spatrick      }
5737e5dd7070Spatrick      */
5738e5dd7070Spatrick     Result += "\nstruct _objc_method {\n";
5739e5dd7070Spatrick     Result += "\tSEL _cmd;\n";
5740e5dd7070Spatrick     Result += "\tchar *method_types;\n";
5741e5dd7070Spatrick     Result += "\tvoid *_imp;\n";
5742e5dd7070Spatrick     Result += "};\n";
5743e5dd7070Spatrick 
5744e5dd7070Spatrick     objc_impl_method = true;
5745e5dd7070Spatrick   }
5746e5dd7070Spatrick 
5747e5dd7070Spatrick   // Build _objc_method_list for class's methods if needed
5748e5dd7070Spatrick 
5749e5dd7070Spatrick   /* struct  {
5750e5dd7070Spatrick    struct _objc_method_list *next_method;
5751e5dd7070Spatrick    int method_count;
5752e5dd7070Spatrick    struct _objc_method method_list[];
5753e5dd7070Spatrick    }
5754e5dd7070Spatrick    */
5755e5dd7070Spatrick   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5756e5dd7070Spatrick   Result += "\nstatic struct {\n";
5757e5dd7070Spatrick   Result += "\tstruct _objc_method_list *next_method;\n";
5758e5dd7070Spatrick   Result += "\tint method_count;\n";
5759e5dd7070Spatrick   Result += "\tstruct _objc_method method_list[";
5760e5dd7070Spatrick   Result += utostr(NumMethods);
5761e5dd7070Spatrick   Result += "];\n} _OBJC_";
5762e5dd7070Spatrick   Result += prefix;
5763e5dd7070Spatrick   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5764e5dd7070Spatrick   Result += "_METHODS_";
5765e5dd7070Spatrick   Result += ClassName;
5766e5dd7070Spatrick   Result += " __attribute__ ((used, section (\"__OBJC, __";
5767e5dd7070Spatrick   Result += IsInstanceMethod ? "inst" : "cls";
5768e5dd7070Spatrick   Result += "_meth\")))= ";
5769e5dd7070Spatrick   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5770e5dd7070Spatrick 
5771e5dd7070Spatrick   Result += "\t,{{(SEL)\"";
5772e5dd7070Spatrick   Result += (*MethodBegin)->getSelector().getAsString();
5773e5dd7070Spatrick   std::string MethodTypeString =
5774e5dd7070Spatrick     Context->getObjCEncodingForMethodDecl(*MethodBegin);
5775e5dd7070Spatrick   Result += "\", \"";
5776e5dd7070Spatrick   Result += MethodTypeString;
5777e5dd7070Spatrick   Result += "\", (void *)";
5778e5dd7070Spatrick   Result += MethodInternalNames[*MethodBegin];
5779e5dd7070Spatrick   Result += "}\n";
5780e5dd7070Spatrick   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5781e5dd7070Spatrick     Result += "\t  ,{(SEL)\"";
5782e5dd7070Spatrick     Result += (*MethodBegin)->getSelector().getAsString();
5783e5dd7070Spatrick     std::string MethodTypeString =
5784e5dd7070Spatrick       Context->getObjCEncodingForMethodDecl(*MethodBegin);
5785e5dd7070Spatrick     Result += "\", \"";
5786e5dd7070Spatrick     Result += MethodTypeString;
5787e5dd7070Spatrick     Result += "\", (void *)";
5788e5dd7070Spatrick     Result += MethodInternalNames[*MethodBegin];
5789e5dd7070Spatrick     Result += "}\n";
5790e5dd7070Spatrick   }
5791e5dd7070Spatrick   Result += "\t }\n};\n";
5792e5dd7070Spatrick }
5793e5dd7070Spatrick 
RewriteObjCIvarRefExpr(ObjCIvarRefExpr * IV)5794e5dd7070Spatrick Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5795e5dd7070Spatrick   SourceRange OldRange = IV->getSourceRange();
5796e5dd7070Spatrick   Expr *BaseExpr = IV->getBase();
5797e5dd7070Spatrick 
5798e5dd7070Spatrick   // Rewrite the base, but without actually doing replaces.
5799e5dd7070Spatrick   {
5800e5dd7070Spatrick     DisableReplaceStmtScope S(*this);
5801e5dd7070Spatrick     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5802e5dd7070Spatrick     IV->setBase(BaseExpr);
5803e5dd7070Spatrick   }
5804e5dd7070Spatrick 
5805e5dd7070Spatrick   ObjCIvarDecl *D = IV->getDecl();
5806e5dd7070Spatrick 
5807e5dd7070Spatrick   Expr *Replacement = IV;
5808e5dd7070Spatrick   if (CurMethodDef) {
5809e5dd7070Spatrick     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5810e5dd7070Spatrick       const ObjCInterfaceType *iFaceDecl =
5811e5dd7070Spatrick       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5812e5dd7070Spatrick       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5813e5dd7070Spatrick       // lookup which class implements the instance variable.
5814e5dd7070Spatrick       ObjCInterfaceDecl *clsDeclared = nullptr;
5815e5dd7070Spatrick       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5816e5dd7070Spatrick                                                    clsDeclared);
5817e5dd7070Spatrick       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5818e5dd7070Spatrick 
5819e5dd7070Spatrick       // Synthesize an explicit cast to gain access to the ivar.
5820ec727ea7Spatrick       std::string RecName =
5821ec727ea7Spatrick           std::string(clsDeclared->getIdentifier()->getName());
5822e5dd7070Spatrick       RecName += "_IMPL";
5823e5dd7070Spatrick       IdentifierInfo *II = &Context->Idents.get(RecName);
5824e5dd7070Spatrick       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5825e5dd7070Spatrick                                           SourceLocation(), SourceLocation(),
5826e5dd7070Spatrick                                           II);
5827e5dd7070Spatrick       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5828e5dd7070Spatrick       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5829e5dd7070Spatrick       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5830e5dd7070Spatrick                                                     CK_BitCast,
5831e5dd7070Spatrick                                                     IV->getBase());
5832e5dd7070Spatrick       // Don't forget the parens to enforce the proper binding.
5833e5dd7070Spatrick       ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5834e5dd7070Spatrick                                               OldRange.getEnd(),
5835e5dd7070Spatrick                                               castExpr);
5836e5dd7070Spatrick       if (IV->isFreeIvar() &&
5837e5dd7070Spatrick           declaresSameEntity(CurMethodDef->getClassInterface(),
5838e5dd7070Spatrick                              iFaceDecl->getDecl())) {
5839e5dd7070Spatrick         MemberExpr *ME = MemberExpr::CreateImplicit(
5840e5dd7070Spatrick             *Context, PE, true, D, D->getType(), VK_LValue, OK_Ordinary);
5841e5dd7070Spatrick         Replacement = ME;
5842e5dd7070Spatrick       } else {
5843e5dd7070Spatrick         IV->setBase(PE);
5844e5dd7070Spatrick       }
5845e5dd7070Spatrick     }
5846e5dd7070Spatrick   } else { // we are outside a method.
5847e5dd7070Spatrick     assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5848e5dd7070Spatrick 
5849e5dd7070Spatrick     // Explicit ivar refs need to have a cast inserted.
5850e5dd7070Spatrick     // FIXME: consider sharing some of this code with the code above.
5851e5dd7070Spatrick     if (BaseExpr->getType()->isObjCObjectPointerType()) {
5852e5dd7070Spatrick       const ObjCInterfaceType *iFaceDecl =
5853e5dd7070Spatrick       dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5854e5dd7070Spatrick       // lookup which class implements the instance variable.
5855e5dd7070Spatrick       ObjCInterfaceDecl *clsDeclared = nullptr;
5856e5dd7070Spatrick       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5857e5dd7070Spatrick                                                    clsDeclared);
5858e5dd7070Spatrick       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5859e5dd7070Spatrick 
5860e5dd7070Spatrick       // Synthesize an explicit cast to gain access to the ivar.
5861ec727ea7Spatrick       std::string RecName =
5862ec727ea7Spatrick           std::string(clsDeclared->getIdentifier()->getName());
5863e5dd7070Spatrick       RecName += "_IMPL";
5864e5dd7070Spatrick       IdentifierInfo *II = &Context->Idents.get(RecName);
5865e5dd7070Spatrick       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5866e5dd7070Spatrick                                           SourceLocation(), SourceLocation(),
5867e5dd7070Spatrick                                           II);
5868e5dd7070Spatrick       assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5869e5dd7070Spatrick       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5870e5dd7070Spatrick       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5871e5dd7070Spatrick                                                     CK_BitCast,
5872e5dd7070Spatrick                                                     IV->getBase());
5873e5dd7070Spatrick       // Don't forget the parens to enforce the proper binding.
5874e5dd7070Spatrick       ParenExpr *PE = new (Context) ParenExpr(
5875e5dd7070Spatrick           IV->getBase()->getBeginLoc(), IV->getBase()->getEndLoc(), castExpr);
5876e5dd7070Spatrick       // Cannot delete IV->getBase(), since PE points to it.
5877e5dd7070Spatrick       // Replace the old base with the cast. This is important when doing
5878e5dd7070Spatrick       // embedded rewrites. For example, [newInv->_container addObject:0].
5879e5dd7070Spatrick       IV->setBase(PE);
5880e5dd7070Spatrick     }
5881e5dd7070Spatrick   }
5882e5dd7070Spatrick 
5883e5dd7070Spatrick   ReplaceStmtWithRange(IV, Replacement, OldRange);
5884e5dd7070Spatrick   return Replacement;
5885e5dd7070Spatrick }
5886e5dd7070Spatrick 
5887e5dd7070Spatrick #endif // CLANG_ENABLE_OBJC_REWRITER
5888