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