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