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