1 //===-- RewriteModernObjC.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/Basic/TargetInfo.h"
23 #include "clang/Config/config.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Rewrite/Core/Rewriter.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <memory>
32 
33 #if CLANG_ENABLE_OBJC_REWRITER
34 
35 using namespace clang;
36 using llvm::utostr;
37 
38 namespace {
39   class RewriteModernObjC : public ASTConsumer {
40   protected:
41 
42     enum {
43       BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
44                                         block, ... */
45       BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
46       BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
47                                         __block variable */
48       BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
49                                         helpers */
50       BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
51                                         support routines */
52       BLOCK_BYREF_CURRENT_MAX = 256
53     };
54 
55     enum {
56       BLOCK_NEEDS_FREE =        (1 << 24),
57       BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
58       BLOCK_HAS_CXX_OBJ =       (1 << 26),
59       BLOCK_IS_GC =             (1 << 27),
60       BLOCK_IS_GLOBAL =         (1 << 28),
61       BLOCK_HAS_DESCRIPTOR =    (1 << 29)
62     };
63 
64     Rewriter Rewrite;
65     DiagnosticsEngine &Diags;
66     const LangOptions &LangOpts;
67     ASTContext *Context;
68     SourceManager *SM;
69     TranslationUnitDecl *TUDecl;
70     FileID MainFileID;
71     const char *MainFileStart, *MainFileEnd;
72     Stmt *CurrentBody;
73     ParentMap *PropParentMap; // created lazily.
74     std::string InFileName;
75     std::unique_ptr<raw_ostream> OutFile;
76     std::string Preamble;
77 
78     TypeDecl *ProtocolTypeDecl;
79     VarDecl *GlobalVarDecl;
80     Expr *GlobalConstructionExp;
81     unsigned RewriteFailedDiag;
82     unsigned GlobalBlockRewriteFailedDiag;
83     // ObjC string constant support.
84     unsigned NumObjCStringLiterals;
85     VarDecl *ConstantStringClassReference;
86     RecordDecl *NSStringRecord;
87 
88     // ObjC foreach break/continue generation support.
89     int BcLabelCount;
90 
91     unsigned TryFinallyContainsReturnDiag;
92     // Needed for super.
93     ObjCMethodDecl *CurMethodDef;
94     RecordDecl *SuperStructDecl;
95     RecordDecl *ConstantStringDecl;
96 
97     FunctionDecl *MsgSendFunctionDecl;
98     FunctionDecl *MsgSendSuperFunctionDecl;
99     FunctionDecl *MsgSendStretFunctionDecl;
100     FunctionDecl *MsgSendSuperStretFunctionDecl;
101     FunctionDecl *MsgSendFpretFunctionDecl;
102     FunctionDecl *GetClassFunctionDecl;
103     FunctionDecl *GetMetaClassFunctionDecl;
104     FunctionDecl *GetSuperClassFunctionDecl;
105     FunctionDecl *SelGetUidFunctionDecl;
106     FunctionDecl *CFStringFunctionDecl;
107     FunctionDecl *SuperConstructorFunctionDecl;
108     FunctionDecl *CurFunctionDef;
109 
110     /* Misc. containers needed for meta-data rewrite. */
111     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114     llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116     llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117     SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118     /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119     SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120 
121     /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122     SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123 
124     SmallVector<Stmt *, 32> Stmts;
125     SmallVector<int, 8> ObjCBcLabelNo;
126     // Remember all the @protocol(<expr>) expressions.
127     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128 
129     llvm::DenseSet<uint64_t> CopyDestroyCache;
130 
131     // Block expressions.
132     SmallVector<BlockExpr *, 32> Blocks;
133     SmallVector<int, 32> InnerDeclRefsCount;
134     SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135 
136     SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137 
138     // Block related declarations.
139     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140     llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141     SmallVector<ValueDecl *, 8> BlockByRefDecls;
142     llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143     llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144     llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145     llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146 
147     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
148     llvm::DenseMap<ObjCInterfaceDecl *,
149                     llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
150 
151     // ivar bitfield grouping containers
152     llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153     llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154     // This container maps an <class, group number for ivar> tuple to the type
155     // of the struct where the bitfield belongs.
156     llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
157     SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
158 
159     // This maps an original source AST to it's rewritten form. This allows
160     // us to avoid rewriting the same node twice (which is very uncommon).
161     // This is needed to support some of the exotic property rewriting.
162     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163 
164     // Needed for header files being rewritten
165     bool IsHeader;
166     bool SilenceRewriteMacroWarning;
167     bool GenerateLineInfo;
168     bool objc_impl_method;
169 
170     bool DisableReplaceStmt;
171     class DisableReplaceStmtScope {
172       RewriteModernObjC &R;
173       bool SavedValue;
174 
175     public:
176       DisableReplaceStmtScope(RewriteModernObjC &R)
177         : R(R), SavedValue(R.DisableReplaceStmt) {
178         R.DisableReplaceStmt = true;
179       }
180       ~DisableReplaceStmtScope() {
181         R.DisableReplaceStmt = SavedValue;
182       }
183     };
184     void InitializeCommon(ASTContext &context);
185 
186   public:
187     llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
188 
189     // Top Level Driver code.
190     bool HandleTopLevelDecl(DeclGroupRef D) override {
191       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192         if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193           if (!Class->isThisDeclarationADefinition()) {
194             RewriteForwardClassDecl(D);
195             break;
196           } else {
197             // Keep track of all interface declarations seen.
198             ObjCInterfacesSeen.push_back(Class);
199             break;
200           }
201         }
202 
203         if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204           if (!Proto->isThisDeclarationADefinition()) {
205             RewriteForwardProtocolDecl(D);
206             break;
207           }
208         }
209 
210         if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211           // Under modern abi, we cannot translate body of the function
212           // yet until all class extensions and its implementation is seen.
213           // This is because they may introduce new bitfields which must go
214           // into their grouping struct.
215           if (FDecl->isThisDeclarationADefinition() &&
216               // Not c functions defined inside an objc container.
217               !FDecl->isTopLevelDeclInObjCContainer()) {
218             FunctionDefinitionsSeen.push_back(FDecl);
219             break;
220           }
221         }
222         HandleTopLevelSingleDecl(*I);
223       }
224       return true;
225     }
226 
227     void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230           if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231             RewriteBlockPointerDecl(TD);
232           else if (TD->getUnderlyingType()->isFunctionPointerType())
233             CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234           else
235             RewriteObjCQualifiedInterfaceTypes(TD);
236         }
237       }
238     }
239 
240     void HandleTopLevelSingleDecl(Decl *D);
241     void HandleDeclInMainFile(Decl *D);
242     RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243                       DiagnosticsEngine &D, const LangOptions &LOpts,
244                       bool silenceMacroWarn, bool LineInfo);
245 
246     ~RewriteModernObjC() override {}
247 
248     void HandleTranslationUnit(ASTContext &C) override;
249 
250     void ReplaceStmt(Stmt *Old, Stmt *New) {
251       ReplaceStmtWithRange(Old, New, Old->getSourceRange());
252     }
253 
254     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255       assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
256 
257       Stmt *ReplacingStmt = ReplacedNodes[Old];
258       if (ReplacingStmt)
259         return; // We can't rewrite the same node twice.
260 
261       if (DisableReplaceStmt)
262         return;
263 
264       // Measure the old text.
265       int Size = Rewrite.getRangeSize(SrcRange);
266       if (Size == -1) {
267         Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268             << Old->getSourceRange();
269         return;
270       }
271       // Get the new text.
272       std::string SStr;
273       llvm::raw_string_ostream S(SStr);
274       New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
275       const std::string &Str = S.str();
276 
277       // If replacement succeeded or warning disabled return with no warning.
278       if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279         ReplacedNodes[Old] = New;
280         return;
281       }
282       if (SilenceRewriteMacroWarning)
283         return;
284       Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285           << Old->getSourceRange();
286     }
287 
288     void InsertText(SourceLocation Loc, StringRef Str,
289                     bool InsertAfter = true) {
290       // If insertion succeeded or warning disabled return with no warning.
291       if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292           SilenceRewriteMacroWarning)
293         return;
294 
295       Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296     }
297 
298     void ReplaceText(SourceLocation Start, unsigned OrigLength,
299                      StringRef Str) {
300       // If removal succeeded or warning disabled return with no warning.
301       if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302           SilenceRewriteMacroWarning)
303         return;
304 
305       Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306     }
307 
308     // Syntactic Rewriting.
309     void RewriteRecordBody(RecordDecl *RD);
310     void RewriteInclude();
311     void RewriteLineDirective(const Decl *D);
312     void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313                                               std::string &LineString);
314     void RewriteForwardClassDecl(DeclGroupRef D);
315     void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
316     void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317                                      const std::string &typedefString);
318     void RewriteImplementations();
319     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320                                  ObjCImplementationDecl *IMD,
321                                  ObjCCategoryImplDecl *CID);
322     void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323     void RewriteImplementationDecl(Decl *Dcl);
324     void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325                                ObjCMethodDecl *MDecl, std::string &ResultStr);
326     void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327                                const FunctionType *&FPRetType);
328     void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329                             ValueDecl *VD, bool def=false);
330     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332     void RewriteForwardProtocolDecl(DeclGroupRef D);
333     void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
334     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335     void RewriteProperty(ObjCPropertyDecl *prop);
336     void RewriteFunctionDecl(FunctionDecl *FD);
337     void RewriteBlockPointerType(std::string& Str, QualType Type);
338     void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
339     void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
340     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341     void RewriteTypeOfDecl(VarDecl *VD);
342     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
343 
344     std::string getIvarAccessString(ObjCIvarDecl *D);
345 
346     // Expression Rewriting.
347     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349     Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350     Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
354     Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
355     Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
356     Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
357     Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
358     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
359     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
360     Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
361     Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364                                        SourceLocation OrigEnd);
365     Stmt *RewriteBreakStmt(BreakStmt *S);
366     Stmt *RewriteContinueStmt(ContinueStmt *S);
367     void RewriteCastExpr(CStyleCastExpr *CE);
368     void RewriteImplicitCastObjCExpr(CastExpr *IE);
369 
370     // Computes ivar bitfield group no.
371     unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372     // Names field decl. for ivar bitfield group.
373     void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374     // Names struct type for ivar bitfield group.
375     void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376     // Names symbol for ivar bitfield group field offset.
377     void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378     // Given an ivar bitfield, it builds (or finds) its group record type.
379     QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380     QualType SynthesizeBitfieldGroupStructType(
381                                     ObjCIvarDecl *IV,
382                                     SmallVectorImpl<ObjCIvarDecl *> &IVars);
383 
384     // Block rewriting.
385     void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386 
387     // Block specific rewrite rules.
388     void RewriteBlockPointerDecl(NamedDecl *VD);
389     void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
390     Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
391     Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392     void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393 
394     void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395                                       std::string &Result);
396 
397     void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
398     bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
399                                  bool &IsNamedDefinition);
400     void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401                                               std::string &Result);
402 
403     bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404 
405     void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406                                   std::string &Result);
407 
408     void Initialize(ASTContext &context) override;
409 
410     // Misc. AST transformation routines. Sometimes they end up calling
411     // rewriting routines on the new ASTs.
412     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
413                                            ArrayRef<Expr *> Args,
414                                            SourceLocation StartLoc=SourceLocation(),
415                                            SourceLocation EndLoc=SourceLocation());
416 
417     Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
418                                         QualType returnType,
419                                         SmallVectorImpl<QualType> &ArgTypes,
420                                         SmallVectorImpl<Expr*> &MsgExprs,
421                                         ObjCMethodDecl *Method);
422 
423     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424                            SourceLocation StartLoc=SourceLocation(),
425                            SourceLocation EndLoc=SourceLocation());
426 
427     void SynthCountByEnumWithState(std::string &buf);
428     void SynthMsgSendFunctionDecl();
429     void SynthMsgSendSuperFunctionDecl();
430     void SynthMsgSendStretFunctionDecl();
431     void SynthMsgSendFpretFunctionDecl();
432     void SynthMsgSendSuperStretFunctionDecl();
433     void SynthGetClassFunctionDecl();
434     void SynthGetMetaClassFunctionDecl();
435     void SynthGetSuperClassFunctionDecl();
436     void SynthSelGetUidFunctionDecl();
437     void SynthSuperConstructorFunctionDecl();
438 
439     // Rewriting metadata
440     template<typename MethodIterator>
441     void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442                                     MethodIterator MethodEnd,
443                                     bool IsInstanceMethod,
444                                     StringRef prefix,
445                                     StringRef ClassName,
446                                     std::string &Result);
447     void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448                                      std::string &Result);
449     void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
450                                           std::string &Result);
451     void RewriteClassSetupInitHook(std::string &Result);
452 
453     void RewriteMetaDataIntoBuffer(std::string &Result);
454     void WriteImageInfo(std::string &Result);
455     void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
456                                              std::string &Result);
457     void RewriteCategorySetupInitHook(std::string &Result);
458 
459     // Rewriting ivar
460     void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
461                                               std::string &Result);
462     Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
463 
464 
465     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467                                       StringRef funcName, std::string Tag);
468     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469                                       StringRef funcName, std::string Tag);
470     std::string SynthesizeBlockImpl(BlockExpr *CE,
471                                     std::string Tag, std::string Desc);
472     std::string SynthesizeBlockDescriptor(std::string DescTag,
473                                           std::string ImplTag,
474                                           int i, StringRef funcName,
475                                           unsigned hasCopy);
476     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478                                  StringRef FunName);
479     FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480     Stmt *SynthBlockInitExpr(BlockExpr *Exp,
481                       const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
482 
483     // Misc. helper routines.
484     QualType getProtocolType();
485     void WarnAboutReturnGotoStmts(Stmt *S);
486     void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487     void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488     void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489 
490     bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491     void CollectBlockDeclRefInfo(BlockExpr *Exp);
492     void GetBlockDeclRefExprs(Stmt *S);
493     void GetInnerBlockDeclRefExprs(Stmt *S,
494                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
495                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
496 
497     // We avoid calling Type::isBlockPointerType(), since it operates on the
498     // canonical type. We only care if the top-level type is a closure pointer.
499     bool isTopLevelBlockPointerType(QualType T) {
500       return isa<BlockPointerType>(T);
501     }
502 
503     /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504     /// to a function pointer type and upon success, returns true; false
505     /// otherwise.
506     bool convertBlockPointerToFunctionPointer(QualType &T) {
507       if (isTopLevelBlockPointerType(T)) {
508         const auto *BPT = T->castAs<BlockPointerType>();
509         T = Context->getPointerType(BPT->getPointeeType());
510         return true;
511       }
512       return false;
513     }
514 
515     bool convertObjCTypeToCStyleType(QualType &T);
516 
517     bool needToScanForQualifiers(QualType T);
518     QualType getSuperStructType();
519     QualType getConstantStringStructType();
520     QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521 
522     void convertToUnqualifiedObjCType(QualType &T) {
523       if (T->isObjCQualifiedIdType()) {
524         bool isConst = T.isConstQualified();
525         T = isConst ? Context->getObjCIdType().withConst()
526                     : Context->getObjCIdType();
527       }
528       else if (T->isObjCQualifiedClassType())
529         T = Context->getObjCClassType();
530       else if (T->isObjCObjectPointerType() &&
531                T->getPointeeType()->isObjCQualifiedInterfaceType()) {
532         if (const ObjCObjectPointerType * OBJPT =
533               T->getAsObjCInterfacePointerType()) {
534           const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535           T = QualType(IFaceT, 0);
536           T = Context->getPointerType(T);
537         }
538      }
539     }
540 
541     // FIXME: This predicate seems like it would be useful to add to ASTContext.
542     bool isObjCType(QualType T) {
543       if (!LangOpts.ObjC)
544         return false;
545 
546       QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547 
548       if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549           OCT == Context->getCanonicalType(Context->getObjCClassType()))
550         return true;
551 
552       if (const PointerType *PT = OCT->getAs<PointerType>()) {
553         if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554             PT->getPointeeType()->isObjCQualifiedIdType())
555           return true;
556       }
557       return false;
558     }
559 
560     bool PointerTypeTakesAnyBlockArguments(QualType QT);
561     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562     void GetExtentOfArgList(const char *Name, const char *&LParen,
563                             const char *&RParen);
564 
565     void QuoteDoublequotes(std::string &From, std::string &To) {
566       for (unsigned i = 0; i < From.length(); i++) {
567         if (From[i] == '"')
568           To += "\\\"";
569         else
570           To += From[i];
571       }
572     }
573 
574     QualType getSimpleFunctionType(QualType result,
575                                    ArrayRef<QualType> args,
576                                    bool variadic = false) {
577       if (result == Context->getObjCInstanceType())
578         result =  Context->getObjCIdType();
579       FunctionProtoType::ExtProtoInfo fpi;
580       fpi.Variadic = variadic;
581       return Context->getFunctionType(result, args, fpi);
582     }
583 
584     // Helper function: create a CStyleCastExpr with trivial type source info.
585     CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586                                              CastKind Kind, Expr *E) {
587       TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588       return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589                                     TInfo, SourceLocation(), SourceLocation());
590     }
591 
592     bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593       IdentifierInfo* II = &Context->Idents.get("load");
594       Selector LoadSel = Context->Selectors.getSelector(0, &II);
595       return OD->getClassMethod(LoadSel) != nullptr;
596     }
597 
598     StringLiteral *getStringLiteral(StringRef Str) {
599       QualType StrType = Context->getConstantArrayType(
600           Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
601           ArrayType::Normal, 0);
602       return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603                                    /*Pascal=*/false, StrType, SourceLocation());
604     }
605   };
606 } // end anonymous namespace
607 
608 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609                                                    NamedDecl *D) {
610   if (const FunctionProtoType *fproto
611       = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
612     for (const auto &I : fproto->param_types())
613       if (isTopLevelBlockPointerType(I)) {
614         // All the args are checked/rewritten. Don't call twice!
615         RewriteBlockPointerDecl(D);
616         break;
617       }
618   }
619 }
620 
621 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622   const PointerType *PT = funcType->getAs<PointerType>();
623   if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624     RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625 }
626 
627 static bool IsHeaderFile(const std::string &Filename) {
628   std::string::size_type DotPos = Filename.rfind('.');
629 
630   if (DotPos == std::string::npos) {
631     // no file extension
632     return false;
633   }
634 
635   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636   // C header: .h
637   // C++ header: .hh or .H;
638   return Ext == "h" || Ext == "hh" || Ext == "H";
639 }
640 
641 RewriteModernObjC::RewriteModernObjC(std::string inFile,
642                                      std::unique_ptr<raw_ostream> OS,
643                                      DiagnosticsEngine &D,
644                                      const LangOptions &LOpts,
645                                      bool silenceMacroWarn, bool LineInfo)
646     : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647       SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
648   IsHeader = IsHeaderFile(inFile);
649   RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650                "rewriting sub-expression within a macro (may not be correct)");
651   // FIXME. This should be an error. But if block is not called, it is OK. And it
652   // may break including some headers.
653   GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654     "rewriting block literal declared in global scope is not implemented");
655 
656   TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657                DiagnosticsEngine::Warning,
658                "rewriter doesn't support user-specified control flow semantics "
659                "for @try/@finally (code may not execute properly)");
660 }
661 
662 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
663     const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664     DiagnosticsEngine &Diags, const LangOptions &LOpts,
665     bool SilenceRewriteMacroWarning, bool LineInfo) {
666   return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
667                                               LOpts, SilenceRewriteMacroWarning,
668                                               LineInfo);
669 }
670 
671 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672   Context = &context;
673   SM = &Context->getSourceManager();
674   TUDecl = Context->getTranslationUnitDecl();
675   MsgSendFunctionDecl = nullptr;
676   MsgSendSuperFunctionDecl = nullptr;
677   MsgSendStretFunctionDecl = nullptr;
678   MsgSendSuperStretFunctionDecl = nullptr;
679   MsgSendFpretFunctionDecl = nullptr;
680   GetClassFunctionDecl = nullptr;
681   GetMetaClassFunctionDecl = nullptr;
682   GetSuperClassFunctionDecl = nullptr;
683   SelGetUidFunctionDecl = nullptr;
684   CFStringFunctionDecl = nullptr;
685   ConstantStringClassReference = nullptr;
686   NSStringRecord = nullptr;
687   CurMethodDef = nullptr;
688   CurFunctionDef = nullptr;
689   GlobalVarDecl = nullptr;
690   GlobalConstructionExp = nullptr;
691   SuperStructDecl = nullptr;
692   ProtocolTypeDecl = nullptr;
693   ConstantStringDecl = nullptr;
694   BcLabelCount = 0;
695   SuperConstructorFunctionDecl = nullptr;
696   NumObjCStringLiterals = 0;
697   PropParentMap = nullptr;
698   CurrentBody = nullptr;
699   DisableReplaceStmt = false;
700   objc_impl_method = false;
701 
702   // Get the ID and start/end of the main file.
703   MainFileID = SM->getMainFileID();
704   const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705   MainFileStart = MainBuf->getBufferStart();
706   MainFileEnd = MainBuf->getBufferEnd();
707 
708   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
709 }
710 
711 //===----------------------------------------------------------------------===//
712 // Top Level Driver Code
713 //===----------------------------------------------------------------------===//
714 
715 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716   if (Diags.hasErrorOccurred())
717     return;
718 
719   // Two cases: either the decl could be in the main file, or it could be in a
720   // #included file.  If the former, rewrite it now.  If the later, check to see
721   // if we rewrote the #include/#import.
722   SourceLocation Loc = D->getLocation();
723   Loc = SM->getExpansionLoc(Loc);
724 
725   // If this is for a builtin, ignore it.
726   if (Loc.isInvalid()) return;
727 
728   // Look for built-in declarations that we need to refer during the rewrite.
729   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730     RewriteFunctionDecl(FD);
731   } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732     // declared in <Foundation/NSString.h>
733     if (FVD->getName() == "_NSConstantStringClassReference") {
734       ConstantStringClassReference = FVD;
735       return;
736     }
737   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738     RewriteCategoryDecl(CD);
739   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740     if (PD->isThisDeclarationADefinition())
741       RewriteProtocolDecl(PD);
742   } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743     // Recurse into linkage specifications
744     for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745                                  DIEnd = LSD->decls_end();
746          DI != DIEnd; ) {
747       if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748         if (!IFace->isThisDeclarationADefinition()) {
749           SmallVector<Decl *, 8> DG;
750           SourceLocation StartLoc = IFace->getBeginLoc();
751           do {
752             if (isa<ObjCInterfaceDecl>(*DI) &&
753                 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
754                 StartLoc == (*DI)->getBeginLoc())
755               DG.push_back(*DI);
756             else
757               break;
758 
759             ++DI;
760           } while (DI != DIEnd);
761           RewriteForwardClassDecl(DG);
762           continue;
763         }
764         else {
765           // Keep track of all interface declarations seen.
766           ObjCInterfacesSeen.push_back(IFace);
767           ++DI;
768           continue;
769         }
770       }
771 
772       if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773         if (!Proto->isThisDeclarationADefinition()) {
774           SmallVector<Decl *, 8> DG;
775           SourceLocation StartLoc = Proto->getBeginLoc();
776           do {
777             if (isa<ObjCProtocolDecl>(*DI) &&
778                 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
779                 StartLoc == (*DI)->getBeginLoc())
780               DG.push_back(*DI);
781             else
782               break;
783 
784             ++DI;
785           } while (DI != DIEnd);
786           RewriteForwardProtocolDecl(DG);
787           continue;
788         }
789       }
790 
791       HandleTopLevelSingleDecl(*DI);
792       ++DI;
793     }
794   }
795   // If we have a decl in the main file, see if we should rewrite it.
796   if (SM->isWrittenInMainFile(Loc))
797     return HandleDeclInMainFile(D);
798 }
799 
800 //===----------------------------------------------------------------------===//
801 // Syntactic (non-AST) Rewriting Code
802 //===----------------------------------------------------------------------===//
803 
804 void RewriteModernObjC::RewriteInclude() {
805   SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806   StringRef MainBuf = SM->getBufferData(MainFileID);
807   const char *MainBufStart = MainBuf.begin();
808   const char *MainBufEnd = MainBuf.end();
809   size_t ImportLen = strlen("import");
810 
811   // Loop over the whole file, looking for includes.
812   for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
813     if (*BufPtr == '#') {
814       if (++BufPtr == MainBufEnd)
815         return;
816       while (*BufPtr == ' ' || *BufPtr == '\t')
817         if (++BufPtr == MainBufEnd)
818           return;
819       if (!strncmp(BufPtr, "import", ImportLen)) {
820         // replace import with include
821         SourceLocation ImportLoc =
822           LocStart.getLocWithOffset(BufPtr-MainBufStart);
823         ReplaceText(ImportLoc, ImportLen, "include");
824         BufPtr += ImportLen;
825       }
826     }
827   }
828 }
829 
830 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831                                   ObjCIvarDecl *IvarDecl, std::string &Result) {
832   Result += "OBJC_IVAR_$_";
833   Result += IDecl->getName();
834   Result += "$";
835   Result += IvarDecl->getName();
836 }
837 
838 std::string
839 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840   const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
841 
842   // Build name of symbol holding ivar offset.
843   std::string IvarOffsetName;
844   if (D->isBitField())
845     ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846   else
847     WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
848 
849   std::string S = "(*(";
850   QualType IvarT = D->getType();
851   if (D->isBitField())
852     IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
853 
854   if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
855     RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
856     RD = RD->getDefinition();
857     if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858       // decltype(((Foo_IMPL*)0)->bar) *
859       auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
860       // ivar in class extensions requires special treatment.
861       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862         CDecl = CatDecl->getClassInterface();
863       std::string RecName = CDecl->getName();
864       RecName += "_IMPL";
865       RecordDecl *RD =
866           RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
867                              SourceLocation(), &Context->Idents.get(RecName));
868       QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869       unsigned UnsignedIntSize =
870       static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871       Expr *Zero = IntegerLiteral::Create(*Context,
872                                           llvm::APInt(UnsignedIntSize, 0),
873                                           Context->UnsignedIntTy, SourceLocation());
874       Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876                                               Zero);
877       FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
878                                         SourceLocation(),
879                                         &Context->Idents.get(D->getNameAsString()),
880                                         IvarT, nullptr,
881                                         /*BitWidth=*/nullptr, /*Mutable=*/true,
882                                         ICIS_NoInit);
883       MemberExpr *ME = MemberExpr::CreateImplicit(
884           *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
885       IvarT = Context->getDecltypeType(ME, ME->getType());
886     }
887   }
888   convertObjCTypeToCStyleType(IvarT);
889   QualType castT = Context->getPointerType(IvarT);
890   std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891   S += TypeString;
892   S += ")";
893 
894   // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895   S += "((char *)self + ";
896   S += IvarOffsetName;
897   S += "))";
898   if (D->isBitField()) {
899     S += ".";
900     S += D->getNameAsString();
901   }
902   ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
903   return S;
904 }
905 
906 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907 /// been found in the class implementation. In this case, it must be synthesized.
908 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909                                              ObjCPropertyDecl *PD,
910                                              bool getter) {
911   auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
912                                             : PD->getSetterName());
913   return !OMD || OMD->isSynthesizedAccessorStub();
914 }
915 
916 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917                                           ObjCImplementationDecl *IMD,
918                                           ObjCCategoryImplDecl *CID) {
919   static bool objcGetPropertyDefined = false;
920   static bool objcSetPropertyDefined = false;
921   SourceLocation startGetterSetterLoc;
922 
923   if (PID->getBeginLoc().isValid()) {
924     SourceLocation startLoc = PID->getBeginLoc();
925     InsertText(startLoc, "// ");
926     const char *startBuf = SM->getCharacterData(startLoc);
927     assert((*startBuf == '@') && "bogus @synthesize location");
928     const char *semiBuf = strchr(startBuf, ';');
929     assert((*semiBuf == ';') && "@synthesize: can't find ';'");
930     startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
931   } else
932     startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
933 
934   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935     return; // FIXME: is this correct?
936 
937   // Generate the 'getter' function.
938   ObjCPropertyDecl *PD = PID->getPropertyDecl();
939   ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
940   assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
941 
942   unsigned Attributes = PD->getPropertyAttributes();
943   if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
944     bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945                           (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
946                                          ObjCPropertyDecl::OBJC_PR_copy));
947     std::string Getr;
948     if (GenGetProperty && !objcGetPropertyDefined) {
949       objcGetPropertyDefined = true;
950       // FIXME. Is this attribute correct in all cases?
951       Getr = "\nextern \"C\" __declspec(dllimport) "
952             "id objc_getProperty(id, SEL, long, bool);\n";
953     }
954     RewriteObjCMethodDecl(OID->getContainingInterface(),
955                           PID->getGetterMethodDecl(), Getr);
956     Getr += "{ ";
957     // Synthesize an explicit cast to gain access to the ivar.
958     // See objc-act.c:objc_synthesize_new_getter() for details.
959     if (GenGetProperty) {
960       // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961       Getr += "typedef ";
962       const FunctionType *FPRetType = nullptr;
963       RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
964                             FPRetType);
965       Getr += " _TYPE";
966       if (FPRetType) {
967         Getr += ")"; // close the precedence "scope" for "*".
968 
969         // Now, emit the argument types (if any).
970         if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971           Getr += "(";
972           for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
973             if (i) Getr += ", ";
974             std::string ParamStr =
975                 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
976             Getr += ParamStr;
977           }
978           if (FT->isVariadic()) {
979             if (FT->getNumParams())
980               Getr += ", ";
981             Getr += "...";
982           }
983           Getr += ")";
984         } else
985           Getr += "()";
986       }
987       Getr += ";\n";
988       Getr += "return (_TYPE)";
989       Getr += "objc_getProperty(self, _cmd, ";
990       RewriteIvarOffsetComputation(OID, Getr);
991       Getr += ", 1)";
992     }
993     else
994       Getr += "return " + getIvarAccessString(OID);
995     Getr += "; }";
996     InsertText(startGetterSetterLoc, Getr);
997   }
998 
999   if (PD->isReadOnly() ||
1000       !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1001     return;
1002 
1003   // Generate the 'setter' function.
1004   std::string Setr;
1005   bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1006                                       ObjCPropertyDecl::OBJC_PR_copy);
1007   if (GenSetProperty && !objcSetPropertyDefined) {
1008     objcSetPropertyDefined = true;
1009     // FIXME. Is this attribute correct in all cases?
1010     Setr = "\nextern \"C\" __declspec(dllimport) "
1011     "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012   }
1013 
1014   RewriteObjCMethodDecl(OID->getContainingInterface(),
1015                         PID->getSetterMethodDecl(), Setr);
1016   Setr += "{ ";
1017   // Synthesize an explicit cast to initialize the ivar.
1018   // See objc-act.c:objc_synthesize_new_setter() for details.
1019   if (GenSetProperty) {
1020     Setr += "objc_setProperty (self, _cmd, ";
1021     RewriteIvarOffsetComputation(OID, Setr);
1022     Setr += ", (id)";
1023     Setr += PD->getName();
1024     Setr += ", ";
1025     if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1026       Setr += "0, ";
1027     else
1028       Setr += "1, ";
1029     if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1030       Setr += "1)";
1031     else
1032       Setr += "0)";
1033   }
1034   else {
1035     Setr += getIvarAccessString(OID) + " = ";
1036     Setr += PD->getName();
1037   }
1038   Setr += "; }\n";
1039   InsertText(startGetterSetterLoc, Setr);
1040 }
1041 
1042 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043                                        std::string &typedefString) {
1044   typedefString += "\n#ifndef _REWRITER_typedef_";
1045   typedefString += ForwardDecl->getNameAsString();
1046   typedefString += "\n";
1047   typedefString += "#define _REWRITER_typedef_";
1048   typedefString += ForwardDecl->getNameAsString();
1049   typedefString += "\n";
1050   typedefString += "typedef struct objc_object ";
1051   typedefString += ForwardDecl->getNameAsString();
1052   // typedef struct { } _objc_exc_Classname;
1053   typedefString += ";\ntypedef struct {} _objc_exc_";
1054   typedefString += ForwardDecl->getNameAsString();
1055   typedefString += ";\n#endif\n";
1056 }
1057 
1058 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059                                               const std::string &typedefString) {
1060   SourceLocation startLoc = ClassDecl->getBeginLoc();
1061   const char *startBuf = SM->getCharacterData(startLoc);
1062   const char *semiPtr = strchr(startBuf, ';');
1063   // Replace the @class with typedefs corresponding to the classes.
1064   ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1065 }
1066 
1067 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068   std::string typedefString;
1069   for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1070     if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1071       if (I == D.begin()) {
1072         // Translate to typedef's that forward reference structs with the same name
1073         // as the class. As a convenience, we include the original declaration
1074         // as a comment.
1075         typedefString += "// @class ";
1076         typedefString += ForwardDecl->getNameAsString();
1077         typedefString += ";";
1078       }
1079       RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1080     }
1081     else
1082       HandleTopLevelSingleDecl(*I);
1083   }
1084   DeclGroupRef::iterator I = D.begin();
1085   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086 }
1087 
1088 void RewriteModernObjC::RewriteForwardClassDecl(
1089                                 const SmallVectorImpl<Decl *> &D) {
1090   std::string typedefString;
1091   for (unsigned i = 0; i < D.size(); i++) {
1092     ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093     if (i == 0) {
1094       typedefString += "// @class ";
1095       typedefString += ForwardDecl->getNameAsString();
1096       typedefString += ";";
1097     }
1098     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099   }
1100   RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101 }
1102 
1103 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104   // When method is a synthesized one, such as a getter/setter there is
1105   // nothing to rewrite.
1106   if (Method->isImplicit())
1107     return;
1108   SourceLocation LocStart = Method->getBeginLoc();
1109   SourceLocation LocEnd = Method->getEndLoc();
1110 
1111   if (SM->getExpansionLineNumber(LocEnd) >
1112       SM->getExpansionLineNumber(LocStart)) {
1113     InsertText(LocStart, "#if 0\n");
1114     ReplaceText(LocEnd, 1, ";\n#endif\n");
1115   } else {
1116     InsertText(LocStart, "// ");
1117   }
1118 }
1119 
1120 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121   SourceLocation Loc = prop->getAtLoc();
1122 
1123   ReplaceText(Loc, 0, "// ");
1124   // FIXME: handle properties that are declared across multiple lines.
1125 }
1126 
1127 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128   SourceLocation LocStart = CatDecl->getBeginLoc();
1129 
1130   // FIXME: handle category headers that are declared across multiple lines.
1131   if (CatDecl->getIvarRBraceLoc().isValid()) {
1132     ReplaceText(LocStart, 1, "/** ");
1133     ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134   }
1135   else {
1136     ReplaceText(LocStart, 0, "// ");
1137   }
1138 
1139   for (auto *I : CatDecl->instance_properties())
1140     RewriteProperty(I);
1141 
1142   for (auto *I : CatDecl->instance_methods())
1143     RewriteMethodDeclaration(I);
1144   for (auto *I : CatDecl->class_methods())
1145     RewriteMethodDeclaration(I);
1146 
1147   // Lastly, comment out the @end.
1148   ReplaceText(CatDecl->getAtEndRange().getBegin(),
1149               strlen("@end"), "/* @end */\n");
1150 }
1151 
1152 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153   SourceLocation LocStart = PDecl->getBeginLoc();
1154   assert(PDecl->isThisDeclarationADefinition());
1155 
1156   // FIXME: handle protocol headers that are declared across multiple lines.
1157   ReplaceText(LocStart, 0, "// ");
1158 
1159   for (auto *I : PDecl->instance_methods())
1160     RewriteMethodDeclaration(I);
1161   for (auto *I : PDecl->class_methods())
1162     RewriteMethodDeclaration(I);
1163   for (auto *I : PDecl->instance_properties())
1164     RewriteProperty(I);
1165 
1166   // Lastly, comment out the @end.
1167   SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1168   ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1169 
1170   // Must comment out @optional/@required
1171   const char *startBuf = SM->getCharacterData(LocStart);
1172   const char *endBuf = SM->getCharacterData(LocEnd);
1173   for (const char *p = startBuf; p < endBuf; p++) {
1174     if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1175       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1176       ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1177 
1178     }
1179     else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1180       SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1181       ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1182 
1183     }
1184   }
1185 }
1186 
1187 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1188   SourceLocation LocStart = (*D.begin())->getBeginLoc();
1189   if (LocStart.isInvalid())
1190     llvm_unreachable("Invalid SourceLocation");
1191   // FIXME: handle forward protocol that are declared across multiple lines.
1192   ReplaceText(LocStart, 0, "// ");
1193 }
1194 
1195 void
1196 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1197   SourceLocation LocStart = DG[0]->getBeginLoc();
1198   if (LocStart.isInvalid())
1199     llvm_unreachable("Invalid SourceLocation");
1200   // FIXME: handle forward protocol that are declared across multiple lines.
1201   ReplaceText(LocStart, 0, "// ");
1202 }
1203 
1204 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1205                                         const FunctionType *&FPRetType) {
1206   if (T->isObjCQualifiedIdType())
1207     ResultStr += "id";
1208   else if (T->isFunctionPointerType() ||
1209            T->isBlockPointerType()) {
1210     // needs special handling, since pointer-to-functions have special
1211     // syntax (where a decaration models use).
1212     QualType retType = T;
1213     QualType PointeeTy;
1214     if (const PointerType* PT = retType->getAs<PointerType>())
1215       PointeeTy = PT->getPointeeType();
1216     else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1217       PointeeTy = BPT->getPointeeType();
1218     if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1219       ResultStr +=
1220           FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1221       ResultStr += "(*";
1222     }
1223   } else
1224     ResultStr += T.getAsString(Context->getPrintingPolicy());
1225 }
1226 
1227 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1228                                         ObjCMethodDecl *OMD,
1229                                         std::string &ResultStr) {
1230   //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1231   const FunctionType *FPRetType = nullptr;
1232   ResultStr += "\nstatic ";
1233   RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1234   ResultStr += " ";
1235 
1236   // Unique method name
1237   std::string NameStr;
1238 
1239   if (OMD->isInstanceMethod())
1240     NameStr += "_I_";
1241   else
1242     NameStr += "_C_";
1243 
1244   NameStr += IDecl->getNameAsString();
1245   NameStr += "_";
1246 
1247   if (ObjCCategoryImplDecl *CID =
1248       dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1249     NameStr += CID->getNameAsString();
1250     NameStr += "_";
1251   }
1252   // Append selector names, replacing ':' with '_'
1253   {
1254     std::string selString = OMD->getSelector().getAsString();
1255     int len = selString.size();
1256     for (int i = 0; i < len; i++)
1257       if (selString[i] == ':')
1258         selString[i] = '_';
1259     NameStr += selString;
1260   }
1261   // Remember this name for metadata emission
1262   MethodInternalNames[OMD] = NameStr;
1263   ResultStr += NameStr;
1264 
1265   // Rewrite arguments
1266   ResultStr += "(";
1267 
1268   // invisible arguments
1269   if (OMD->isInstanceMethod()) {
1270     QualType selfTy = Context->getObjCInterfaceType(IDecl);
1271     selfTy = Context->getPointerType(selfTy);
1272     if (!LangOpts.MicrosoftExt) {
1273       if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1274         ResultStr += "struct ";
1275     }
1276     // When rewriting for Microsoft, explicitly omit the structure name.
1277     ResultStr += IDecl->getNameAsString();
1278     ResultStr += " *";
1279   }
1280   else
1281     ResultStr += Context->getObjCClassType().getAsString(
1282       Context->getPrintingPolicy());
1283 
1284   ResultStr += " self, ";
1285   ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1286   ResultStr += " _cmd";
1287 
1288   // Method arguments.
1289   for (const auto *PDecl : OMD->parameters()) {
1290     ResultStr += ", ";
1291     if (PDecl->getType()->isObjCQualifiedIdType()) {
1292       ResultStr += "id ";
1293       ResultStr += PDecl->getNameAsString();
1294     } else {
1295       std::string Name = PDecl->getNameAsString();
1296       QualType QT = PDecl->getType();
1297       // Make sure we convert "t (^)(...)" to "t (*)(...)".
1298       (void)convertBlockPointerToFunctionPointer(QT);
1299       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1300       ResultStr += Name;
1301     }
1302   }
1303   if (OMD->isVariadic())
1304     ResultStr += ", ...";
1305   ResultStr += ") ";
1306 
1307   if (FPRetType) {
1308     ResultStr += ")"; // close the precedence "scope" for "*".
1309 
1310     // Now, emit the argument types (if any).
1311     if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1312       ResultStr += "(";
1313       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1314         if (i) ResultStr += ", ";
1315         std::string ParamStr =
1316             FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1317         ResultStr += ParamStr;
1318       }
1319       if (FT->isVariadic()) {
1320         if (FT->getNumParams())
1321           ResultStr += ", ";
1322         ResultStr += "...";
1323       }
1324       ResultStr += ")";
1325     } else {
1326       ResultStr += "()";
1327     }
1328   }
1329 }
1330 
1331 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1332   ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1333   ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1334   assert((IMD || CID) && "Unknown implementation type");
1335 
1336   if (IMD) {
1337     if (IMD->getIvarRBraceLoc().isValid()) {
1338       ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1339       ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1340     }
1341     else {
1342       InsertText(IMD->getBeginLoc(), "// ");
1343     }
1344   }
1345   else
1346     InsertText(CID->getBeginLoc(), "// ");
1347 
1348   for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1349     if (!OMD->getBody())
1350       continue;
1351     std::string ResultStr;
1352     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1353     SourceLocation LocStart = OMD->getBeginLoc();
1354     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1355 
1356     const char *startBuf = SM->getCharacterData(LocStart);
1357     const char *endBuf = SM->getCharacterData(LocEnd);
1358     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1359   }
1360 
1361   for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1362     if (!OMD->getBody())
1363       continue;
1364     std::string ResultStr;
1365     RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1366     SourceLocation LocStart = OMD->getBeginLoc();
1367     SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1368 
1369     const char *startBuf = SM->getCharacterData(LocStart);
1370     const char *endBuf = SM->getCharacterData(LocEnd);
1371     ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1372   }
1373   for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1374     RewritePropertyImplDecl(I, IMD, CID);
1375 
1376   InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1377 }
1378 
1379 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1380   // Do not synthesize more than once.
1381   if (ObjCSynthesizedStructs.count(ClassDecl))
1382     return;
1383   // Make sure super class's are written before current class is written.
1384   ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1385   while (SuperClass) {
1386     RewriteInterfaceDecl(SuperClass);
1387     SuperClass = SuperClass->getSuperClass();
1388   }
1389   std::string ResultStr;
1390   if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1391     // we haven't seen a forward decl - generate a typedef.
1392     RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1393     RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1394 
1395     RewriteObjCInternalStruct(ClassDecl, ResultStr);
1396     // Mark this typedef as having been written into its c++ equivalent.
1397     ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1398 
1399     for (auto *I : ClassDecl->instance_properties())
1400       RewriteProperty(I);
1401     for (auto *I : ClassDecl->instance_methods())
1402       RewriteMethodDeclaration(I);
1403     for (auto *I : ClassDecl->class_methods())
1404       RewriteMethodDeclaration(I);
1405 
1406     // Lastly, comment out the @end.
1407     ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1408                 "/* @end */\n");
1409   }
1410 }
1411 
1412 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1413   SourceRange OldRange = PseudoOp->getSourceRange();
1414 
1415   // We just magically know some things about the structure of this
1416   // expression.
1417   ObjCMessageExpr *OldMsg =
1418     cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1419                             PseudoOp->getNumSemanticExprs() - 1));
1420 
1421   // Because the rewriter doesn't allow us to rewrite rewritten code,
1422   // we need to suppress rewriting the sub-statements.
1423   Expr *Base;
1424   SmallVector<Expr*, 2> Args;
1425   {
1426     DisableReplaceStmtScope S(*this);
1427 
1428     // Rebuild the base expression if we have one.
1429     Base = nullptr;
1430     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1431       Base = OldMsg->getInstanceReceiver();
1432       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1433       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434     }
1435 
1436     unsigned numArgs = OldMsg->getNumArgs();
1437     for (unsigned i = 0; i < numArgs; i++) {
1438       Expr *Arg = OldMsg->getArg(i);
1439       if (isa<OpaqueValueExpr>(Arg))
1440         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1441       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1442       Args.push_back(Arg);
1443     }
1444   }
1445 
1446   // TODO: avoid this copy.
1447   SmallVector<SourceLocation, 1> SelLocs;
1448   OldMsg->getSelectorLocs(SelLocs);
1449 
1450   ObjCMessageExpr *NewMsg = nullptr;
1451   switch (OldMsg->getReceiverKind()) {
1452   case ObjCMessageExpr::Class:
1453     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1454                                      OldMsg->getValueKind(),
1455                                      OldMsg->getLeftLoc(),
1456                                      OldMsg->getClassReceiverTypeInfo(),
1457                                      OldMsg->getSelector(),
1458                                      SelLocs,
1459                                      OldMsg->getMethodDecl(),
1460                                      Args,
1461                                      OldMsg->getRightLoc(),
1462                                      OldMsg->isImplicit());
1463     break;
1464 
1465   case ObjCMessageExpr::Instance:
1466     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467                                      OldMsg->getValueKind(),
1468                                      OldMsg->getLeftLoc(),
1469                                      Base,
1470                                      OldMsg->getSelector(),
1471                                      SelLocs,
1472                                      OldMsg->getMethodDecl(),
1473                                      Args,
1474                                      OldMsg->getRightLoc(),
1475                                      OldMsg->isImplicit());
1476     break;
1477 
1478   case ObjCMessageExpr::SuperClass:
1479   case ObjCMessageExpr::SuperInstance:
1480     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1481                                      OldMsg->getValueKind(),
1482                                      OldMsg->getLeftLoc(),
1483                                      OldMsg->getSuperLoc(),
1484                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1485                                      OldMsg->getSuperType(),
1486                                      OldMsg->getSelector(),
1487                                      SelLocs,
1488                                      OldMsg->getMethodDecl(),
1489                                      Args,
1490                                      OldMsg->getRightLoc(),
1491                                      OldMsg->isImplicit());
1492     break;
1493   }
1494 
1495   Stmt *Replacement = SynthMessageExpr(NewMsg);
1496   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1497   return Replacement;
1498 }
1499 
1500 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1501   SourceRange OldRange = PseudoOp->getSourceRange();
1502 
1503   // We just magically know some things about the structure of this
1504   // expression.
1505   ObjCMessageExpr *OldMsg =
1506     cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1507 
1508   // Because the rewriter doesn't allow us to rewrite rewritten code,
1509   // we need to suppress rewriting the sub-statements.
1510   Expr *Base = nullptr;
1511   SmallVector<Expr*, 1> Args;
1512   {
1513     DisableReplaceStmtScope S(*this);
1514     // Rebuild the base expression if we have one.
1515     if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1516       Base = OldMsg->getInstanceReceiver();
1517       Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1518       Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1519     }
1520     unsigned numArgs = OldMsg->getNumArgs();
1521     for (unsigned i = 0; i < numArgs; i++) {
1522       Expr *Arg = OldMsg->getArg(i);
1523       if (isa<OpaqueValueExpr>(Arg))
1524         Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1525       Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1526       Args.push_back(Arg);
1527     }
1528   }
1529 
1530   // Intentionally empty.
1531   SmallVector<SourceLocation, 1> SelLocs;
1532 
1533   ObjCMessageExpr *NewMsg = nullptr;
1534   switch (OldMsg->getReceiverKind()) {
1535   case ObjCMessageExpr::Class:
1536     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1537                                      OldMsg->getValueKind(),
1538                                      OldMsg->getLeftLoc(),
1539                                      OldMsg->getClassReceiverTypeInfo(),
1540                                      OldMsg->getSelector(),
1541                                      SelLocs,
1542                                      OldMsg->getMethodDecl(),
1543                                      Args,
1544                                      OldMsg->getRightLoc(),
1545                                      OldMsg->isImplicit());
1546     break;
1547 
1548   case ObjCMessageExpr::Instance:
1549     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1550                                      OldMsg->getValueKind(),
1551                                      OldMsg->getLeftLoc(),
1552                                      Base,
1553                                      OldMsg->getSelector(),
1554                                      SelLocs,
1555                                      OldMsg->getMethodDecl(),
1556                                      Args,
1557                                      OldMsg->getRightLoc(),
1558                                      OldMsg->isImplicit());
1559     break;
1560 
1561   case ObjCMessageExpr::SuperClass:
1562   case ObjCMessageExpr::SuperInstance:
1563     NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1564                                      OldMsg->getValueKind(),
1565                                      OldMsg->getLeftLoc(),
1566                                      OldMsg->getSuperLoc(),
1567                  OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1568                                      OldMsg->getSuperType(),
1569                                      OldMsg->getSelector(),
1570                                      SelLocs,
1571                                      OldMsg->getMethodDecl(),
1572                                      Args,
1573                                      OldMsg->getRightLoc(),
1574                                      OldMsg->isImplicit());
1575     break;
1576   }
1577 
1578   Stmt *Replacement = SynthMessageExpr(NewMsg);
1579   ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1580   return Replacement;
1581 }
1582 
1583 /// SynthCountByEnumWithState - To print:
1584 /// ((NSUInteger (*)
1585 ///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1586 ///  (void *)objc_msgSend)((id)l_collection,
1587 ///                        sel_registerName(
1588 ///                          "countByEnumeratingWithState:objects:count:"),
1589 ///                        &enumState,
1590 ///                        (id *)__rw_items, (NSUInteger)16)
1591 ///
1592 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1593   buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1594   "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1595   buf += "\n\t\t";
1596   buf += "((id)l_collection,\n\t\t";
1597   buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1598   buf += "\n\t\t";
1599   buf += "&enumState, "
1600          "(id *)__rw_items, (_WIN_NSUInteger)16)";
1601 }
1602 
1603 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1604 /// statement to exit to its outer synthesized loop.
1605 ///
1606 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1607   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1608     return S;
1609   // replace break with goto __break_label
1610   std::string buf;
1611 
1612   SourceLocation startLoc = S->getBeginLoc();
1613   buf = "goto __break_label_";
1614   buf += utostr(ObjCBcLabelNo.back());
1615   ReplaceText(startLoc, strlen("break"), buf);
1616 
1617   return nullptr;
1618 }
1619 
1620 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1621                                           SourceLocation Loc,
1622                                           std::string &LineString) {
1623   if (Loc.isFileID() && GenerateLineInfo) {
1624     LineString += "\n#line ";
1625     PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1626     LineString += utostr(PLoc.getLine());
1627     LineString += " \"";
1628     LineString += Lexer::Stringify(PLoc.getFilename());
1629     LineString += "\"\n";
1630   }
1631 }
1632 
1633 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1634 /// statement to continue with its inner synthesized loop.
1635 ///
1636 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1637   if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1638     return S;
1639   // replace continue with goto __continue_label
1640   std::string buf;
1641 
1642   SourceLocation startLoc = S->getBeginLoc();
1643   buf = "goto __continue_label_";
1644   buf += utostr(ObjCBcLabelNo.back());
1645   ReplaceText(startLoc, strlen("continue"), buf);
1646 
1647   return nullptr;
1648 }
1649 
1650 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1651 ///  It rewrites:
1652 /// for ( type elem in collection) { stmts; }
1653 
1654 /// Into:
1655 /// {
1656 ///   type elem;
1657 ///   struct __objcFastEnumerationState enumState = { 0 };
1658 ///   id __rw_items[16];
1659 ///   id l_collection = (id)collection;
1660 ///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1661 ///                                       objects:__rw_items count:16];
1662 /// if (limit) {
1663 ///   unsigned long startMutations = *enumState.mutationsPtr;
1664 ///   do {
1665 ///        unsigned long counter = 0;
1666 ///        do {
1667 ///             if (startMutations != *enumState.mutationsPtr)
1668 ///               objc_enumerationMutation(l_collection);
1669 ///             elem = (type)enumState.itemsPtr[counter++];
1670 ///             stmts;
1671 ///             __continue_label: ;
1672 ///        } while (counter < limit);
1673 ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1674 ///                                  objects:__rw_items count:16]));
1675 ///   elem = nil;
1676 ///   __break_label: ;
1677 ///  }
1678 ///  else
1679 ///       elem = nil;
1680 ///  }
1681 ///
1682 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1683                                                 SourceLocation OrigEnd) {
1684   assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1685   assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1686          "ObjCForCollectionStmt Statement stack mismatch");
1687   assert(!ObjCBcLabelNo.empty() &&
1688          "ObjCForCollectionStmt - Label No stack empty");
1689 
1690   SourceLocation startLoc = S->getBeginLoc();
1691   const char *startBuf = SM->getCharacterData(startLoc);
1692   StringRef elementName;
1693   std::string elementTypeAsString;
1694   std::string buf;
1695   // line directive first.
1696   SourceLocation ForEachLoc = S->getForLoc();
1697   ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1698   buf += "{\n\t";
1699   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1700     // type elem;
1701     NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1702     QualType ElementType = cast<ValueDecl>(D)->getType();
1703     if (ElementType->isObjCQualifiedIdType() ||
1704         ElementType->isObjCQualifiedInterfaceType())
1705       // Simply use 'id' for all qualified types.
1706       elementTypeAsString = "id";
1707     else
1708       elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1709     buf += elementTypeAsString;
1710     buf += " ";
1711     elementName = D->getName();
1712     buf += elementName;
1713     buf += ";\n\t";
1714   }
1715   else {
1716     DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1717     elementName = DR->getDecl()->getName();
1718     ValueDecl *VD = DR->getDecl();
1719     if (VD->getType()->isObjCQualifiedIdType() ||
1720         VD->getType()->isObjCQualifiedInterfaceType())
1721       // Simply use 'id' for all qualified types.
1722       elementTypeAsString = "id";
1723     else
1724       elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1725   }
1726 
1727   // struct __objcFastEnumerationState enumState = { 0 };
1728   buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1729   // id __rw_items[16];
1730   buf += "id __rw_items[16];\n\t";
1731   // id l_collection = (id)
1732   buf += "id l_collection = (id)";
1733   // Find start location of 'collection' the hard way!
1734   const char *startCollectionBuf = startBuf;
1735   startCollectionBuf += 3;  // skip 'for'
1736   startCollectionBuf = strchr(startCollectionBuf, '(');
1737   startCollectionBuf++; // skip '('
1738   // find 'in' and skip it.
1739   while (*startCollectionBuf != ' ' ||
1740          *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1741          (*(startCollectionBuf+3) != ' ' &&
1742           *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1743     startCollectionBuf++;
1744   startCollectionBuf += 3;
1745 
1746   // Replace: "for (type element in" with string constructed thus far.
1747   ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1748   // Replace ')' in for '(' type elem in collection ')' with ';'
1749   SourceLocation rightParenLoc = S->getRParenLoc();
1750   const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1751   SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1752   buf = ";\n\t";
1753 
1754   // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1755   //                                   objects:__rw_items count:16];
1756   // which is synthesized into:
1757   // NSUInteger limit =
1758   // ((NSUInteger (*)
1759   //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1760   //  (void *)objc_msgSend)((id)l_collection,
1761   //                        sel_registerName(
1762   //                          "countByEnumeratingWithState:objects:count:"),
1763   //                        (struct __objcFastEnumerationState *)&state,
1764   //                        (id *)__rw_items, (NSUInteger)16);
1765   buf += "_WIN_NSUInteger limit =\n\t\t";
1766   SynthCountByEnumWithState(buf);
1767   buf += ";\n\t";
1768   /// if (limit) {
1769   ///   unsigned long startMutations = *enumState.mutationsPtr;
1770   ///   do {
1771   ///        unsigned long counter = 0;
1772   ///        do {
1773   ///             if (startMutations != *enumState.mutationsPtr)
1774   ///               objc_enumerationMutation(l_collection);
1775   ///             elem = (type)enumState.itemsPtr[counter++];
1776   buf += "if (limit) {\n\t";
1777   buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1778   buf += "do {\n\t\t";
1779   buf += "unsigned long counter = 0;\n\t\t";
1780   buf += "do {\n\t\t\t";
1781   buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1782   buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1783   buf += elementName;
1784   buf += " = (";
1785   buf += elementTypeAsString;
1786   buf += ")enumState.itemsPtr[counter++];";
1787   // Replace ')' in for '(' type elem in collection ')' with all of these.
1788   ReplaceText(lparenLoc, 1, buf);
1789 
1790   ///            __continue_label: ;
1791   ///        } while (counter < limit);
1792   ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1793   ///                                  objects:__rw_items count:16]));
1794   ///   elem = nil;
1795   ///   __break_label: ;
1796   ///  }
1797   ///  else
1798   ///       elem = nil;
1799   ///  }
1800   ///
1801   buf = ";\n\t";
1802   buf += "__continue_label_";
1803   buf += utostr(ObjCBcLabelNo.back());
1804   buf += ": ;";
1805   buf += "\n\t\t";
1806   buf += "} while (counter < limit);\n\t";
1807   buf += "} while ((limit = ";
1808   SynthCountByEnumWithState(buf);
1809   buf += "));\n\t";
1810   buf += elementName;
1811   buf += " = ((";
1812   buf += elementTypeAsString;
1813   buf += ")0);\n\t";
1814   buf += "__break_label_";
1815   buf += utostr(ObjCBcLabelNo.back());
1816   buf += ": ;\n\t";
1817   buf += "}\n\t";
1818   buf += "else\n\t\t";
1819   buf += elementName;
1820   buf += " = ((";
1821   buf += elementTypeAsString;
1822   buf += ")0);\n\t";
1823   buf += "}\n";
1824 
1825   // Insert all these *after* the statement body.
1826   // FIXME: If this should support Obj-C++, support CXXTryStmt
1827   if (isa<CompoundStmt>(S->getBody())) {
1828     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1829     InsertText(endBodyLoc, buf);
1830   } else {
1831     /* Need to treat single statements specially. For example:
1832      *
1833      *     for (A *a in b) if (stuff()) break;
1834      *     for (A *a in b) xxxyy;
1835      *
1836      * The following code simply scans ahead to the semi to find the actual end.
1837      */
1838     const char *stmtBuf = SM->getCharacterData(OrigEnd);
1839     const char *semiBuf = strchr(stmtBuf, ';');
1840     assert(semiBuf && "Can't find ';'");
1841     SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1842     InsertText(endBodyLoc, buf);
1843   }
1844   Stmts.pop_back();
1845   ObjCBcLabelNo.pop_back();
1846   return nullptr;
1847 }
1848 
1849 static void Write_RethrowObject(std::string &buf) {
1850   buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1851   buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1852   buf += "\tid rethrow;\n";
1853   buf += "\t} _fin_force_rethow(_rethrow);";
1854 }
1855 
1856 /// RewriteObjCSynchronizedStmt -
1857 /// This routine rewrites @synchronized(expr) stmt;
1858 /// into:
1859 /// objc_sync_enter(expr);
1860 /// @try stmt @finally { objc_sync_exit(expr); }
1861 ///
1862 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1863   // Get the start location and compute the semi location.
1864   SourceLocation startLoc = S->getBeginLoc();
1865   const char *startBuf = SM->getCharacterData(startLoc);
1866 
1867   assert((*startBuf == '@') && "bogus @synchronized location");
1868 
1869   std::string buf;
1870   SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1871   ConvertSourceLocationToLineDirective(SynchLoc, buf);
1872   buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1873 
1874   const char *lparenBuf = startBuf;
1875   while (*lparenBuf != '(') lparenBuf++;
1876   ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1877 
1878   buf = "; objc_sync_enter(_sync_obj);\n";
1879   buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1880   buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1881   buf += "\n\tid sync_exit;";
1882   buf += "\n\t} _sync_exit(_sync_obj);\n";
1883 
1884   // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1885   // the sync expression is typically a message expression that's already
1886   // been rewritten! (which implies the SourceLocation's are invalid).
1887   SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1888   const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1889   while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1890   RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1891 
1892   SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1893   const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1894   assert (*LBraceLocBuf == '{');
1895   ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1896 
1897   SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1898   assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1899          "bogus @synchronized block");
1900 
1901   buf = "} catch (id e) {_rethrow = e;}\n";
1902   Write_RethrowObject(buf);
1903   buf += "}\n";
1904   buf += "}\n";
1905 
1906   ReplaceText(startRBraceLoc, 1, buf);
1907 
1908   return nullptr;
1909 }
1910 
1911 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1912 {
1913   // Perform a bottom up traversal of all children.
1914   for (Stmt *SubStmt : S->children())
1915     if (SubStmt)
1916       WarnAboutReturnGotoStmts(SubStmt);
1917 
1918   if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1919     Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1920                  TryFinallyContainsReturnDiag);
1921   }
1922 }
1923 
1924 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1925   SourceLocation startLoc = S->getAtLoc();
1926   ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1927   ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1928               "{ __AtAutoreleasePool __autoreleasepool; ");
1929 
1930   return nullptr;
1931 }
1932 
1933 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1934   ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1935   bool noCatch = S->getNumCatchStmts() == 0;
1936   std::string buf;
1937   SourceLocation TryLocation = S->getAtTryLoc();
1938   ConvertSourceLocationToLineDirective(TryLocation, buf);
1939 
1940   if (finalStmt) {
1941     if (noCatch)
1942       buf += "{ id volatile _rethrow = 0;\n";
1943     else {
1944       buf += "{ id volatile _rethrow = 0;\ntry {\n";
1945     }
1946   }
1947   // Get the start location and compute the semi location.
1948   SourceLocation startLoc = S->getBeginLoc();
1949   const char *startBuf = SM->getCharacterData(startLoc);
1950 
1951   assert((*startBuf == '@') && "bogus @try location");
1952   if (finalStmt)
1953     ReplaceText(startLoc, 1, buf);
1954   else
1955     // @try -> try
1956     ReplaceText(startLoc, 1, "");
1957 
1958   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1959     ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1960     VarDecl *catchDecl = Catch->getCatchParamDecl();
1961 
1962     startLoc = Catch->getBeginLoc();
1963     bool AtRemoved = false;
1964     if (catchDecl) {
1965       QualType t = catchDecl->getType();
1966       if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1967         // Should be a pointer to a class.
1968         ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1969         if (IDecl) {
1970           std::string Result;
1971           ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1972 
1973           startBuf = SM->getCharacterData(startLoc);
1974           assert((*startBuf == '@') && "bogus @catch location");
1975           SourceLocation rParenLoc = Catch->getRParenLoc();
1976           const char *rParenBuf = SM->getCharacterData(rParenLoc);
1977 
1978           // _objc_exc_Foo *_e as argument to catch.
1979           Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1980           Result += " *_"; Result += catchDecl->getNameAsString();
1981           Result += ")";
1982           ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1983           // Foo *e = (Foo *)_e;
1984           Result.clear();
1985           Result = "{ ";
1986           Result += IDecl->getNameAsString();
1987           Result += " *"; Result += catchDecl->getNameAsString();
1988           Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1989           Result += "_"; Result += catchDecl->getNameAsString();
1990 
1991           Result += "; ";
1992           SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1993           ReplaceText(lBraceLoc, 1, Result);
1994           AtRemoved = true;
1995         }
1996       }
1997     }
1998     if (!AtRemoved)
1999       // @catch -> catch
2000       ReplaceText(startLoc, 1, "");
2001 
2002   }
2003   if (finalStmt) {
2004     buf.clear();
2005     SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2006 
2007     if (noCatch) {
2008       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2009       buf += "catch (id e) {_rethrow = e;}\n";
2010     }
2011     else {
2012       buf += "}\n";
2013       ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2014       buf += "catch (id e) {_rethrow = e;}\n";
2015     }
2016 
2017     SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2018     ReplaceText(startFinalLoc, 8, buf);
2019     Stmt *body = finalStmt->getFinallyBody();
2020     SourceLocation startFinalBodyLoc = body->getBeginLoc();
2021     buf.clear();
2022     Write_RethrowObject(buf);
2023     ReplaceText(startFinalBodyLoc, 1, buf);
2024 
2025     SourceLocation endFinalBodyLoc = body->getEndLoc();
2026     ReplaceText(endFinalBodyLoc, 1, "}\n}");
2027     // Now check for any return/continue/go statements within the @try.
2028     WarnAboutReturnGotoStmts(S->getTryBody());
2029   }
2030 
2031   return nullptr;
2032 }
2033 
2034 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2035 // the throw expression is typically a message expression that's already
2036 // been rewritten! (which implies the SourceLocation's are invalid).
2037 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2038   // Get the start location and compute the semi location.
2039   SourceLocation startLoc = S->getBeginLoc();
2040   const char *startBuf = SM->getCharacterData(startLoc);
2041 
2042   assert((*startBuf == '@') && "bogus @throw location");
2043 
2044   std::string buf;
2045   /* void objc_exception_throw(id) __attribute__((noreturn)); */
2046   if (S->getThrowExpr())
2047     buf = "objc_exception_throw(";
2048   else
2049     buf = "throw";
2050 
2051   // handle "@  throw" correctly.
2052   const char *wBuf = strchr(startBuf, 'w');
2053   assert((*wBuf == 'w') && "@throw: can't find 'w'");
2054   ReplaceText(startLoc, wBuf-startBuf+1, buf);
2055 
2056   SourceLocation endLoc = S->getEndLoc();
2057   const char *endBuf = SM->getCharacterData(endLoc);
2058   const char *semiBuf = strchr(endBuf, ';');
2059   assert((*semiBuf == ';') && "@throw: can't find ';'");
2060   SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2061   if (S->getThrowExpr())
2062     ReplaceText(semiLoc, 1, ");");
2063   return nullptr;
2064 }
2065 
2066 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2067   // Create a new string expression.
2068   std::string StrEncoding;
2069   Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2070   Expr *Replacement = getStringLiteral(StrEncoding);
2071   ReplaceStmt(Exp, Replacement);
2072 
2073   // Replace this subexpr in the parent.
2074   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2075   return Replacement;
2076 }
2077 
2078 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2079   if (!SelGetUidFunctionDecl)
2080     SynthSelGetUidFunctionDecl();
2081   assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2082   // Create a call to sel_registerName("selName").
2083   SmallVector<Expr*, 8> SelExprs;
2084   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2085   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2086                                                   SelExprs);
2087   ReplaceStmt(Exp, SelExp);
2088   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2089   return SelExp;
2090 }
2091 
2092 CallExpr *
2093 RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2094                                                 ArrayRef<Expr *> Args,
2095                                                 SourceLocation StartLoc,
2096                                                 SourceLocation EndLoc) {
2097   // Get the type, we will need to reference it in a couple spots.
2098   QualType msgSendType = FD->getType();
2099 
2100   // Create a reference to the objc_msgSend() declaration.
2101   DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2102                                                VK_LValue, SourceLocation());
2103 
2104   // Now, we cast the reference to a pointer to the objc_msgSend type.
2105   QualType pToFunc = Context->getPointerType(msgSendType);
2106   ImplicitCastExpr *ICE =
2107     ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2108                              DRE, nullptr, VK_RValue);
2109 
2110   const auto *FT = msgSendType->castAs<FunctionType>();
2111   CallExpr *Exp = CallExpr::Create(
2112       *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2113   return Exp;
2114 }
2115 
2116 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2117                                 const char *&startRef, const char *&endRef) {
2118   while (startBuf < endBuf) {
2119     if (*startBuf == '<')
2120       startRef = startBuf; // mark the start.
2121     if (*startBuf == '>') {
2122       if (startRef && *startRef == '<') {
2123         endRef = startBuf; // mark the end.
2124         return true;
2125       }
2126       return false;
2127     }
2128     startBuf++;
2129   }
2130   return false;
2131 }
2132 
2133 static void scanToNextArgument(const char *&argRef) {
2134   int angle = 0;
2135   while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2136     if (*argRef == '<')
2137       angle++;
2138     else if (*argRef == '>')
2139       angle--;
2140     argRef++;
2141   }
2142   assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2143 }
2144 
2145 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2146   if (T->isObjCQualifiedIdType())
2147     return true;
2148   if (const PointerType *PT = T->getAs<PointerType>()) {
2149     if (PT->getPointeeType()->isObjCQualifiedIdType())
2150       return true;
2151   }
2152   if (T->isObjCObjectPointerType()) {
2153     T = T->getPointeeType();
2154     return T->isObjCQualifiedInterfaceType();
2155   }
2156   if (T->isArrayType()) {
2157     QualType ElemTy = Context->getBaseElementType(T);
2158     return needToScanForQualifiers(ElemTy);
2159   }
2160   return false;
2161 }
2162 
2163 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2164   QualType Type = E->getType();
2165   if (needToScanForQualifiers(Type)) {
2166     SourceLocation Loc, EndLoc;
2167 
2168     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2169       Loc = ECE->getLParenLoc();
2170       EndLoc = ECE->getRParenLoc();
2171     } else {
2172       Loc = E->getBeginLoc();
2173       EndLoc = E->getEndLoc();
2174     }
2175     // This will defend against trying to rewrite synthesized expressions.
2176     if (Loc.isInvalid() || EndLoc.isInvalid())
2177       return;
2178 
2179     const char *startBuf = SM->getCharacterData(Loc);
2180     const char *endBuf = SM->getCharacterData(EndLoc);
2181     const char *startRef = nullptr, *endRef = nullptr;
2182     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183       // Get the locations of the startRef, endRef.
2184       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2185       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2186       // Comment out the protocol references.
2187       InsertText(LessLoc, "/*");
2188       InsertText(GreaterLoc, "*/");
2189     }
2190   }
2191 }
2192 
2193 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2194   SourceLocation Loc;
2195   QualType Type;
2196   const FunctionProtoType *proto = nullptr;
2197   if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2198     Loc = VD->getLocation();
2199     Type = VD->getType();
2200   }
2201   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2202     Loc = FD->getLocation();
2203     // Check for ObjC 'id' and class types that have been adorned with protocol
2204     // information (id<p>, C<p>*). The protocol references need to be rewritten!
2205     const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2206     assert(funcType && "missing function type");
2207     proto = dyn_cast<FunctionProtoType>(funcType);
2208     if (!proto)
2209       return;
2210     Type = proto->getReturnType();
2211   }
2212   else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2213     Loc = FD->getLocation();
2214     Type = FD->getType();
2215   }
2216   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2217     Loc = TD->getLocation();
2218     Type = TD->getUnderlyingType();
2219   }
2220   else
2221     return;
2222 
2223   if (needToScanForQualifiers(Type)) {
2224     // Since types are unique, we need to scan the buffer.
2225 
2226     const char *endBuf = SM->getCharacterData(Loc);
2227     const char *startBuf = endBuf;
2228     while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2229       startBuf--; // scan backward (from the decl location) for return type.
2230     const char *startRef = nullptr, *endRef = nullptr;
2231     if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2232       // Get the locations of the startRef, endRef.
2233       SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2234       SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2235       // Comment out the protocol references.
2236       InsertText(LessLoc, "/*");
2237       InsertText(GreaterLoc, "*/");
2238     }
2239   }
2240   if (!proto)
2241       return; // most likely, was a variable
2242   // Now check arguments.
2243   const char *startBuf = SM->getCharacterData(Loc);
2244   const char *startFuncBuf = startBuf;
2245   for (unsigned i = 0; i < proto->getNumParams(); i++) {
2246     if (needToScanForQualifiers(proto->getParamType(i))) {
2247       // Since types are unique, we need to scan the buffer.
2248 
2249       const char *endBuf = startBuf;
2250       // scan forward (from the decl location) for argument types.
2251       scanToNextArgument(endBuf);
2252       const char *startRef = nullptr, *endRef = nullptr;
2253       if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2254         // Get the locations of the startRef, endRef.
2255         SourceLocation LessLoc =
2256           Loc.getLocWithOffset(startRef-startFuncBuf);
2257         SourceLocation GreaterLoc =
2258           Loc.getLocWithOffset(endRef-startFuncBuf+1);
2259         // Comment out the protocol references.
2260         InsertText(LessLoc, "/*");
2261         InsertText(GreaterLoc, "*/");
2262       }
2263       startBuf = ++endBuf;
2264     }
2265     else {
2266       // If the function name is derived from a macro expansion, then the
2267       // argument buffer will not follow the name. Need to speak with Chris.
2268       while (*startBuf && *startBuf != ')' && *startBuf != ',')
2269         startBuf++; // scan forward (from the decl location) for argument types.
2270       startBuf++;
2271     }
2272   }
2273 }
2274 
2275 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2276   QualType QT = ND->getType();
2277   const Type* TypePtr = QT->getAs<Type>();
2278   if (!isa<TypeOfExprType>(TypePtr))
2279     return;
2280   while (isa<TypeOfExprType>(TypePtr)) {
2281     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2282     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2283     TypePtr = QT->getAs<Type>();
2284   }
2285   // FIXME. This will not work for multiple declarators; as in:
2286   // __typeof__(a) b,c,d;
2287   std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2288   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2289   const char *startBuf = SM->getCharacterData(DeclLoc);
2290   if (ND->getInit()) {
2291     std::string Name(ND->getNameAsString());
2292     TypeAsString += " " + Name + " = ";
2293     Expr *E = ND->getInit();
2294     SourceLocation startLoc;
2295     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2296       startLoc = ECE->getLParenLoc();
2297     else
2298       startLoc = E->getBeginLoc();
2299     startLoc = SM->getExpansionLoc(startLoc);
2300     const char *endBuf = SM->getCharacterData(startLoc);
2301     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2302   }
2303   else {
2304     SourceLocation X = ND->getEndLoc();
2305     X = SM->getExpansionLoc(X);
2306     const char *endBuf = SM->getCharacterData(X);
2307     ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2308   }
2309 }
2310 
2311 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2312 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2313   IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2314   SmallVector<QualType, 16> ArgTys;
2315   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2316   QualType getFuncType =
2317     getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2318   SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319                                                SourceLocation(),
2320                                                SourceLocation(),
2321                                                SelGetUidIdent, getFuncType,
2322                                                nullptr, SC_Extern);
2323 }
2324 
2325 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2326   // declared in <objc/objc.h>
2327   if (FD->getIdentifier() &&
2328       FD->getName() == "sel_registerName") {
2329     SelGetUidFunctionDecl = FD;
2330     return;
2331   }
2332   RewriteObjCQualifiedInterfaceTypes(FD);
2333 }
2334 
2335 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2336   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2337   const char *argPtr = TypeString.c_str();
2338   if (!strchr(argPtr, '^')) {
2339     Str += TypeString;
2340     return;
2341   }
2342   while (*argPtr) {
2343     Str += (*argPtr == '^' ? '*' : *argPtr);
2344     argPtr++;
2345   }
2346 }
2347 
2348 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2349 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350                                                   ValueDecl *VD) {
2351   QualType Type = VD->getType();
2352   std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2353   const char *argPtr = TypeString.c_str();
2354   int paren = 0;
2355   while (*argPtr) {
2356     switch (*argPtr) {
2357       case '(':
2358         Str += *argPtr;
2359         paren++;
2360         break;
2361       case ')':
2362         Str += *argPtr;
2363         paren--;
2364         break;
2365       case '^':
2366         Str += '*';
2367         if (paren == 1)
2368           Str += VD->getNameAsString();
2369         break;
2370       default:
2371         Str += *argPtr;
2372         break;
2373     }
2374     argPtr++;
2375   }
2376 }
2377 
2378 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2379   SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2380   const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2381   const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2382   if (!proto)
2383     return;
2384   QualType Type = proto->getReturnType();
2385   std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2386   FdStr += " ";
2387   FdStr += FD->getName();
2388   FdStr +=  "(";
2389   unsigned numArgs = proto->getNumParams();
2390   for (unsigned i = 0; i < numArgs; i++) {
2391     QualType ArgType = proto->getParamType(i);
2392   RewriteBlockPointerType(FdStr, ArgType);
2393   if (i+1 < numArgs)
2394     FdStr += ", ";
2395   }
2396   if (FD->isVariadic()) {
2397     FdStr +=  (numArgs > 0) ? ", ...);\n" : "...);\n";
2398   }
2399   else
2400     FdStr +=  ");\n";
2401   InsertText(FunLocStart, FdStr);
2402 }
2403 
2404 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2405 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2406   if (SuperConstructorFunctionDecl)
2407     return;
2408   IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2409   SmallVector<QualType, 16> ArgTys;
2410   QualType argT = Context->getObjCIdType();
2411   assert(!argT.isNull() && "Can't find 'id' type");
2412   ArgTys.push_back(argT);
2413   ArgTys.push_back(argT);
2414   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2415                                                ArgTys);
2416   SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2417                                                      SourceLocation(),
2418                                                      SourceLocation(),
2419                                                      msgSendIdent, msgSendType,
2420                                                      nullptr, SC_Extern);
2421 }
2422 
2423 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2424 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2425   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2426   SmallVector<QualType, 16> ArgTys;
2427   QualType argT = Context->getObjCIdType();
2428   assert(!argT.isNull() && "Can't find 'id' type");
2429   ArgTys.push_back(argT);
2430   argT = Context->getObjCSelType();
2431   assert(!argT.isNull() && "Can't find 'SEL' type");
2432   ArgTys.push_back(argT);
2433   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2434                                                ArgTys, /*variadic=*/true);
2435   MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2436                                              SourceLocation(),
2437                                              SourceLocation(),
2438                                              msgSendIdent, msgSendType, nullptr,
2439                                              SC_Extern);
2440 }
2441 
2442 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2443 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2444   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2445   SmallVector<QualType, 2> ArgTys;
2446   ArgTys.push_back(Context->VoidTy);
2447   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2448                                                ArgTys, /*variadic=*/true);
2449   MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2450                                                   SourceLocation(),
2451                                                   SourceLocation(),
2452                                                   msgSendIdent, msgSendType,
2453                                                   nullptr, SC_Extern);
2454 }
2455 
2456 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2457 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2458   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2459   SmallVector<QualType, 16> ArgTys;
2460   QualType argT = Context->getObjCIdType();
2461   assert(!argT.isNull() && "Can't find 'id' type");
2462   ArgTys.push_back(argT);
2463   argT = Context->getObjCSelType();
2464   assert(!argT.isNull() && "Can't find 'SEL' type");
2465   ArgTys.push_back(argT);
2466   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2467                                                ArgTys, /*variadic=*/true);
2468   MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469                                                   SourceLocation(),
2470                                                   SourceLocation(),
2471                                                   msgSendIdent, msgSendType,
2472                                                   nullptr, SC_Extern);
2473 }
2474 
2475 // SynthMsgSendSuperStretFunctionDecl -
2476 // id objc_msgSendSuper_stret(void);
2477 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2478   IdentifierInfo *msgSendIdent =
2479     &Context->Idents.get("objc_msgSendSuper_stret");
2480   SmallVector<QualType, 2> ArgTys;
2481   ArgTys.push_back(Context->VoidTy);
2482   QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483                                                ArgTys, /*variadic=*/true);
2484   MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2485                                                        SourceLocation(),
2486                                                        SourceLocation(),
2487                                                        msgSendIdent,
2488                                                        msgSendType, nullptr,
2489                                                        SC_Extern);
2490 }
2491 
2492 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494   IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495   SmallVector<QualType, 16> ArgTys;
2496   QualType argT = Context->getObjCIdType();
2497   assert(!argT.isNull() && "Can't find 'id' type");
2498   ArgTys.push_back(argT);
2499   argT = Context->getObjCSelType();
2500   assert(!argT.isNull() && "Can't find 'SEL' type");
2501   ArgTys.push_back(argT);
2502   QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2503                                                ArgTys, /*variadic=*/true);
2504   MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505                                                   SourceLocation(),
2506                                                   SourceLocation(),
2507                                                   msgSendIdent, msgSendType,
2508                                                   nullptr, SC_Extern);
2509 }
2510 
2511 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2512 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2513   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2514   SmallVector<QualType, 16> ArgTys;
2515   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2516   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2517                                                 ArgTys);
2518   GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519                                               SourceLocation(),
2520                                               SourceLocation(),
2521                                               getClassIdent, getClassType,
2522                                               nullptr, SC_Extern);
2523 }
2524 
2525 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2526 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2527   IdentifierInfo *getSuperClassIdent =
2528     &Context->Idents.get("class_getSuperclass");
2529   SmallVector<QualType, 16> ArgTys;
2530   ArgTys.push_back(Context->getObjCClassType());
2531   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2532                                                 ArgTys);
2533   GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2534                                                    SourceLocation(),
2535                                                    SourceLocation(),
2536                                                    getSuperClassIdent,
2537                                                    getClassType, nullptr,
2538                                                    SC_Extern);
2539 }
2540 
2541 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2542 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2543   IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2544   SmallVector<QualType, 16> ArgTys;
2545   ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2546   QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2547                                                 ArgTys);
2548   GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2549                                                   SourceLocation(),
2550                                                   SourceLocation(),
2551                                                   getClassIdent, getClassType,
2552                                                   nullptr, SC_Extern);
2553 }
2554 
2555 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2556   assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2557   QualType strType = getConstantStringStructType();
2558 
2559   std::string S = "__NSConstantStringImpl_";
2560 
2561   std::string tmpName = InFileName;
2562   unsigned i;
2563   for (i=0; i < tmpName.length(); i++) {
2564     char c = tmpName.at(i);
2565     // replace any non-alphanumeric characters with '_'.
2566     if (!isAlphanumeric(c))
2567       tmpName[i] = '_';
2568   }
2569   S += tmpName;
2570   S += "_";
2571   S += utostr(NumObjCStringLiterals++);
2572 
2573   Preamble += "static __NSConstantStringImpl " + S;
2574   Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2575   Preamble += "0x000007c8,"; // utf8_str
2576   // The pretty printer for StringLiteral handles escape characters properly.
2577   std::string prettyBufS;
2578   llvm::raw_string_ostream prettyBuf(prettyBufS);
2579   Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2580   Preamble += prettyBuf.str();
2581   Preamble += ",";
2582   Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2583 
2584   VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2585                                    SourceLocation(), &Context->Idents.get(S),
2586                                    strType, nullptr, SC_Static);
2587   DeclRefExpr *DRE = new (Context)
2588       DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2589   Expr *Unop = new (Context)
2590       UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2591                     VK_RValue, OK_Ordinary, SourceLocation(), false);
2592   // cast to NSConstantString *
2593   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2594                                             CK_CPointerToObjCPointerCast, Unop);
2595   ReplaceStmt(Exp, cast);
2596   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2597   return cast;
2598 }
2599 
2600 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2601   unsigned IntSize =
2602     static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2603 
2604   Expr *FlagExp = IntegerLiteral::Create(*Context,
2605                                          llvm::APInt(IntSize, Exp->getValue()),
2606                                          Context->IntTy, Exp->getLocation());
2607   CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2608                                             CK_BitCast, FlagExp);
2609   ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2610                                           cast);
2611   ReplaceStmt(Exp, PE);
2612   return PE;
2613 }
2614 
2615 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2616   // synthesize declaration of helper functions needed in this routine.
2617   if (!SelGetUidFunctionDecl)
2618     SynthSelGetUidFunctionDecl();
2619   // use objc_msgSend() for all.
2620   if (!MsgSendFunctionDecl)
2621     SynthMsgSendFunctionDecl();
2622   if (!GetClassFunctionDecl)
2623     SynthGetClassFunctionDecl();
2624 
2625   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2626   SourceLocation StartLoc = Exp->getBeginLoc();
2627   SourceLocation EndLoc = Exp->getEndLoc();
2628 
2629   // Synthesize a call to objc_msgSend().
2630   SmallVector<Expr*, 4> MsgExprs;
2631   SmallVector<Expr*, 4> ClsExprs;
2632 
2633   // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2634   ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2635   ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2636 
2637   IdentifierInfo *clsName = BoxingClass->getIdentifier();
2638   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2639   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2640                                                StartLoc, EndLoc);
2641   MsgExprs.push_back(Cls);
2642 
2643   // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2644   // it will be the 2nd argument.
2645   SmallVector<Expr*, 4> SelExprs;
2646   SelExprs.push_back(
2647       getStringLiteral(BoxingMethod->getSelector().getAsString()));
2648   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2649                                                   SelExprs, StartLoc, EndLoc);
2650   MsgExprs.push_back(SelExp);
2651 
2652   // User provided sub-expression is the 3rd, and last, argument.
2653   Expr *subExpr  = Exp->getSubExpr();
2654   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2655     QualType type = ICE->getType();
2656     const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2657     CastKind CK = CK_BitCast;
2658     if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2659       CK = CK_IntegralToBoolean;
2660     subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2661   }
2662   MsgExprs.push_back(subExpr);
2663 
2664   SmallVector<QualType, 4> ArgTypes;
2665   ArgTypes.push_back(Context->getObjCClassType());
2666   ArgTypes.push_back(Context->getObjCSelType());
2667   for (const auto PI : BoxingMethod->parameters())
2668     ArgTypes.push_back(PI->getType());
2669 
2670   QualType returnType = Exp->getType();
2671   // Get the type, we will need to reference it in a couple spots.
2672   QualType msgSendType = MsgSendFlavor->getType();
2673 
2674   // Create a reference to the objc_msgSend() declaration.
2675   DeclRefExpr *DRE = new (Context) DeclRefExpr(
2676       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2677 
2678   CastExpr *cast = NoTypeInfoCStyleCastExpr(
2679       Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2680 
2681   // Now do the "normal" pointer to function cast.
2682   QualType castType =
2683     getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2684   castType = Context->getPointerType(castType);
2685   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2686                                   cast);
2687 
2688   // Don't forget the parens to enforce the proper binding.
2689   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2690 
2691   const FunctionType *FT = msgSendType->getAs<FunctionType>();
2692   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2693                                   VK_RValue, EndLoc);
2694   ReplaceStmt(Exp, CE);
2695   return CE;
2696 }
2697 
2698 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2699   // synthesize declaration of helper functions needed in this routine.
2700   if (!SelGetUidFunctionDecl)
2701     SynthSelGetUidFunctionDecl();
2702   // use objc_msgSend() for all.
2703   if (!MsgSendFunctionDecl)
2704     SynthMsgSendFunctionDecl();
2705   if (!GetClassFunctionDecl)
2706     SynthGetClassFunctionDecl();
2707 
2708   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2709   SourceLocation StartLoc = Exp->getBeginLoc();
2710   SourceLocation EndLoc = Exp->getEndLoc();
2711 
2712   // Build the expression: __NSContainer_literal(int, ...).arr
2713   QualType IntQT = Context->IntTy;
2714   QualType NSArrayFType =
2715     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2716   std::string NSArrayFName("__NSContainer_literal");
2717   FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2718   DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2719       *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
2720 
2721   SmallVector<Expr*, 16> InitExprs;
2722   unsigned NumElements = Exp->getNumElements();
2723   unsigned UnsignedIntSize =
2724     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725   Expr *count = IntegerLiteral::Create(*Context,
2726                                        llvm::APInt(UnsignedIntSize, NumElements),
2727                                        Context->UnsignedIntTy, SourceLocation());
2728   InitExprs.push_back(count);
2729   for (unsigned i = 0; i < NumElements; i++)
2730     InitExprs.push_back(Exp->getElement(i));
2731   Expr *NSArrayCallExpr =
2732       CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2733                        SourceLocation());
2734 
2735   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2736                                     SourceLocation(),
2737                                     &Context->Idents.get("arr"),
2738                                     Context->getPointerType(Context->VoidPtrTy),
2739                                     nullptr, /*BitWidth=*/nullptr,
2740                                     /*Mutable=*/true, ICIS_NoInit);
2741   MemberExpr *ArrayLiteralME =
2742       MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2743                                  ARRFD->getType(), VK_LValue, OK_Ordinary);
2744   QualType ConstIdT = Context->getObjCIdType().withConst();
2745   CStyleCastExpr * ArrayLiteralObjects =
2746     NoTypeInfoCStyleCastExpr(Context,
2747                              Context->getPointerType(ConstIdT),
2748                              CK_BitCast,
2749                              ArrayLiteralME);
2750 
2751   // Synthesize a call to objc_msgSend().
2752   SmallVector<Expr*, 32> MsgExprs;
2753   SmallVector<Expr*, 4> ClsExprs;
2754   QualType expType = Exp->getType();
2755 
2756   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2757   ObjCInterfaceDecl *Class =
2758     expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2759 
2760   IdentifierInfo *clsName = Class->getIdentifier();
2761   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2762   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2763                                                StartLoc, EndLoc);
2764   MsgExprs.push_back(Cls);
2765 
2766   // Create a call to sel_registerName("arrayWithObjects:count:").
2767   // it will be the 2nd argument.
2768   SmallVector<Expr*, 4> SelExprs;
2769   ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2770   SelExprs.push_back(
2771       getStringLiteral(ArrayMethod->getSelector().getAsString()));
2772   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2773                                                   SelExprs, StartLoc, EndLoc);
2774   MsgExprs.push_back(SelExp);
2775 
2776   // (const id [])objects
2777   MsgExprs.push_back(ArrayLiteralObjects);
2778 
2779   // (NSUInteger)cnt
2780   Expr *cnt = IntegerLiteral::Create(*Context,
2781                                      llvm::APInt(UnsignedIntSize, NumElements),
2782                                      Context->UnsignedIntTy, SourceLocation());
2783   MsgExprs.push_back(cnt);
2784 
2785   SmallVector<QualType, 4> ArgTypes;
2786   ArgTypes.push_back(Context->getObjCClassType());
2787   ArgTypes.push_back(Context->getObjCSelType());
2788   for (const auto *PI : ArrayMethod->parameters())
2789     ArgTypes.push_back(PI->getType());
2790 
2791   QualType returnType = Exp->getType();
2792   // Get the type, we will need to reference it in a couple spots.
2793   QualType msgSendType = MsgSendFlavor->getType();
2794 
2795   // Create a reference to the objc_msgSend() declaration.
2796   DeclRefExpr *DRE = new (Context) DeclRefExpr(
2797       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2798 
2799   CastExpr *cast = NoTypeInfoCStyleCastExpr(
2800       Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2801 
2802   // Now do the "normal" pointer to function cast.
2803   QualType castType =
2804   getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2805   castType = Context->getPointerType(castType);
2806   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2807                                   cast);
2808 
2809   // Don't forget the parens to enforce the proper binding.
2810   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2811 
2812   const FunctionType *FT = msgSendType->castAs<FunctionType>();
2813   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2814                                   VK_RValue, EndLoc);
2815   ReplaceStmt(Exp, CE);
2816   return CE;
2817 }
2818 
2819 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2820   // synthesize declaration of helper functions needed in this routine.
2821   if (!SelGetUidFunctionDecl)
2822     SynthSelGetUidFunctionDecl();
2823   // use objc_msgSend() for all.
2824   if (!MsgSendFunctionDecl)
2825     SynthMsgSendFunctionDecl();
2826   if (!GetClassFunctionDecl)
2827     SynthGetClassFunctionDecl();
2828 
2829   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2830   SourceLocation StartLoc = Exp->getBeginLoc();
2831   SourceLocation EndLoc = Exp->getEndLoc();
2832 
2833   // Build the expression: __NSContainer_literal(int, ...).arr
2834   QualType IntQT = Context->IntTy;
2835   QualType NSDictFType =
2836     getSimpleFunctionType(Context->VoidTy, IntQT, true);
2837   std::string NSDictFName("__NSContainer_literal");
2838   FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2839   DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2840       *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
2841 
2842   SmallVector<Expr*, 16> KeyExprs;
2843   SmallVector<Expr*, 16> ValueExprs;
2844 
2845   unsigned NumElements = Exp->getNumElements();
2846   unsigned UnsignedIntSize =
2847     static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2848   Expr *count = IntegerLiteral::Create(*Context,
2849                                        llvm::APInt(UnsignedIntSize, NumElements),
2850                                        Context->UnsignedIntTy, SourceLocation());
2851   KeyExprs.push_back(count);
2852   ValueExprs.push_back(count);
2853   for (unsigned i = 0; i < NumElements; i++) {
2854     ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2855     KeyExprs.push_back(Element.Key);
2856     ValueExprs.push_back(Element.Value);
2857   }
2858 
2859   // (const id [])objects
2860   Expr *NSValueCallExpr =
2861       CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2862                        SourceLocation());
2863 
2864   FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2865                                        SourceLocation(),
2866                                        &Context->Idents.get("arr"),
2867                                        Context->getPointerType(Context->VoidPtrTy),
2868                                        nullptr, /*BitWidth=*/nullptr,
2869                                        /*Mutable=*/true, ICIS_NoInit);
2870   MemberExpr *DictLiteralValueME =
2871       MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2872                                  ARRFD->getType(), VK_LValue, OK_Ordinary);
2873   QualType ConstIdT = Context->getObjCIdType().withConst();
2874   CStyleCastExpr * DictValueObjects =
2875     NoTypeInfoCStyleCastExpr(Context,
2876                              Context->getPointerType(ConstIdT),
2877                              CK_BitCast,
2878                              DictLiteralValueME);
2879   // (const id <NSCopying> [])keys
2880   Expr *NSKeyCallExpr = CallExpr::Create(
2881       *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
2882 
2883   MemberExpr *DictLiteralKeyME =
2884       MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2885                                  ARRFD->getType(), VK_LValue, OK_Ordinary);
2886 
2887   CStyleCastExpr * DictKeyObjects =
2888     NoTypeInfoCStyleCastExpr(Context,
2889                              Context->getPointerType(ConstIdT),
2890                              CK_BitCast,
2891                              DictLiteralKeyME);
2892 
2893   // Synthesize a call to objc_msgSend().
2894   SmallVector<Expr*, 32> MsgExprs;
2895   SmallVector<Expr*, 4> ClsExprs;
2896   QualType expType = Exp->getType();
2897 
2898   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2899   ObjCInterfaceDecl *Class =
2900   expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2901 
2902   IdentifierInfo *clsName = Class->getIdentifier();
2903   ClsExprs.push_back(getStringLiteral(clsName->getName()));
2904   CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2905                                                StartLoc, EndLoc);
2906   MsgExprs.push_back(Cls);
2907 
2908   // Create a call to sel_registerName("arrayWithObjects:count:").
2909   // it will be the 2nd argument.
2910   SmallVector<Expr*, 4> SelExprs;
2911   ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2912   SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2913   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2914                                                   SelExprs, StartLoc, EndLoc);
2915   MsgExprs.push_back(SelExp);
2916 
2917   // (const id [])objects
2918   MsgExprs.push_back(DictValueObjects);
2919 
2920   // (const id <NSCopying> [])keys
2921   MsgExprs.push_back(DictKeyObjects);
2922 
2923   // (NSUInteger)cnt
2924   Expr *cnt = IntegerLiteral::Create(*Context,
2925                                      llvm::APInt(UnsignedIntSize, NumElements),
2926                                      Context->UnsignedIntTy, SourceLocation());
2927   MsgExprs.push_back(cnt);
2928 
2929   SmallVector<QualType, 8> ArgTypes;
2930   ArgTypes.push_back(Context->getObjCClassType());
2931   ArgTypes.push_back(Context->getObjCSelType());
2932   for (const auto *PI : DictMethod->parameters()) {
2933     QualType T = PI->getType();
2934     if (const PointerType* PT = T->getAs<PointerType>()) {
2935       QualType PointeeTy = PT->getPointeeType();
2936       convertToUnqualifiedObjCType(PointeeTy);
2937       T = Context->getPointerType(PointeeTy);
2938     }
2939     ArgTypes.push_back(T);
2940   }
2941 
2942   QualType returnType = Exp->getType();
2943   // Get the type, we will need to reference it in a couple spots.
2944   QualType msgSendType = MsgSendFlavor->getType();
2945 
2946   // Create a reference to the objc_msgSend() declaration.
2947   DeclRefExpr *DRE = new (Context) DeclRefExpr(
2948       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2949 
2950   CastExpr *cast = NoTypeInfoCStyleCastExpr(
2951       Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2952 
2953   // Now do the "normal" pointer to function cast.
2954   QualType castType =
2955   getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2956   castType = Context->getPointerType(castType);
2957   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2958                                   cast);
2959 
2960   // Don't forget the parens to enforce the proper binding.
2961   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2962 
2963   const FunctionType *FT = msgSendType->castAs<FunctionType>();
2964   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2965                                   VK_RValue, EndLoc);
2966   ReplaceStmt(Exp, CE);
2967   return CE;
2968 }
2969 
2970 // struct __rw_objc_super {
2971 //   struct objc_object *object; struct objc_object *superClass;
2972 // };
2973 QualType RewriteModernObjC::getSuperStructType() {
2974   if (!SuperStructDecl) {
2975     SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2976                                          SourceLocation(), SourceLocation(),
2977                                          &Context->Idents.get("__rw_objc_super"));
2978     QualType FieldTypes[2];
2979 
2980     // struct objc_object *object;
2981     FieldTypes[0] = Context->getObjCIdType();
2982     // struct objc_object *superClass;
2983     FieldTypes[1] = Context->getObjCIdType();
2984 
2985     // Create fields
2986     for (unsigned i = 0; i < 2; ++i) {
2987       SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2988                                                  SourceLocation(),
2989                                                  SourceLocation(), nullptr,
2990                                                  FieldTypes[i], nullptr,
2991                                                  /*BitWidth=*/nullptr,
2992                                                  /*Mutable=*/false,
2993                                                  ICIS_NoInit));
2994     }
2995 
2996     SuperStructDecl->completeDefinition();
2997   }
2998   return Context->getTagDeclType(SuperStructDecl);
2999 }
3000 
3001 QualType RewriteModernObjC::getConstantStringStructType() {
3002   if (!ConstantStringDecl) {
3003     ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3004                                             SourceLocation(), SourceLocation(),
3005                          &Context->Idents.get("__NSConstantStringImpl"));
3006     QualType FieldTypes[4];
3007 
3008     // struct objc_object *receiver;
3009     FieldTypes[0] = Context->getObjCIdType();
3010     // int flags;
3011     FieldTypes[1] = Context->IntTy;
3012     // char *str;
3013     FieldTypes[2] = Context->getPointerType(Context->CharTy);
3014     // long length;
3015     FieldTypes[3] = Context->LongTy;
3016 
3017     // Create fields
3018     for (unsigned i = 0; i < 4; ++i) {
3019       ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3020                                                     ConstantStringDecl,
3021                                                     SourceLocation(),
3022                                                     SourceLocation(), nullptr,
3023                                                     FieldTypes[i], nullptr,
3024                                                     /*BitWidth=*/nullptr,
3025                                                     /*Mutable=*/true,
3026                                                     ICIS_NoInit));
3027     }
3028 
3029     ConstantStringDecl->completeDefinition();
3030   }
3031   return Context->getTagDeclType(ConstantStringDecl);
3032 }
3033 
3034 /// getFunctionSourceLocation - returns start location of a function
3035 /// definition. Complication arises when function has declared as
3036 /// extern "C" or extern "C" {...}
3037 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3038                                                  FunctionDecl *FD) {
3039   if (FD->isExternC()  && !FD->isMain()) {
3040     const DeclContext *DC = FD->getDeclContext();
3041     if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3042       // if it is extern "C" {...}, return function decl's own location.
3043       if (!LSD->getRBraceLoc().isValid())
3044         return LSD->getExternLoc();
3045   }
3046   if (FD->getStorageClass() != SC_None)
3047     R.RewriteBlockLiteralFunctionDecl(FD);
3048   return FD->getTypeSpecStartLoc();
3049 }
3050 
3051 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3052 
3053   SourceLocation Location = D->getLocation();
3054 
3055   if (Location.isFileID() && GenerateLineInfo) {
3056     std::string LineString("\n#line ");
3057     PresumedLoc PLoc = SM->getPresumedLoc(Location);
3058     LineString += utostr(PLoc.getLine());
3059     LineString += " \"";
3060     LineString += Lexer::Stringify(PLoc.getFilename());
3061     if (isa<ObjCMethodDecl>(D))
3062       LineString += "\"";
3063     else LineString += "\"\n";
3064 
3065     Location = D->getBeginLoc();
3066     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3067       if (FD->isExternC()  && !FD->isMain()) {
3068         const DeclContext *DC = FD->getDeclContext();
3069         if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3070           // if it is extern "C" {...}, return function decl's own location.
3071           if (!LSD->getRBraceLoc().isValid())
3072             Location = LSD->getExternLoc();
3073       }
3074     }
3075     InsertText(Location, LineString);
3076   }
3077 }
3078 
3079 /// SynthMsgSendStretCallExpr - This routine translates message expression
3080 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3081 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3082 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3083 /// msgSendType - function type of objc_msgSend_stret(...)
3084 /// returnType - Result type of the method being synthesized.
3085 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3086 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3087 /// starting with receiver.
3088 /// Method - Method being rewritten.
3089 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3090                                                  QualType returnType,
3091                                                  SmallVectorImpl<QualType> &ArgTypes,
3092                                                  SmallVectorImpl<Expr*> &MsgExprs,
3093                                                  ObjCMethodDecl *Method) {
3094   // Now do the "normal" pointer to function cast.
3095   QualType FuncType = getSimpleFunctionType(
3096       returnType, ArgTypes, Method ? Method->isVariadic() : false);
3097   QualType castType = Context->getPointerType(FuncType);
3098 
3099   // build type for containing the objc_msgSend_stret object.
3100   static unsigned stretCount=0;
3101   std::string name = "__Stret"; name += utostr(stretCount);
3102   std::string str =
3103     "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3104   str += "namespace {\n";
3105   str += "struct "; str += name;
3106   str += " {\n\t";
3107   str += name;
3108   str += "(id receiver, SEL sel";
3109   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3110     std::string ArgName = "arg"; ArgName += utostr(i);
3111     ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3112     str += ", "; str += ArgName;
3113   }
3114   // could be vararg.
3115   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3116     std::string ArgName = "arg"; ArgName += utostr(i);
3117     MsgExprs[i]->getType().getAsStringInternal(ArgName,
3118                                                Context->getPrintingPolicy());
3119     str += ", "; str += ArgName;
3120   }
3121 
3122   str += ") {\n";
3123   str += "\t  unsigned size = sizeof(";
3124   str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3125 
3126   str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3127 
3128   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3129   str += ")(void *)objc_msgSend)(receiver, sel";
3130   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3131     str += ", arg"; str += utostr(i);
3132   }
3133   // could be vararg.
3134   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3135     str += ", arg"; str += utostr(i);
3136   }
3137   str+= ");\n";
3138 
3139   str += "\t  else if (receiver == 0)\n";
3140   str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3141   str += "\t  else\n";
3142 
3143   str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3144   str += ")(void *)objc_msgSend_stret)(receiver, sel";
3145   for (unsigned i = 2; i < ArgTypes.size(); i++) {
3146     str += ", arg"; str += utostr(i);
3147   }
3148   // could be vararg.
3149   for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3150     str += ", arg"; str += utostr(i);
3151   }
3152   str += ");\n";
3153 
3154   str += "\t}\n";
3155   str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3156   str += " s;\n";
3157   str += "};\n};\n\n";
3158   SourceLocation FunLocStart;
3159   if (CurFunctionDef)
3160     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3161   else {
3162     assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3163     FunLocStart = CurMethodDef->getBeginLoc();
3164   }
3165 
3166   InsertText(FunLocStart, str);
3167   ++stretCount;
3168 
3169   // AST for __Stretn(receiver, args).s;
3170   IdentifierInfo *ID = &Context->Idents.get(name);
3171   FunctionDecl *FD =
3172       FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3173                            ID, FuncType, nullptr, SC_Extern, false, false);
3174   DeclRefExpr *DRE = new (Context)
3175       DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3176   CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3177                                     VK_LValue, SourceLocation());
3178 
3179   FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3180                                     SourceLocation(),
3181                                     &Context->Idents.get("s"),
3182                                     returnType, nullptr,
3183                                     /*BitWidth=*/nullptr,
3184                                     /*Mutable=*/true, ICIS_NoInit);
3185   MemberExpr *ME = MemberExpr::CreateImplicit(
3186       *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3187 
3188   return ME;
3189 }
3190 
3191 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3192                                     SourceLocation StartLoc,
3193                                     SourceLocation EndLoc) {
3194   if (!SelGetUidFunctionDecl)
3195     SynthSelGetUidFunctionDecl();
3196   if (!MsgSendFunctionDecl)
3197     SynthMsgSendFunctionDecl();
3198   if (!MsgSendSuperFunctionDecl)
3199     SynthMsgSendSuperFunctionDecl();
3200   if (!MsgSendStretFunctionDecl)
3201     SynthMsgSendStretFunctionDecl();
3202   if (!MsgSendSuperStretFunctionDecl)
3203     SynthMsgSendSuperStretFunctionDecl();
3204   if (!MsgSendFpretFunctionDecl)
3205     SynthMsgSendFpretFunctionDecl();
3206   if (!GetClassFunctionDecl)
3207     SynthGetClassFunctionDecl();
3208   if (!GetSuperClassFunctionDecl)
3209     SynthGetSuperClassFunctionDecl();
3210   if (!GetMetaClassFunctionDecl)
3211     SynthGetMetaClassFunctionDecl();
3212 
3213   // default to objc_msgSend().
3214   FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3215   // May need to use objc_msgSend_stret() as well.
3216   FunctionDecl *MsgSendStretFlavor = nullptr;
3217   if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3218     QualType resultType = mDecl->getReturnType();
3219     if (resultType->isRecordType())
3220       MsgSendStretFlavor = MsgSendStretFunctionDecl;
3221     else if (resultType->isRealFloatingType())
3222       MsgSendFlavor = MsgSendFpretFunctionDecl;
3223   }
3224 
3225   // Synthesize a call to objc_msgSend().
3226   SmallVector<Expr*, 8> MsgExprs;
3227   switch (Exp->getReceiverKind()) {
3228   case ObjCMessageExpr::SuperClass: {
3229     MsgSendFlavor = MsgSendSuperFunctionDecl;
3230     if (MsgSendStretFlavor)
3231       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3232     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3233 
3234     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3235 
3236     SmallVector<Expr*, 4> InitExprs;
3237 
3238     // set the receiver to self, the first argument to all methods.
3239     InitExprs.push_back(
3240       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3241                                CK_BitCast,
3242                    new (Context) DeclRefExpr(*Context,
3243                                              CurMethodDef->getSelfDecl(),
3244                                              false,
3245                                              Context->getObjCIdType(),
3246                                              VK_RValue,
3247                                              SourceLocation()))
3248                         ); // set the 'receiver'.
3249 
3250     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3251     SmallVector<Expr*, 8> ClsExprs;
3252     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3253     // (Class)objc_getClass("CurrentClass")
3254     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3255                                                  ClsExprs, StartLoc, EndLoc);
3256     ClsExprs.clear();
3257     ClsExprs.push_back(Cls);
3258     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3259                                        StartLoc, EndLoc);
3260 
3261     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262     // To turn off a warning, type-cast to 'id'
3263     InitExprs.push_back( // set 'super class', using class_getSuperclass().
3264                         NoTypeInfoCStyleCastExpr(Context,
3265                                                  Context->getObjCIdType(),
3266                                                  CK_BitCast, Cls));
3267     // struct __rw_objc_super
3268     QualType superType = getSuperStructType();
3269     Expr *SuperRep;
3270 
3271     if (LangOpts.MicrosoftExt) {
3272       SynthSuperConstructorFunctionDecl();
3273       // Simulate a constructor call...
3274       DeclRefExpr *DRE = new (Context)
3275           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3276                       VK_LValue, SourceLocation());
3277       SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3278                                   VK_LValue, SourceLocation());
3279       // The code for super is a little tricky to prevent collision with
3280       // the structure definition in the header. The rewriter has it's own
3281       // internal definition (__rw_objc_super) that is uses. This is why
3282       // we need the cast below. For example:
3283       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3284       //
3285       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3286                                Context->getPointerType(SuperRep->getType()),
3287                                              VK_RValue, OK_Ordinary,
3288                                              SourceLocation(), false);
3289       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3290                                           Context->getPointerType(superType),
3291                                           CK_BitCast, SuperRep);
3292     } else {
3293       // (struct __rw_objc_super) { <exprs from above> }
3294       InitListExpr *ILE =
3295         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3296                                    SourceLocation());
3297       TypeSourceInfo *superTInfo
3298         = Context->getTrivialTypeSourceInfo(superType);
3299       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3300                                                    superType, VK_LValue,
3301                                                    ILE, false);
3302       // struct __rw_objc_super *
3303       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3304                                Context->getPointerType(SuperRep->getType()),
3305                                              VK_RValue, OK_Ordinary,
3306                                              SourceLocation(), false);
3307     }
3308     MsgExprs.push_back(SuperRep);
3309     break;
3310   }
3311 
3312   case ObjCMessageExpr::Class: {
3313     SmallVector<Expr*, 8> ClsExprs;
3314     ObjCInterfaceDecl *Class
3315       = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3316     IdentifierInfo *clsName = Class->getIdentifier();
3317     ClsExprs.push_back(getStringLiteral(clsName->getName()));
3318     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3319                                                  StartLoc, EndLoc);
3320     CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3321                                                  Context->getObjCIdType(),
3322                                                  CK_BitCast, Cls);
3323     MsgExprs.push_back(ArgExpr);
3324     break;
3325   }
3326 
3327   case ObjCMessageExpr::SuperInstance:{
3328     MsgSendFlavor = MsgSendSuperFunctionDecl;
3329     if (MsgSendStretFlavor)
3330       MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3331     assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3332     ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333     SmallVector<Expr*, 4> InitExprs;
3334 
3335     InitExprs.push_back(
3336       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3337                                CK_BitCast,
3338                    new (Context) DeclRefExpr(*Context,
3339                                              CurMethodDef->getSelfDecl(),
3340                                              false,
3341                                              Context->getObjCIdType(),
3342                                              VK_RValue, SourceLocation()))
3343                         ); // set the 'receiver'.
3344 
3345     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3346     SmallVector<Expr*, 8> ClsExprs;
3347     ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3348     // (Class)objc_getClass("CurrentClass")
3349     CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3350                                                  StartLoc, EndLoc);
3351     ClsExprs.clear();
3352     ClsExprs.push_back(Cls);
3353     Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3354                                        StartLoc, EndLoc);
3355 
3356     // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3357     // To turn off a warning, type-cast to 'id'
3358     InitExprs.push_back(
3359       // set 'super class', using class_getSuperclass().
3360       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3361                                CK_BitCast, Cls));
3362     // struct __rw_objc_super
3363     QualType superType = getSuperStructType();
3364     Expr *SuperRep;
3365 
3366     if (LangOpts.MicrosoftExt) {
3367       SynthSuperConstructorFunctionDecl();
3368       // Simulate a constructor call...
3369       DeclRefExpr *DRE = new (Context)
3370           DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3371                       VK_LValue, SourceLocation());
3372       SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3373                                   VK_LValue, SourceLocation());
3374       // The code for super is a little tricky to prevent collision with
3375       // the structure definition in the header. The rewriter has it's own
3376       // internal definition (__rw_objc_super) that is uses. This is why
3377       // we need the cast below. For example:
3378       // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3379       //
3380       SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3381                                Context->getPointerType(SuperRep->getType()),
3382                                VK_RValue, OK_Ordinary,
3383                                SourceLocation(), false);
3384       SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385                                Context->getPointerType(superType),
3386                                CK_BitCast, SuperRep);
3387     } else {
3388       // (struct __rw_objc_super) { <exprs from above> }
3389       InitListExpr *ILE =
3390         new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3391                                    SourceLocation());
3392       TypeSourceInfo *superTInfo
3393         = Context->getTrivialTypeSourceInfo(superType);
3394       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3395                                                    superType, VK_RValue, ILE,
3396                                                    false);
3397     }
3398     MsgExprs.push_back(SuperRep);
3399     break;
3400   }
3401 
3402   case ObjCMessageExpr::Instance: {
3403     // Remove all type-casts because it may contain objc-style types; e.g.
3404     // Foo<Proto> *.
3405     Expr *recExpr = Exp->getInstanceReceiver();
3406     while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3407       recExpr = CE->getSubExpr();
3408     CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3409                     ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3410                                      ? CK_BlockPointerToObjCPointerCast
3411                                      : CK_CPointerToObjCPointerCast;
3412 
3413     recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3414                                        CK, recExpr);
3415     MsgExprs.push_back(recExpr);
3416     break;
3417   }
3418   }
3419 
3420   // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3421   SmallVector<Expr*, 8> SelExprs;
3422   SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3423   CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3424                                                   SelExprs, StartLoc, EndLoc);
3425   MsgExprs.push_back(SelExp);
3426 
3427   // Now push any user supplied arguments.
3428   for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3429     Expr *userExpr = Exp->getArg(i);
3430     // Make all implicit casts explicit...ICE comes in handy:-)
3431     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3432       // Reuse the ICE type, it is exactly what the doctor ordered.
3433       QualType type = ICE->getType();
3434       if (needToScanForQualifiers(type))
3435         type = Context->getObjCIdType();
3436       // Make sure we convert "type (^)(...)" to "type (*)(...)".
3437       (void)convertBlockPointerToFunctionPointer(type);
3438       const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3439       CastKind CK;
3440       if (SubExpr->getType()->isIntegralType(*Context) &&
3441           type->isBooleanType()) {
3442         CK = CK_IntegralToBoolean;
3443       } else if (type->isObjCObjectPointerType()) {
3444         if (SubExpr->getType()->isBlockPointerType()) {
3445           CK = CK_BlockPointerToObjCPointerCast;
3446         } else if (SubExpr->getType()->isPointerType()) {
3447           CK = CK_CPointerToObjCPointerCast;
3448         } else {
3449           CK = CK_BitCast;
3450         }
3451       } else {
3452         CK = CK_BitCast;
3453       }
3454 
3455       userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3456     }
3457     // Make id<P...> cast into an 'id' cast.
3458     else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3459       if (CE->getType()->isObjCQualifiedIdType()) {
3460         while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3461           userExpr = CE->getSubExpr();
3462         CastKind CK;
3463         if (userExpr->getType()->isIntegralType(*Context)) {
3464           CK = CK_IntegralToPointer;
3465         } else if (userExpr->getType()->isBlockPointerType()) {
3466           CK = CK_BlockPointerToObjCPointerCast;
3467         } else if (userExpr->getType()->isPointerType()) {
3468           CK = CK_CPointerToObjCPointerCast;
3469         } else {
3470           CK = CK_BitCast;
3471         }
3472         userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3473                                             CK, userExpr);
3474       }
3475     }
3476     MsgExprs.push_back(userExpr);
3477     // We've transferred the ownership to MsgExprs. For now, we *don't* null
3478     // out the argument in the original expression (since we aren't deleting
3479     // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3480     //Exp->setArg(i, 0);
3481   }
3482   // Generate the funky cast.
3483   CastExpr *cast;
3484   SmallVector<QualType, 8> ArgTypes;
3485   QualType returnType;
3486 
3487   // Push 'id' and 'SEL', the 2 implicit arguments.
3488   if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3489     ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3490   else
3491     ArgTypes.push_back(Context->getObjCIdType());
3492   ArgTypes.push_back(Context->getObjCSelType());
3493   if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3494     // Push any user argument types.
3495     for (const auto *PI : OMD->parameters()) {
3496       QualType t = PI->getType()->isObjCQualifiedIdType()
3497                      ? Context->getObjCIdType()
3498                      : PI->getType();
3499       // Make sure we convert "t (^)(...)" to "t (*)(...)".
3500       (void)convertBlockPointerToFunctionPointer(t);
3501       ArgTypes.push_back(t);
3502     }
3503     returnType = Exp->getType();
3504     convertToUnqualifiedObjCType(returnType);
3505     (void)convertBlockPointerToFunctionPointer(returnType);
3506   } else {
3507     returnType = Context->getObjCIdType();
3508   }
3509   // Get the type, we will need to reference it in a couple spots.
3510   QualType msgSendType = MsgSendFlavor->getType();
3511 
3512   // Create a reference to the objc_msgSend() declaration.
3513   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3514       *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3515 
3516   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3517   // If we don't do this cast, we get the following bizarre warning/note:
3518   // xx.m:13: warning: function called through a non-compatible type
3519   // xx.m:13: note: if this code is reached, the program will abort
3520   cast = NoTypeInfoCStyleCastExpr(Context,
3521                                   Context->getPointerType(Context->VoidTy),
3522                                   CK_BitCast, DRE);
3523 
3524   // Now do the "normal" pointer to function cast.
3525   // If we don't have a method decl, force a variadic cast.
3526   const ObjCMethodDecl *MD = Exp->getMethodDecl();
3527   QualType castType =
3528     getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3529   castType = Context->getPointerType(castType);
3530   cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3531                                   cast);
3532 
3533   // Don't forget the parens to enforce the proper binding.
3534   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3535 
3536   const FunctionType *FT = msgSendType->castAs<FunctionType>();
3537   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3538                                   VK_RValue, EndLoc);
3539   Stmt *ReplacingStmt = CE;
3540   if (MsgSendStretFlavor) {
3541     // We have the method which returns a struct/union. Must also generate
3542     // call to objc_msgSend_stret and hang both varieties on a conditional
3543     // expression which dictate which one to envoke depending on size of
3544     // method's return type.
3545 
3546     Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3547                                            returnType,
3548                                            ArgTypes, MsgExprs,
3549                                            Exp->getMethodDecl());
3550     ReplacingStmt = STCE;
3551   }
3552   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3553   return ReplacingStmt;
3554 }
3555 
3556 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3557   Stmt *ReplacingStmt =
3558       SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3559 
3560   // Now do the actual rewrite.
3561   ReplaceStmt(Exp, ReplacingStmt);
3562 
3563   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3564   return ReplacingStmt;
3565 }
3566 
3567 // typedef struct objc_object Protocol;
3568 QualType RewriteModernObjC::getProtocolType() {
3569   if (!ProtocolTypeDecl) {
3570     TypeSourceInfo *TInfo
3571       = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3572     ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3573                                            SourceLocation(), SourceLocation(),
3574                                            &Context->Idents.get("Protocol"),
3575                                            TInfo);
3576   }
3577   return Context->getTypeDeclType(ProtocolTypeDecl);
3578 }
3579 
3580 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3581 /// a synthesized/forward data reference (to the protocol's metadata).
3582 /// The forward references (and metadata) are generated in
3583 /// RewriteModernObjC::HandleTranslationUnit().
3584 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3585   std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3586                       Exp->getProtocol()->getNameAsString();
3587   IdentifierInfo *ID = &Context->Idents.get(Name);
3588   VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3589                                 SourceLocation(), ID, getProtocolType(),
3590                                 nullptr, SC_Extern);
3591   DeclRefExpr *DRE = new (Context) DeclRefExpr(
3592       *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3593   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3594       Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3595   ReplaceStmt(Exp, castExpr);
3596   ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3597   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3598   return castExpr;
3599 }
3600 
3601 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3602 /// is defined inside an objective-c class. If so, it returns true.
3603 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3604                                                 TagDecl *Tag,
3605                                                 bool &IsNamedDefinition) {
3606   if (!IDecl)
3607     return false;
3608   SourceLocation TagLocation;
3609   if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3610     RD = RD->getDefinition();
3611     if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3612       return false;
3613     IsNamedDefinition = true;
3614     TagLocation = RD->getLocation();
3615     return Context->getSourceManager().isBeforeInTranslationUnit(
3616                                           IDecl->getLocation(), TagLocation);
3617   }
3618   if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3619     if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3620       return false;
3621     IsNamedDefinition = true;
3622     TagLocation = ED->getLocation();
3623     return Context->getSourceManager().isBeforeInTranslationUnit(
3624                                           IDecl->getLocation(), TagLocation);
3625   }
3626   return false;
3627 }
3628 
3629 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3630 /// It handles elaborated types, as well as enum types in the process.
3631 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3632                                                  std::string &Result) {
3633   if (isa<TypedefType>(Type)) {
3634     Result += "\t";
3635     return false;
3636   }
3637 
3638   if (Type->isArrayType()) {
3639     QualType ElemTy = Context->getBaseElementType(Type);
3640     return RewriteObjCFieldDeclType(ElemTy, Result);
3641   }
3642   else if (Type->isRecordType()) {
3643     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3644     if (RD->isCompleteDefinition()) {
3645       if (RD->isStruct())
3646         Result += "\n\tstruct ";
3647       else if (RD->isUnion())
3648         Result += "\n\tunion ";
3649       else
3650         assert(false && "class not allowed as an ivar type");
3651 
3652       Result += RD->getName();
3653       if (GlobalDefinedTags.count(RD)) {
3654         // struct/union is defined globally, use it.
3655         Result += " ";
3656         return true;
3657       }
3658       Result += " {\n";
3659       for (auto *FD : RD->fields())
3660         RewriteObjCFieldDecl(FD, Result);
3661       Result += "\t} ";
3662       return true;
3663     }
3664   }
3665   else if (Type->isEnumeralType()) {
3666     EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3667     if (ED->isCompleteDefinition()) {
3668       Result += "\n\tenum ";
3669       Result += ED->getName();
3670       if (GlobalDefinedTags.count(ED)) {
3671         // Enum is globall defined, use it.
3672         Result += " ";
3673         return true;
3674       }
3675 
3676       Result += " {\n";
3677       for (const auto *EC : ED->enumerators()) {
3678         Result += "\t"; Result += EC->getName(); Result += " = ";
3679         llvm::APSInt Val = EC->getInitVal();
3680         Result += Val.toString(10);
3681         Result += ",\n";
3682       }
3683       Result += "\t} ";
3684       return true;
3685     }
3686   }
3687 
3688   Result += "\t";
3689   convertObjCTypeToCStyleType(Type);
3690   return false;
3691 }
3692 
3693 
3694 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3695 /// It handles elaborated types, as well as enum types in the process.
3696 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3697                                              std::string &Result) {
3698   QualType Type = fieldDecl->getType();
3699   std::string Name = fieldDecl->getNameAsString();
3700 
3701   bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3702   if (!EleboratedType)
3703     Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3704   Result += Name;
3705   if (fieldDecl->isBitField()) {
3706     Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3707   }
3708   else if (EleboratedType && Type->isArrayType()) {
3709     const ArrayType *AT = Context->getAsArrayType(Type);
3710     do {
3711       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3712         Result += "[";
3713         llvm::APInt Dim = CAT->getSize();
3714         Result += utostr(Dim.getZExtValue());
3715         Result += "]";
3716       }
3717       AT = Context->getAsArrayType(AT->getElementType());
3718     } while (AT);
3719   }
3720 
3721   Result += ";\n";
3722 }
3723 
3724 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3725 /// named aggregate types into the input buffer.
3726 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3727                                              std::string &Result) {
3728   QualType Type = fieldDecl->getType();
3729   if (isa<TypedefType>(Type))
3730     return;
3731   if (Type->isArrayType())
3732     Type = Context->getBaseElementType(Type);
3733 
3734   auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3735 
3736   TagDecl *TD = nullptr;
3737   if (Type->isRecordType()) {
3738     TD = Type->castAs<RecordType>()->getDecl();
3739   }
3740   else if (Type->isEnumeralType()) {
3741     TD = Type->castAs<EnumType>()->getDecl();
3742   }
3743 
3744   if (TD) {
3745     if (GlobalDefinedTags.count(TD))
3746       return;
3747 
3748     bool IsNamedDefinition = false;
3749     if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3750       RewriteObjCFieldDeclType(Type, Result);
3751       Result += ";";
3752     }
3753     if (IsNamedDefinition)
3754       GlobalDefinedTags.insert(TD);
3755   }
3756 }
3757 
3758 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3759   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3760   if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3761     return IvarGroupNumber[IV];
3762   }
3763   unsigned GroupNo = 0;
3764   SmallVector<const ObjCIvarDecl *, 8> IVars;
3765   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3766        IVD; IVD = IVD->getNextIvar())
3767     IVars.push_back(IVD);
3768 
3769   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3770     if (IVars[i]->isBitField()) {
3771       IvarGroupNumber[IVars[i++]] = ++GroupNo;
3772       while (i < e && IVars[i]->isBitField())
3773         IvarGroupNumber[IVars[i++]] = GroupNo;
3774       if (i < e)
3775         --i;
3776     }
3777 
3778   ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3779   return IvarGroupNumber[IV];
3780 }
3781 
3782 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3783                               ObjCIvarDecl *IV,
3784                               SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3785   std::string StructTagName;
3786   ObjCIvarBitfieldGroupType(IV, StructTagName);
3787   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3788                                       Context->getTranslationUnitDecl(),
3789                                       SourceLocation(), SourceLocation(),
3790                                       &Context->Idents.get(StructTagName));
3791   for (unsigned i=0, e = IVars.size(); i < e; i++) {
3792     ObjCIvarDecl *Ivar = IVars[i];
3793     RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3794                                   &Context->Idents.get(Ivar->getName()),
3795                                   Ivar->getType(),
3796                                   nullptr, /*Expr *BW */Ivar->getBitWidth(),
3797                                   false, ICIS_NoInit));
3798   }
3799   RD->completeDefinition();
3800   return Context->getTagDeclType(RD);
3801 }
3802 
3803 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3804   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3805   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3806   std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3807   if (GroupRecordType.count(tuple))
3808     return GroupRecordType[tuple];
3809 
3810   SmallVector<ObjCIvarDecl *, 8> IVars;
3811   for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3812        IVD; IVD = IVD->getNextIvar()) {
3813     if (IVD->isBitField())
3814       IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3815     else {
3816       if (!IVars.empty()) {
3817         unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3818         // Generate the struct type for this group of bitfield ivars.
3819         GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3820           SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3821         IVars.clear();
3822       }
3823     }
3824   }
3825   if (!IVars.empty()) {
3826     // Do the last one.
3827     unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828     GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3829       SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3830   }
3831   QualType RetQT = GroupRecordType[tuple];
3832   assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3833 
3834   return RetQT;
3835 }
3836 
3837 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3838 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3839 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3840                                                   std::string &Result) {
3841   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3842   Result += CDecl->getName();
3843   Result += "__GRBF_";
3844   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3845   Result += utostr(GroupNo);
3846 }
3847 
3848 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3849 /// Name of the struct would be: classname__T_n where n is the group number for
3850 /// this ivar.
3851 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3852                                                   std::string &Result) {
3853   const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3854   Result += CDecl->getName();
3855   Result += "__T_";
3856   unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3857   Result += utostr(GroupNo);
3858 }
3859 
3860 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3861 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3862 /// this ivar.
3863 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3864                                                     std::string &Result) {
3865   Result += "OBJC_IVAR_$_";
3866   ObjCIvarBitfieldGroupDecl(IV, Result);
3867 }
3868 
3869 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3870       while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3871         ++IX; \
3872       if (IX < ENDIX) \
3873         --IX; \
3874 }
3875 
3876 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3877 /// an objective-c class with ivars.
3878 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3879                                                std::string &Result) {
3880   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3881   assert(CDecl->getName() != "" &&
3882          "Name missing in SynthesizeObjCInternalStruct");
3883   ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3884   SmallVector<ObjCIvarDecl *, 8> IVars;
3885   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3886        IVD; IVD = IVD->getNextIvar())
3887     IVars.push_back(IVD);
3888 
3889   SourceLocation LocStart = CDecl->getBeginLoc();
3890   SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3891 
3892   const char *startBuf = SM->getCharacterData(LocStart);
3893   const char *endBuf = SM->getCharacterData(LocEnd);
3894 
3895   // If no ivars and no root or if its root, directly or indirectly,
3896   // have no ivars (thus not synthesized) then no need to synthesize this class.
3897   if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3898       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3899     endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3900     ReplaceText(LocStart, endBuf-startBuf, Result);
3901     return;
3902   }
3903 
3904   // Insert named struct/union definitions inside class to
3905   // outer scope. This follows semantics of locally defined
3906   // struct/unions in objective-c classes.
3907   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3908     RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3909 
3910   // Insert named structs which are syntheized to group ivar bitfields
3911   // to outer scope as well.
3912   for (unsigned i = 0, e = IVars.size(); i < e; i++)
3913     if (IVars[i]->isBitField()) {
3914       ObjCIvarDecl *IV = IVars[i];
3915       QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3916       RewriteObjCFieldDeclType(QT, Result);
3917       Result += ";";
3918       // skip over ivar bitfields in this group.
3919       SKIP_BITFIELDS(i , e, IVars);
3920     }
3921 
3922   Result += "\nstruct ";
3923   Result += CDecl->getNameAsString();
3924   Result += "_IMPL {\n";
3925 
3926   if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3927     Result += "\tstruct "; Result += RCDecl->getNameAsString();
3928     Result += "_IMPL "; Result += RCDecl->getNameAsString();
3929     Result += "_IVARS;\n";
3930   }
3931 
3932   for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3933     if (IVars[i]->isBitField()) {
3934       ObjCIvarDecl *IV = IVars[i];
3935       Result += "\tstruct ";
3936       ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3937       ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3938       // skip over ivar bitfields in this group.
3939       SKIP_BITFIELDS(i , e, IVars);
3940     }
3941     else
3942       RewriteObjCFieldDecl(IVars[i], Result);
3943   }
3944 
3945   Result += "};\n";
3946   endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3947   ReplaceText(LocStart, endBuf-startBuf, Result);
3948   // Mark this struct as having been generated.
3949   if (!ObjCSynthesizedStructs.insert(CDecl).second)
3950     llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3951 }
3952 
3953 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3954 /// have been referenced in an ivar access expression.
3955 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3956                                                   std::string &Result) {
3957   // write out ivar offset symbols which have been referenced in an ivar
3958   // access expression.
3959   llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3960 
3961   if (Ivars.empty())
3962     return;
3963 
3964   llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3965   for (ObjCIvarDecl *IvarDecl : Ivars) {
3966     const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3967     unsigned GroupNo = 0;
3968     if (IvarDecl->isBitField()) {
3969       GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3970       if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3971         continue;
3972     }
3973     Result += "\n";
3974     if (LangOpts.MicrosoftExt)
3975       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3976     Result += "extern \"C\" ";
3977     if (LangOpts.MicrosoftExt &&
3978         IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3979         IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3980         Result += "__declspec(dllimport) ";
3981 
3982     Result += "unsigned long ";
3983     if (IvarDecl->isBitField()) {
3984       ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3985       GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3986     }
3987     else
3988       WriteInternalIvarName(CDecl, IvarDecl, Result);
3989     Result += ";";
3990   }
3991 }
3992 
3993 //===----------------------------------------------------------------------===//
3994 // Meta Data Emission
3995 //===----------------------------------------------------------------------===//
3996 
3997 /// RewriteImplementations - This routine rewrites all method implementations
3998 /// and emits meta-data.
3999 
4000 void RewriteModernObjC::RewriteImplementations() {
4001   int ClsDefCount = ClassImplementation.size();
4002   int CatDefCount = CategoryImplementation.size();
4003 
4004   // Rewrite implemented methods
4005   for (int i = 0; i < ClsDefCount; i++) {
4006     ObjCImplementationDecl *OIMP = ClassImplementation[i];
4007     ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4008     if (CDecl->isImplicitInterfaceDecl())
4009       assert(false &&
4010              "Legacy implicit interface rewriting not supported in moder abi");
4011     RewriteImplementationDecl(OIMP);
4012   }
4013 
4014   for (int i = 0; i < CatDefCount; i++) {
4015     ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4016     ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4017     if (CDecl->isImplicitInterfaceDecl())
4018       assert(false &&
4019              "Legacy implicit interface rewriting not supported in moder abi");
4020     RewriteImplementationDecl(CIMP);
4021   }
4022 }
4023 
4024 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4025                                      const std::string &Name,
4026                                      ValueDecl *VD, bool def) {
4027   assert(BlockByRefDeclNo.count(VD) &&
4028          "RewriteByRefString: ByRef decl missing");
4029   if (def)
4030     ResultStr += "struct ";
4031   ResultStr += "__Block_byref_" + Name +
4032     "_" + utostr(BlockByRefDeclNo[VD]) ;
4033 }
4034 
4035 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4036   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4037     return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4038   return false;
4039 }
4040 
4041 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4042                                                    StringRef funcName,
4043                                                    std::string Tag) {
4044   const FunctionType *AFT = CE->getFunctionType();
4045   QualType RT = AFT->getReturnType();
4046   std::string StructRef = "struct " + Tag;
4047   SourceLocation BlockLoc = CE->getExprLoc();
4048   std::string S;
4049   ConvertSourceLocationToLineDirective(BlockLoc, S);
4050 
4051   S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4052          funcName.str() + "_block_func_" + utostr(i);
4053 
4054   BlockDecl *BD = CE->getBlockDecl();
4055 
4056   if (isa<FunctionNoProtoType>(AFT)) {
4057     // No user-supplied arguments. Still need to pass in a pointer to the
4058     // block (to reference imported block decl refs).
4059     S += "(" + StructRef + " *__cself)";
4060   } else if (BD->param_empty()) {
4061     S += "(" + StructRef + " *__cself)";
4062   } else {
4063     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4064     assert(FT && "SynthesizeBlockFunc: No function proto");
4065     S += '(';
4066     // first add the implicit argument.
4067     S += StructRef + " *__cself, ";
4068     std::string ParamStr;
4069     for (BlockDecl::param_iterator AI = BD->param_begin(),
4070          E = BD->param_end(); AI != E; ++AI) {
4071       if (AI != BD->param_begin()) S += ", ";
4072       ParamStr = (*AI)->getNameAsString();
4073       QualType QT = (*AI)->getType();
4074       (void)convertBlockPointerToFunctionPointer(QT);
4075       QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4076       S += ParamStr;
4077     }
4078     if (FT->isVariadic()) {
4079       if (!BD->param_empty()) S += ", ";
4080       S += "...";
4081     }
4082     S += ')';
4083   }
4084   S += " {\n";
4085 
4086   // Create local declarations to avoid rewriting all closure decl ref exprs.
4087   // First, emit a declaration for all "by ref" decls.
4088   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4089        E = BlockByRefDecls.end(); I != E; ++I) {
4090     S += "  ";
4091     std::string Name = (*I)->getNameAsString();
4092     std::string TypeString;
4093     RewriteByRefString(TypeString, Name, (*I));
4094     TypeString += " *";
4095     Name = TypeString + Name;
4096     S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4097   }
4098   // Next, emit a declaration for all "by copy" declarations.
4099   for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4100        E = BlockByCopyDecls.end(); I != E; ++I) {
4101     S += "  ";
4102     // Handle nested closure invocation. For example:
4103     //
4104     //   void (^myImportedClosure)(void);
4105     //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4106     //
4107     //   void (^anotherClosure)(void);
4108     //   anotherClosure = ^(void) {
4109     //     myImportedClosure(); // import and invoke the closure
4110     //   };
4111     //
4112     if (isTopLevelBlockPointerType((*I)->getType())) {
4113       RewriteBlockPointerTypeVariable(S, (*I));
4114       S += " = (";
4115       RewriteBlockPointerType(S, (*I)->getType());
4116       S += ")";
4117       S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4118     }
4119     else {
4120       std::string Name = (*I)->getNameAsString();
4121       QualType QT = (*I)->getType();
4122       if (HasLocalVariableExternalStorage(*I))
4123         QT = Context->getPointerType(QT);
4124       QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4125       S += Name + " = __cself->" +
4126                               (*I)->getNameAsString() + "; // bound by copy\n";
4127     }
4128   }
4129   std::string RewrittenStr = RewrittenBlockExprs[CE];
4130   const char *cstr = RewrittenStr.c_str();
4131   while (*cstr++ != '{') ;
4132   S += cstr;
4133   S += "\n";
4134   return S;
4135 }
4136 
4137 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4138                                                    StringRef funcName,
4139                                                    std::string Tag) {
4140   std::string StructRef = "struct " + Tag;
4141   std::string S = "static void __";
4142 
4143   S += funcName;
4144   S += "_block_copy_" + utostr(i);
4145   S += "(" + StructRef;
4146   S += "*dst, " + StructRef;
4147   S += "*src) {";
4148   for (ValueDecl *VD : ImportedBlockDecls) {
4149     S += "_Block_object_assign((void*)&dst->";
4150     S += VD->getNameAsString();
4151     S += ", (void*)src->";
4152     S += VD->getNameAsString();
4153     if (BlockByRefDeclsPtrSet.count(VD))
4154       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4155     else if (VD->getType()->isBlockPointerType())
4156       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4157     else
4158       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4159   }
4160   S += "}\n";
4161 
4162   S += "\nstatic void __";
4163   S += funcName;
4164   S += "_block_dispose_" + utostr(i);
4165   S += "(" + StructRef;
4166   S += "*src) {";
4167   for (ValueDecl *VD : ImportedBlockDecls) {
4168     S += "_Block_object_dispose((void*)src->";
4169     S += VD->getNameAsString();
4170     if (BlockByRefDeclsPtrSet.count(VD))
4171       S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4172     else if (VD->getType()->isBlockPointerType())
4173       S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4174     else
4175       S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4176   }
4177   S += "}\n";
4178   return S;
4179 }
4180 
4181 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4182                                              std::string Desc) {
4183   std::string S = "\nstruct " + Tag;
4184   std::string Constructor = "  " + Tag;
4185 
4186   S += " {\n  struct __block_impl impl;\n";
4187   S += "  struct " + Desc;
4188   S += "* Desc;\n";
4189 
4190   Constructor += "(void *fp, "; // Invoke function pointer.
4191   Constructor += "struct " + Desc; // Descriptor pointer.
4192   Constructor += " *desc";
4193 
4194   if (BlockDeclRefs.size()) {
4195     // Output all "by copy" declarations.
4196     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4197          E = BlockByCopyDecls.end(); I != E; ++I) {
4198       S += "  ";
4199       std::string FieldName = (*I)->getNameAsString();
4200       std::string ArgName = "_" + FieldName;
4201       // Handle nested closure invocation. For example:
4202       //
4203       //   void (^myImportedBlock)(void);
4204       //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4205       //
4206       //   void (^anotherBlock)(void);
4207       //   anotherBlock = ^(void) {
4208       //     myImportedBlock(); // import and invoke the closure
4209       //   };
4210       //
4211       if (isTopLevelBlockPointerType((*I)->getType())) {
4212         S += "struct __block_impl *";
4213         Constructor += ", void *" + ArgName;
4214       } else {
4215         QualType QT = (*I)->getType();
4216         if (HasLocalVariableExternalStorage(*I))
4217           QT = Context->getPointerType(QT);
4218         QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4219         QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4220         Constructor += ", " + ArgName;
4221       }
4222       S += FieldName + ";\n";
4223     }
4224     // Output all "by ref" declarations.
4225     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4226          E = BlockByRefDecls.end(); I != E; ++I) {
4227       S += "  ";
4228       std::string FieldName = (*I)->getNameAsString();
4229       std::string ArgName = "_" + FieldName;
4230       {
4231         std::string TypeString;
4232         RewriteByRefString(TypeString, FieldName, (*I));
4233         TypeString += " *";
4234         FieldName = TypeString + FieldName;
4235         ArgName = TypeString + ArgName;
4236         Constructor += ", " + ArgName;
4237       }
4238       S += FieldName + "; // by ref\n";
4239     }
4240     // Finish writing the constructor.
4241     Constructor += ", int flags=0)";
4242     // Initialize all "by copy" arguments.
4243     bool firsTime = true;
4244     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4245          E = BlockByCopyDecls.end(); I != E; ++I) {
4246       std::string Name = (*I)->getNameAsString();
4247         if (firsTime) {
4248           Constructor += " : ";
4249           firsTime = false;
4250         }
4251         else
4252           Constructor += ", ";
4253         if (isTopLevelBlockPointerType((*I)->getType()))
4254           Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4255         else
4256           Constructor += Name + "(_" + Name + ")";
4257     }
4258     // Initialize all "by ref" arguments.
4259     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4260          E = BlockByRefDecls.end(); I != E; ++I) {
4261       std::string Name = (*I)->getNameAsString();
4262       if (firsTime) {
4263         Constructor += " : ";
4264         firsTime = false;
4265       }
4266       else
4267         Constructor += ", ";
4268       Constructor += Name + "(_" + Name + "->__forwarding)";
4269     }
4270 
4271     Constructor += " {\n";
4272     if (GlobalVarDecl)
4273       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4274     else
4275       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4276     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4277 
4278     Constructor += "    Desc = desc;\n";
4279   } else {
4280     // Finish writing the constructor.
4281     Constructor += ", int flags=0) {\n";
4282     if (GlobalVarDecl)
4283       Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4284     else
4285       Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4286     Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4287     Constructor += "    Desc = desc;\n";
4288   }
4289   Constructor += "  ";
4290   Constructor += "}\n";
4291   S += Constructor;
4292   S += "};\n";
4293   return S;
4294 }
4295 
4296 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4297                                                    std::string ImplTag, int i,
4298                                                    StringRef FunName,
4299                                                    unsigned hasCopy) {
4300   std::string S = "\nstatic struct " + DescTag;
4301 
4302   S += " {\n  size_t reserved;\n";
4303   S += "  size_t Block_size;\n";
4304   if (hasCopy) {
4305     S += "  void (*copy)(struct ";
4306     S += ImplTag; S += "*, struct ";
4307     S += ImplTag; S += "*);\n";
4308 
4309     S += "  void (*dispose)(struct ";
4310     S += ImplTag; S += "*);\n";
4311   }
4312   S += "} ";
4313 
4314   S += DescTag + "_DATA = { 0, sizeof(struct ";
4315   S += ImplTag + ")";
4316   if (hasCopy) {
4317     S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4318     S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4319   }
4320   S += "};\n";
4321   return S;
4322 }
4323 
4324 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4325                                           StringRef FunName) {
4326   bool RewriteSC = (GlobalVarDecl &&
4327                     !Blocks.empty() &&
4328                     GlobalVarDecl->getStorageClass() == SC_Static &&
4329                     GlobalVarDecl->getType().getCVRQualifiers());
4330   if (RewriteSC) {
4331     std::string SC(" void __");
4332     SC += GlobalVarDecl->getNameAsString();
4333     SC += "() {}";
4334     InsertText(FunLocStart, SC);
4335   }
4336 
4337   // Insert closures that were part of the function.
4338   for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4339     CollectBlockDeclRefInfo(Blocks[i]);
4340     // Need to copy-in the inner copied-in variables not actually used in this
4341     // block.
4342     for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4343       DeclRefExpr *Exp = InnerDeclRefs[count++];
4344       ValueDecl *VD = Exp->getDecl();
4345       BlockDeclRefs.push_back(Exp);
4346       if (!VD->hasAttr<BlocksAttr>()) {
4347         if (!BlockByCopyDeclsPtrSet.count(VD)) {
4348           BlockByCopyDeclsPtrSet.insert(VD);
4349           BlockByCopyDecls.push_back(VD);
4350         }
4351         continue;
4352       }
4353 
4354       if (!BlockByRefDeclsPtrSet.count(VD)) {
4355         BlockByRefDeclsPtrSet.insert(VD);
4356         BlockByRefDecls.push_back(VD);
4357       }
4358 
4359       // imported objects in the inner blocks not used in the outer
4360       // blocks must be copied/disposed in the outer block as well.
4361       if (VD->getType()->isObjCObjectPointerType() ||
4362           VD->getType()->isBlockPointerType())
4363         ImportedBlockDecls.insert(VD);
4364     }
4365 
4366     std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4367     std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4368 
4369     std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4370 
4371     InsertText(FunLocStart, CI);
4372 
4373     std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4374 
4375     InsertText(FunLocStart, CF);
4376 
4377     if (ImportedBlockDecls.size()) {
4378       std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4379       InsertText(FunLocStart, HF);
4380     }
4381     std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4382                                                ImportedBlockDecls.size() > 0);
4383     InsertText(FunLocStart, BD);
4384 
4385     BlockDeclRefs.clear();
4386     BlockByRefDecls.clear();
4387     BlockByRefDeclsPtrSet.clear();
4388     BlockByCopyDecls.clear();
4389     BlockByCopyDeclsPtrSet.clear();
4390     ImportedBlockDecls.clear();
4391   }
4392   if (RewriteSC) {
4393     // Must insert any 'const/volatile/static here. Since it has been
4394     // removed as result of rewriting of block literals.
4395     std::string SC;
4396     if (GlobalVarDecl->getStorageClass() == SC_Static)
4397       SC = "static ";
4398     if (GlobalVarDecl->getType().isConstQualified())
4399       SC += "const ";
4400     if (GlobalVarDecl->getType().isVolatileQualified())
4401       SC += "volatile ";
4402     if (GlobalVarDecl->getType().isRestrictQualified())
4403       SC += "restrict ";
4404     InsertText(FunLocStart, SC);
4405   }
4406   if (GlobalConstructionExp) {
4407     // extra fancy dance for global literal expression.
4408 
4409     // Always the latest block expression on the block stack.
4410     std::string Tag = "__";
4411     Tag += FunName;
4412     Tag += "_block_impl_";
4413     Tag += utostr(Blocks.size()-1);
4414     std::string globalBuf = "static ";
4415     globalBuf += Tag; globalBuf += " ";
4416     std::string SStr;
4417 
4418     llvm::raw_string_ostream constructorExprBuf(SStr);
4419     GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4420                                        PrintingPolicy(LangOpts));
4421     globalBuf += constructorExprBuf.str();
4422     globalBuf += ";\n";
4423     InsertText(FunLocStart, globalBuf);
4424     GlobalConstructionExp = nullptr;
4425   }
4426 
4427   Blocks.clear();
4428   InnerDeclRefsCount.clear();
4429   InnerDeclRefs.clear();
4430   RewrittenBlockExprs.clear();
4431 }
4432 
4433 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4434   SourceLocation FunLocStart =
4435     (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4436                       : FD->getTypeSpecStartLoc();
4437   StringRef FuncName = FD->getName();
4438 
4439   SynthesizeBlockLiterals(FunLocStart, FuncName);
4440 }
4441 
4442 static void BuildUniqueMethodName(std::string &Name,
4443                                   ObjCMethodDecl *MD) {
4444   ObjCInterfaceDecl *IFace = MD->getClassInterface();
4445   Name = IFace->getName();
4446   Name += "__" + MD->getSelector().getAsString();
4447   // Convert colons to underscores.
4448   std::string::size_type loc = 0;
4449   while ((loc = Name.find(':', loc)) != std::string::npos)
4450     Name.replace(loc, 1, "_");
4451 }
4452 
4453 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4454   // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4455   // SourceLocation FunLocStart = MD->getBeginLoc();
4456   SourceLocation FunLocStart = MD->getBeginLoc();
4457   std::string FuncName;
4458   BuildUniqueMethodName(FuncName, MD);
4459   SynthesizeBlockLiterals(FunLocStart, FuncName);
4460 }
4461 
4462 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4463   for (Stmt *SubStmt : S->children())
4464     if (SubStmt) {
4465       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4466         GetBlockDeclRefExprs(CBE->getBody());
4467       else
4468         GetBlockDeclRefExprs(SubStmt);
4469     }
4470   // Handle specific things.
4471   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4472     if (DRE->refersToEnclosingVariableOrCapture() ||
4473         HasLocalVariableExternalStorage(DRE->getDecl()))
4474       // FIXME: Handle enums.
4475       BlockDeclRefs.push_back(DRE);
4476 }
4477 
4478 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479                 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4480                 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4481   for (Stmt *SubStmt : S->children())
4482     if (SubStmt) {
4483       if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4484         InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4485         GetInnerBlockDeclRefExprs(CBE->getBody(),
4486                                   InnerBlockDeclRefs,
4487                                   InnerContexts);
4488       }
4489       else
4490         GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4491     }
4492   // Handle specific things.
4493   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4494     if (DRE->refersToEnclosingVariableOrCapture() ||
4495         HasLocalVariableExternalStorage(DRE->getDecl())) {
4496       if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4497         InnerBlockDeclRefs.push_back(DRE);
4498       if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4499         if (Var->isFunctionOrMethodVarDecl())
4500           ImportedLocalExternalDecls.insert(Var);
4501     }
4502   }
4503 }
4504 
4505 /// convertObjCTypeToCStyleType - This routine converts such objc types
4506 /// as qualified objects, and blocks to their closest c/c++ types that
4507 /// it can. It returns true if input type was modified.
4508 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4509   QualType oldT = T;
4510   convertBlockPointerToFunctionPointer(T);
4511   if (T->isFunctionPointerType()) {
4512     QualType PointeeTy;
4513     if (const PointerType* PT = T->getAs<PointerType>()) {
4514       PointeeTy = PT->getPointeeType();
4515       if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4516         T = convertFunctionTypeOfBlocks(FT);
4517         T = Context->getPointerType(T);
4518       }
4519     }
4520   }
4521 
4522   convertToUnqualifiedObjCType(T);
4523   return T != oldT;
4524 }
4525 
4526 /// convertFunctionTypeOfBlocks - This routine converts a function type
4527 /// whose result type may be a block pointer or whose argument type(s)
4528 /// might be block pointers to an equivalent function type replacing
4529 /// all block pointers to function pointers.
4530 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4531   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4532   // FTP will be null for closures that don't take arguments.
4533   // Generate a funky cast.
4534   SmallVector<QualType, 8> ArgTypes;
4535   QualType Res = FT->getReturnType();
4536   bool modified = convertObjCTypeToCStyleType(Res);
4537 
4538   if (FTP) {
4539     for (auto &I : FTP->param_types()) {
4540       QualType t = I;
4541       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4542       if (convertObjCTypeToCStyleType(t))
4543         modified = true;
4544       ArgTypes.push_back(t);
4545     }
4546   }
4547   QualType FuncType;
4548   if (modified)
4549     FuncType = getSimpleFunctionType(Res, ArgTypes);
4550   else FuncType = QualType(FT, 0);
4551   return FuncType;
4552 }
4553 
4554 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4555   // Navigate to relevant type information.
4556   const BlockPointerType *CPT = nullptr;
4557 
4558   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4559     CPT = DRE->getType()->getAs<BlockPointerType>();
4560   } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4561     CPT = MExpr->getType()->getAs<BlockPointerType>();
4562   }
4563   else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4564     return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4565   }
4566   else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4567     CPT = IEXPR->getType()->getAs<BlockPointerType>();
4568   else if (const ConditionalOperator *CEXPR =
4569             dyn_cast<ConditionalOperator>(BlockExp)) {
4570     Expr *LHSExp = CEXPR->getLHS();
4571     Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4572     Expr *RHSExp = CEXPR->getRHS();
4573     Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4574     Expr *CONDExp = CEXPR->getCond();
4575     ConditionalOperator *CondExpr =
4576       new (Context) ConditionalOperator(CONDExp,
4577                                       SourceLocation(), cast<Expr>(LHSStmt),
4578                                       SourceLocation(), cast<Expr>(RHSStmt),
4579                                       Exp->getType(), VK_RValue, OK_Ordinary);
4580     return CondExpr;
4581   } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4582     CPT = IRE->getType()->getAs<BlockPointerType>();
4583   } else if (const PseudoObjectExpr *POE
4584                = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4585     CPT = POE->getType()->castAs<BlockPointerType>();
4586   } else {
4587     assert(false && "RewriteBlockClass: Bad type");
4588   }
4589   assert(CPT && "RewriteBlockClass: Bad type");
4590   const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4591   assert(FT && "RewriteBlockClass: Bad type");
4592   const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593   // FTP will be null for closures that don't take arguments.
4594 
4595   RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596                                       SourceLocation(), SourceLocation(),
4597                                       &Context->Idents.get("__block_impl"));
4598   QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4599 
4600   // Generate a funky cast.
4601   SmallVector<QualType, 8> ArgTypes;
4602 
4603   // Push the block argument type.
4604   ArgTypes.push_back(PtrBlock);
4605   if (FTP) {
4606     for (auto &I : FTP->param_types()) {
4607       QualType t = I;
4608       // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609       if (!convertBlockPointerToFunctionPointer(t))
4610         convertToUnqualifiedObjCType(t);
4611       ArgTypes.push_back(t);
4612     }
4613   }
4614   // Now do the pointer to function cast.
4615   QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4616 
4617   PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4618 
4619   CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4620                                                CK_BitCast,
4621                                                const_cast<Expr*>(BlockExp));
4622   // Don't forget the parens to enforce the proper binding.
4623   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4624                                           BlkCast);
4625   //PE->dump();
4626 
4627   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4628                                     SourceLocation(),
4629                                     &Context->Idents.get("FuncPtr"),
4630                                     Context->VoidPtrTy, nullptr,
4631                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4632                                     ICIS_NoInit);
4633   MemberExpr *ME = MemberExpr::CreateImplicit(
4634       *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4635 
4636   CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4637                                                 CK_BitCast, ME);
4638   PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4639 
4640   SmallVector<Expr*, 8> BlkExprs;
4641   // Add the implicit argument.
4642   BlkExprs.push_back(BlkCast);
4643   // Add the user arguments.
4644   for (CallExpr::arg_iterator I = Exp->arg_begin(),
4645        E = Exp->arg_end(); I != E; ++I) {
4646     BlkExprs.push_back(*I);
4647   }
4648   CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4649                                   VK_RValue, SourceLocation());
4650   return CE;
4651 }
4652 
4653 // We need to return the rewritten expression to handle cases where the
4654 // DeclRefExpr is embedded in another expression being rewritten.
4655 // For example:
4656 //
4657 // int main() {
4658 //    __block Foo *f;
4659 //    __block int i;
4660 //
4661 //    void (^myblock)() = ^() {
4662 //        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4663 //        i = 77;
4664 //    };
4665 //}
4666 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4667   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4668   // for each DeclRefExp where BYREFVAR is name of the variable.
4669   ValueDecl *VD = DeclRefExp->getDecl();
4670   bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4671                  HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4672 
4673   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4674                                     SourceLocation(),
4675                                     &Context->Idents.get("__forwarding"),
4676                                     Context->VoidPtrTy, nullptr,
4677                                     /*BitWidth=*/nullptr, /*Mutable=*/true,
4678                                     ICIS_NoInit);
4679   MemberExpr *ME = MemberExpr::CreateImplicit(
4680       *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4681 
4682   StringRef Name = VD->getName();
4683   FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4684                          &Context->Idents.get(Name),
4685                          Context->VoidPtrTy, nullptr,
4686                          /*BitWidth=*/nullptr, /*Mutable=*/true,
4687                          ICIS_NoInit);
4688   ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4689                                   VK_LValue, OK_Ordinary);
4690 
4691   // Need parens to enforce precedence.
4692   ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4693                                           DeclRefExp->getExprLoc(),
4694                                           ME);
4695   ReplaceStmt(DeclRefExp, PE);
4696   return PE;
4697 }
4698 
4699 // Rewrites the imported local variable V with external storage
4700 // (static, extern, etc.) as *V
4701 //
4702 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4703   ValueDecl *VD = DRE->getDecl();
4704   if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4705     if (!ImportedLocalExternalDecls.count(Var))
4706       return DRE;
4707   Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4708                                           VK_LValue, OK_Ordinary,
4709                                           DRE->getLocation(), false);
4710   // Need parens to enforce precedence.
4711   ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4712                                           Exp);
4713   ReplaceStmt(DRE, PE);
4714   return PE;
4715 }
4716 
4717 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4718   SourceLocation LocStart = CE->getLParenLoc();
4719   SourceLocation LocEnd = CE->getRParenLoc();
4720 
4721   // Need to avoid trying to rewrite synthesized casts.
4722   if (LocStart.isInvalid())
4723     return;
4724   // Need to avoid trying to rewrite casts contained in macros.
4725   if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4726     return;
4727 
4728   const char *startBuf = SM->getCharacterData(LocStart);
4729   const char *endBuf = SM->getCharacterData(LocEnd);
4730   QualType QT = CE->getType();
4731   const Type* TypePtr = QT->getAs<Type>();
4732   if (isa<TypeOfExprType>(TypePtr)) {
4733     const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4734     QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4735     std::string TypeAsString = "(";
4736     RewriteBlockPointerType(TypeAsString, QT);
4737     TypeAsString += ")";
4738     ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4739     return;
4740   }
4741   // advance the location to startArgList.
4742   const char *argPtr = startBuf;
4743 
4744   while (*argPtr++ && (argPtr < endBuf)) {
4745     switch (*argPtr) {
4746     case '^':
4747       // Replace the '^' with '*'.
4748       LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4749       ReplaceText(LocStart, 1, "*");
4750       break;
4751     }
4752   }
4753 }
4754 
4755 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4756   CastKind CastKind = IC->getCastKind();
4757   if (CastKind != CK_BlockPointerToObjCPointerCast &&
4758       CastKind != CK_AnyPointerToBlockPointerCast)
4759     return;
4760 
4761   QualType QT = IC->getType();
4762   (void)convertBlockPointerToFunctionPointer(QT);
4763   std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4764   std::string Str = "(";
4765   Str += TypeString;
4766   Str += ")";
4767   InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4768 }
4769 
4770 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4771   SourceLocation DeclLoc = FD->getLocation();
4772   unsigned parenCount = 0;
4773 
4774   // We have 1 or more arguments that have closure pointers.
4775   const char *startBuf = SM->getCharacterData(DeclLoc);
4776   const char *startArgList = strchr(startBuf, '(');
4777 
4778   assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4779 
4780   parenCount++;
4781   // advance the location to startArgList.
4782   DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4783   assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4784 
4785   const char *argPtr = startArgList;
4786 
4787   while (*argPtr++ && parenCount) {
4788     switch (*argPtr) {
4789     case '^':
4790       // Replace the '^' with '*'.
4791       DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4792       ReplaceText(DeclLoc, 1, "*");
4793       break;
4794     case '(':
4795       parenCount++;
4796       break;
4797     case ')':
4798       parenCount--;
4799       break;
4800     }
4801   }
4802 }
4803 
4804 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4805   const FunctionProtoType *FTP;
4806   const PointerType *PT = QT->getAs<PointerType>();
4807   if (PT) {
4808     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4809   } else {
4810     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4811     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4812     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4813   }
4814   if (FTP) {
4815     for (const auto &I : FTP->param_types())
4816       if (isTopLevelBlockPointerType(I))
4817         return true;
4818   }
4819   return false;
4820 }
4821 
4822 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4823   const FunctionProtoType *FTP;
4824   const PointerType *PT = QT->getAs<PointerType>();
4825   if (PT) {
4826     FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4827   } else {
4828     const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4829     assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4830     FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4831   }
4832   if (FTP) {
4833     for (const auto &I : FTP->param_types()) {
4834       if (I->isObjCQualifiedIdType())
4835         return true;
4836       if (I->isObjCObjectPointerType() &&
4837           I->getPointeeType()->isObjCQualifiedInterfaceType())
4838         return true;
4839     }
4840 
4841   }
4842   return false;
4843 }
4844 
4845 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4846                                      const char *&RParen) {
4847   const char *argPtr = strchr(Name, '(');
4848   assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4849 
4850   LParen = argPtr; // output the start.
4851   argPtr++; // skip past the left paren.
4852   unsigned parenCount = 1;
4853 
4854   while (*argPtr && parenCount) {
4855     switch (*argPtr) {
4856     case '(': parenCount++; break;
4857     case ')': parenCount--; break;
4858     default: break;
4859     }
4860     if (parenCount) argPtr++;
4861   }
4862   assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4863   RParen = argPtr; // output the end
4864 }
4865 
4866 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4867   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4868     RewriteBlockPointerFunctionArgs(FD);
4869     return;
4870   }
4871   // Handle Variables and Typedefs.
4872   SourceLocation DeclLoc = ND->getLocation();
4873   QualType DeclT;
4874   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4875     DeclT = VD->getType();
4876   else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4877     DeclT = TDD->getUnderlyingType();
4878   else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4879     DeclT = FD->getType();
4880   else
4881     llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4882 
4883   const char *startBuf = SM->getCharacterData(DeclLoc);
4884   const char *endBuf = startBuf;
4885   // scan backward (from the decl location) for the end of the previous decl.
4886   while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4887     startBuf--;
4888   SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4889   std::string buf;
4890   unsigned OrigLength=0;
4891   // *startBuf != '^' if we are dealing with a pointer to function that
4892   // may take block argument types (which will be handled below).
4893   if (*startBuf == '^') {
4894     // Replace the '^' with '*', computing a negative offset.
4895     buf = '*';
4896     startBuf++;
4897     OrigLength++;
4898   }
4899   while (*startBuf != ')') {
4900     buf += *startBuf;
4901     startBuf++;
4902     OrigLength++;
4903   }
4904   buf += ')';
4905   OrigLength++;
4906 
4907   if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4908       PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4909     // Replace the '^' with '*' for arguments.
4910     // Replace id<P> with id/*<>*/
4911     DeclLoc = ND->getLocation();
4912     startBuf = SM->getCharacterData(DeclLoc);
4913     const char *argListBegin, *argListEnd;
4914     GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4915     while (argListBegin < argListEnd) {
4916       if (*argListBegin == '^')
4917         buf += '*';
4918       else if (*argListBegin ==  '<') {
4919         buf += "/*";
4920         buf += *argListBegin++;
4921         OrigLength++;
4922         while (*argListBegin != '>') {
4923           buf += *argListBegin++;
4924           OrigLength++;
4925         }
4926         buf += *argListBegin;
4927         buf += "*/";
4928       }
4929       else
4930         buf += *argListBegin;
4931       argListBegin++;
4932       OrigLength++;
4933     }
4934     buf += ')';
4935     OrigLength++;
4936   }
4937   ReplaceText(Start, OrigLength, buf);
4938 }
4939 
4940 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4941 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4942 ///                    struct Block_byref_id_object *src) {
4943 ///  _Block_object_assign (&_dest->object, _src->object,
4944 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4945 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4946 ///  _Block_object_assign(&_dest->object, _src->object,
4947 ///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4948 ///                       [|BLOCK_FIELD_IS_WEAK]) // block
4949 /// }
4950 /// And:
4951 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4952 ///  _Block_object_dispose(_src->object,
4953 ///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4954 ///                        [|BLOCK_FIELD_IS_WEAK]) // object
4955 ///  _Block_object_dispose(_src->object,
4956 ///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4957 ///                         [|BLOCK_FIELD_IS_WEAK]) // block
4958 /// }
4959 
4960 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4961                                                           int flag) {
4962   std::string S;
4963   if (CopyDestroyCache.count(flag))
4964     return S;
4965   CopyDestroyCache.insert(flag);
4966   S = "static void __Block_byref_id_object_copy_";
4967   S += utostr(flag);
4968   S += "(void *dst, void *src) {\n";
4969 
4970   // offset into the object pointer is computed as:
4971   // void * + void* + int + int + void* + void *
4972   unsigned IntSize =
4973   static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4974   unsigned VoidPtrSize =
4975   static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4976 
4977   unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4978   S += " _Block_object_assign((char*)dst + ";
4979   S += utostr(offset);
4980   S += ", *(void * *) ((char*)src + ";
4981   S += utostr(offset);
4982   S += "), ";
4983   S += utostr(flag);
4984   S += ");\n}\n";
4985 
4986   S += "static void __Block_byref_id_object_dispose_";
4987   S += utostr(flag);
4988   S += "(void *src) {\n";
4989   S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4990   S += utostr(offset);
4991   S += "), ";
4992   S += utostr(flag);
4993   S += ");\n}\n";
4994   return S;
4995 }
4996 
4997 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4998 /// the declaration into:
4999 /// struct __Block_byref_ND {
5000 /// void *__isa;                  // NULL for everything except __weak pointers
5001 /// struct __Block_byref_ND *__forwarding;
5002 /// int32_t __flags;
5003 /// int32_t __size;
5004 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5005 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5006 /// typex ND;
5007 /// };
5008 ///
5009 /// It then replaces declaration of ND variable with:
5010 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5011 ///                               __size=sizeof(struct __Block_byref_ND),
5012 ///                               ND=initializer-if-any};
5013 ///
5014 ///
5015 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5016                                         bool lastDecl) {
5017   int flag = 0;
5018   int isa = 0;
5019   SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5020   if (DeclLoc.isInvalid())
5021     // If type location is missing, it is because of missing type (a warning).
5022     // Use variable's location which is good for this case.
5023     DeclLoc = ND->getLocation();
5024   const char *startBuf = SM->getCharacterData(DeclLoc);
5025   SourceLocation X = ND->getEndLoc();
5026   X = SM->getExpansionLoc(X);
5027   const char *endBuf = SM->getCharacterData(X);
5028   std::string Name(ND->getNameAsString());
5029   std::string ByrefType;
5030   RewriteByRefString(ByrefType, Name, ND, true);
5031   ByrefType += " {\n";
5032   ByrefType += "  void *__isa;\n";
5033   RewriteByRefString(ByrefType, Name, ND);
5034   ByrefType += " *__forwarding;\n";
5035   ByrefType += " int __flags;\n";
5036   ByrefType += " int __size;\n";
5037   // Add void *__Block_byref_id_object_copy;
5038   // void *__Block_byref_id_object_dispose; if needed.
5039   QualType Ty = ND->getType();
5040   bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5041   if (HasCopyAndDispose) {
5042     ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5043     ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5044   }
5045 
5046   QualType T = Ty;
5047   (void)convertBlockPointerToFunctionPointer(T);
5048   T.getAsStringInternal(Name, Context->getPrintingPolicy());
5049 
5050   ByrefType += " " + Name + ";\n";
5051   ByrefType += "};\n";
5052   // Insert this type in global scope. It is needed by helper function.
5053   SourceLocation FunLocStart;
5054   if (CurFunctionDef)
5055      FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5056   else {
5057     assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5058     FunLocStart = CurMethodDef->getBeginLoc();
5059   }
5060   InsertText(FunLocStart, ByrefType);
5061 
5062   if (Ty.isObjCGCWeak()) {
5063     flag |= BLOCK_FIELD_IS_WEAK;
5064     isa = 1;
5065   }
5066   if (HasCopyAndDispose) {
5067     flag = BLOCK_BYREF_CALLER;
5068     QualType Ty = ND->getType();
5069     // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5070     if (Ty->isBlockPointerType())
5071       flag |= BLOCK_FIELD_IS_BLOCK;
5072     else
5073       flag |= BLOCK_FIELD_IS_OBJECT;
5074     std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5075     if (!HF.empty())
5076       Preamble += HF;
5077   }
5078 
5079   // struct __Block_byref_ND ND =
5080   // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5081   //  initializer-if-any};
5082   bool hasInit = (ND->getInit() != nullptr);
5083   // FIXME. rewriter does not support __block c++ objects which
5084   // require construction.
5085   if (hasInit)
5086     if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5087       CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5088       if (CXXDecl && CXXDecl->isDefaultConstructor())
5089         hasInit = false;
5090     }
5091 
5092   unsigned flags = 0;
5093   if (HasCopyAndDispose)
5094     flags |= BLOCK_HAS_COPY_DISPOSE;
5095   Name = ND->getNameAsString();
5096   ByrefType.clear();
5097   RewriteByRefString(ByrefType, Name, ND);
5098   std::string ForwardingCastType("(");
5099   ForwardingCastType += ByrefType + " *)";
5100   ByrefType += " " + Name + " = {(void*)";
5101   ByrefType += utostr(isa);
5102   ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
5103   ByrefType += utostr(flags);
5104   ByrefType += ", ";
5105   ByrefType += "sizeof(";
5106   RewriteByRefString(ByrefType, Name, ND);
5107   ByrefType += ")";
5108   if (HasCopyAndDispose) {
5109     ByrefType += ", __Block_byref_id_object_copy_";
5110     ByrefType += utostr(flag);
5111     ByrefType += ", __Block_byref_id_object_dispose_";
5112     ByrefType += utostr(flag);
5113   }
5114 
5115   if (!firstDecl) {
5116     // In multiple __block declarations, and for all but 1st declaration,
5117     // find location of the separating comma. This would be start location
5118     // where new text is to be inserted.
5119     DeclLoc = ND->getLocation();
5120     const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5121     const char *commaBuf = startDeclBuf;
5122     while (*commaBuf != ',')
5123       commaBuf--;
5124     assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5125     DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5126     startBuf = commaBuf;
5127   }
5128 
5129   if (!hasInit) {
5130     ByrefType += "};\n";
5131     unsigned nameSize = Name.size();
5132     // for block or function pointer declaration. Name is already
5133     // part of the declaration.
5134     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5135       nameSize = 1;
5136     ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5137   }
5138   else {
5139     ByrefType += ", ";
5140     SourceLocation startLoc;
5141     Expr *E = ND->getInit();
5142     if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5143       startLoc = ECE->getLParenLoc();
5144     else
5145       startLoc = E->getBeginLoc();
5146     startLoc = SM->getExpansionLoc(startLoc);
5147     endBuf = SM->getCharacterData(startLoc);
5148     ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5149 
5150     const char separator = lastDecl ? ';' : ',';
5151     const char *startInitializerBuf = SM->getCharacterData(startLoc);
5152     const char *separatorBuf = strchr(startInitializerBuf, separator);
5153     assert((*separatorBuf == separator) &&
5154            "RewriteByRefVar: can't find ';' or ','");
5155     SourceLocation separatorLoc =
5156       startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5157 
5158     InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5159   }
5160 }
5161 
5162 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5163   // Add initializers for any closure decl refs.
5164   GetBlockDeclRefExprs(Exp->getBody());
5165   if (BlockDeclRefs.size()) {
5166     // Unique all "by copy" declarations.
5167     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5168       if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5169         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5170           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5171           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5172         }
5173       }
5174     // Unique all "by ref" declarations.
5175     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5176       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5177         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5178           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5179           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5180         }
5181       }
5182     // Find any imported blocks...they will need special attention.
5183     for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5184       if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5185           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5186           BlockDeclRefs[i]->getType()->isBlockPointerType())
5187         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5188   }
5189 }
5190 
5191 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5192   IdentifierInfo *ID = &Context->Idents.get(name);
5193   QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5194   return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5195                               SourceLocation(), ID, FType, nullptr, SC_Extern,
5196                               false, false);
5197 }
5198 
5199 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5200                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5201   const BlockDecl *block = Exp->getBlockDecl();
5202 
5203   Blocks.push_back(Exp);
5204 
5205   CollectBlockDeclRefInfo(Exp);
5206 
5207   // Add inner imported variables now used in current block.
5208   int countOfInnerDecls = 0;
5209   if (!InnerBlockDeclRefs.empty()) {
5210     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5211       DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5212       ValueDecl *VD = Exp->getDecl();
5213       if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5214       // We need to save the copied-in variables in nested
5215       // blocks because it is needed at the end for some of the API generations.
5216       // See SynthesizeBlockLiterals routine.
5217         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5218         BlockDeclRefs.push_back(Exp);
5219         BlockByCopyDeclsPtrSet.insert(VD);
5220         BlockByCopyDecls.push_back(VD);
5221       }
5222       if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5223         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5224         BlockDeclRefs.push_back(Exp);
5225         BlockByRefDeclsPtrSet.insert(VD);
5226         BlockByRefDecls.push_back(VD);
5227       }
5228     }
5229     // Find any imported blocks...they will need special attention.
5230     for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5231       if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5232           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5233           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5234         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5235   }
5236   InnerDeclRefsCount.push_back(countOfInnerDecls);
5237 
5238   std::string FuncName;
5239 
5240   if (CurFunctionDef)
5241     FuncName = CurFunctionDef->getNameAsString();
5242   else if (CurMethodDef)
5243     BuildUniqueMethodName(FuncName, CurMethodDef);
5244   else if (GlobalVarDecl)
5245     FuncName = std::string(GlobalVarDecl->getNameAsString());
5246 
5247   bool GlobalBlockExpr =
5248     block->getDeclContext()->getRedeclContext()->isFileContext();
5249 
5250   if (GlobalBlockExpr && !GlobalVarDecl) {
5251     Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5252     GlobalBlockExpr = false;
5253   }
5254 
5255   std::string BlockNumber = utostr(Blocks.size()-1);
5256 
5257   std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5258 
5259   // Get a pointer to the function type so we can cast appropriately.
5260   QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5261   QualType FType = Context->getPointerType(BFT);
5262 
5263   FunctionDecl *FD;
5264   Expr *NewRep;
5265 
5266   // Simulate a constructor call...
5267   std::string Tag;
5268 
5269   if (GlobalBlockExpr)
5270     Tag = "__global_";
5271   else
5272     Tag = "__";
5273   Tag += FuncName + "_block_impl_" + BlockNumber;
5274 
5275   FD = SynthBlockInitFunctionDecl(Tag);
5276   DeclRefExpr *DRE = new (Context)
5277       DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
5278 
5279   SmallVector<Expr*, 4> InitExprs;
5280 
5281   // Initialize the block function.
5282   FD = SynthBlockInitFunctionDecl(Func);
5283   DeclRefExpr *Arg = new (Context) DeclRefExpr(
5284       *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5285   CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5286                                                 CK_BitCast, Arg);
5287   InitExprs.push_back(castExpr);
5288 
5289   // Initialize the block descriptor.
5290   std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5291 
5292   VarDecl *NewVD = VarDecl::Create(
5293       *Context, TUDecl, SourceLocation(), SourceLocation(),
5294       &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5295   UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5296       new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5297                                 VK_LValue, SourceLocation()),
5298       UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5299       OK_Ordinary, SourceLocation(), false);
5300   InitExprs.push_back(DescRefExpr);
5301 
5302   // Add initializers for any closure decl refs.
5303   if (BlockDeclRefs.size()) {
5304     Expr *Exp;
5305     // Output all "by copy" declarations.
5306     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5307          E = BlockByCopyDecls.end(); I != E; ++I) {
5308       if (isObjCType((*I)->getType())) {
5309         // FIXME: Conform to ABI ([[obj retain] autorelease]).
5310         FD = SynthBlockInitFunctionDecl((*I)->getName());
5311         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5312                                         VK_LValue, SourceLocation());
5313         if (HasLocalVariableExternalStorage(*I)) {
5314           QualType QT = (*I)->getType();
5315           QT = Context->getPointerType(QT);
5316           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5317                                             OK_Ordinary, SourceLocation(),
5318                                             false);
5319         }
5320       } else if (isTopLevelBlockPointerType((*I)->getType())) {
5321         FD = SynthBlockInitFunctionDecl((*I)->getName());
5322         Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5323                                         VK_LValue, SourceLocation());
5324         Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5325                                        CK_BitCast, Arg);
5326       } else {
5327         FD = SynthBlockInitFunctionDecl((*I)->getName());
5328         Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5329                                         VK_LValue, SourceLocation());
5330         if (HasLocalVariableExternalStorage(*I)) {
5331           QualType QT = (*I)->getType();
5332           QT = Context->getPointerType(QT);
5333           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5334                                             OK_Ordinary, SourceLocation(),
5335                                             false);
5336         }
5337 
5338       }
5339       InitExprs.push_back(Exp);
5340     }
5341     // Output all "by ref" declarations.
5342     for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5343          E = BlockByRefDecls.end(); I != E; ++I) {
5344       ValueDecl *ND = (*I);
5345       std::string Name(ND->getNameAsString());
5346       std::string RecName;
5347       RewriteByRefString(RecName, Name, ND, true);
5348       IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5349                                                 + sizeof("struct"));
5350       RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5351                                           SourceLocation(), SourceLocation(),
5352                                           II);
5353       assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5354       QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5355 
5356       FD = SynthBlockInitFunctionDecl((*I)->getName());
5357       Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5358                                       VK_LValue, SourceLocation());
5359       bool isNestedCapturedVar = false;
5360       if (block)
5361         for (const auto &CI : block->captures()) {
5362           const VarDecl *variable = CI.getVariable();
5363           if (variable == ND && CI.isNested()) {
5364             assert (CI.isByRef() &&
5365                     "SynthBlockInitExpr - captured block variable is not byref");
5366             isNestedCapturedVar = true;
5367             break;
5368           }
5369         }
5370       // captured nested byref variable has its address passed. Do not take
5371       // its address again.
5372       if (!isNestedCapturedVar)
5373           Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5374                                      Context->getPointerType(Exp->getType()),
5375                                      VK_RValue, OK_Ordinary, SourceLocation(),
5376                                      false);
5377       Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5378       InitExprs.push_back(Exp);
5379     }
5380   }
5381   if (ImportedBlockDecls.size()) {
5382     // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5383     int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5384     unsigned IntSize =
5385       static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5386     Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5387                                            Context->IntTy, SourceLocation());
5388     InitExprs.push_back(FlagExp);
5389   }
5390   NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5391                             SourceLocation());
5392 
5393   if (GlobalBlockExpr) {
5394     assert (!GlobalConstructionExp &&
5395             "SynthBlockInitExpr - GlobalConstructionExp must be null");
5396     GlobalConstructionExp = NewRep;
5397     NewRep = DRE;
5398   }
5399 
5400   NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5401                              Context->getPointerType(NewRep->getType()),
5402                              VK_RValue, OK_Ordinary, SourceLocation(), false);
5403   NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5404                                     NewRep);
5405   // Put Paren around the call.
5406   NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5407                                    NewRep);
5408 
5409   BlockDeclRefs.clear();
5410   BlockByRefDecls.clear();
5411   BlockByRefDeclsPtrSet.clear();
5412   BlockByCopyDecls.clear();
5413   BlockByCopyDeclsPtrSet.clear();
5414   ImportedBlockDecls.clear();
5415   return NewRep;
5416 }
5417 
5418 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5419   if (const ObjCForCollectionStmt * CS =
5420       dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5421         return CS->getElement() == DS;
5422   return false;
5423 }
5424 
5425 //===----------------------------------------------------------------------===//
5426 // Function Body / Expression rewriting
5427 //===----------------------------------------------------------------------===//
5428 
5429 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5430   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5431       isa<DoStmt>(S) || isa<ForStmt>(S))
5432     Stmts.push_back(S);
5433   else if (isa<ObjCForCollectionStmt>(S)) {
5434     Stmts.push_back(S);
5435     ObjCBcLabelNo.push_back(++BcLabelCount);
5436   }
5437 
5438   // Pseudo-object operations and ivar references need special
5439   // treatment because we're going to recursively rewrite them.
5440   if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5441     if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5442       return RewritePropertyOrImplicitSetter(PseudoOp);
5443     } else {
5444       return RewritePropertyOrImplicitGetter(PseudoOp);
5445     }
5446   } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5447     return RewriteObjCIvarRefExpr(IvarRefExpr);
5448   }
5449   else if (isa<OpaqueValueExpr>(S))
5450     S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5451 
5452   SourceRange OrigStmtRange = S->getSourceRange();
5453 
5454   // Perform a bottom up rewrite of all children.
5455   for (Stmt *&childStmt : S->children())
5456     if (childStmt) {
5457       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5458       if (newStmt) {
5459         childStmt = newStmt;
5460       }
5461     }
5462 
5463   if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5464     SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5465     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5466     InnerContexts.insert(BE->getBlockDecl());
5467     ImportedLocalExternalDecls.clear();
5468     GetInnerBlockDeclRefExprs(BE->getBody(),
5469                               InnerBlockDeclRefs, InnerContexts);
5470     // Rewrite the block body in place.
5471     Stmt *SaveCurrentBody = CurrentBody;
5472     CurrentBody = BE->getBody();
5473     PropParentMap = nullptr;
5474     // block literal on rhs of a property-dot-sytax assignment
5475     // must be replaced by its synthesize ast so getRewrittenText
5476     // works as expected. In this case, what actually ends up on RHS
5477     // is the blockTranscribed which is the helper function for the
5478     // block literal; as in: self.c = ^() {[ace ARR];};
5479     bool saveDisableReplaceStmt = DisableReplaceStmt;
5480     DisableReplaceStmt = false;
5481     RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5482     DisableReplaceStmt = saveDisableReplaceStmt;
5483     CurrentBody = SaveCurrentBody;
5484     PropParentMap = nullptr;
5485     ImportedLocalExternalDecls.clear();
5486     // Now we snarf the rewritten text and stash it away for later use.
5487     std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5488     RewrittenBlockExprs[BE] = Str;
5489 
5490     Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5491 
5492     //blockTranscribed->dump();
5493     ReplaceStmt(S, blockTranscribed);
5494     return blockTranscribed;
5495   }
5496   // Handle specific things.
5497   if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5498     return RewriteAtEncode(AtEncode);
5499 
5500   if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5501     return RewriteAtSelector(AtSelector);
5502 
5503   if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5504     return RewriteObjCStringLiteral(AtString);
5505 
5506   if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5507     return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5508 
5509   if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5510     return RewriteObjCBoxedExpr(BoxedExpr);
5511 
5512   if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5513     return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5514 
5515   if (ObjCDictionaryLiteral *DictionaryLitExpr =
5516         dyn_cast<ObjCDictionaryLiteral>(S))
5517     return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5518 
5519   if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5520 #if 0
5521     // Before we rewrite it, put the original message expression in a comment.
5522     SourceLocation startLoc = MessExpr->getBeginLoc();
5523     SourceLocation endLoc = MessExpr->getEndLoc();
5524 
5525     const char *startBuf = SM->getCharacterData(startLoc);
5526     const char *endBuf = SM->getCharacterData(endLoc);
5527 
5528     std::string messString;
5529     messString += "// ";
5530     messString.append(startBuf, endBuf-startBuf+1);
5531     messString += "\n";
5532 
5533     // FIXME: Missing definition of
5534     // InsertText(clang::SourceLocation, char const*, unsigned int).
5535     // InsertText(startLoc, messString);
5536     // Tried this, but it didn't work either...
5537     // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5538 #endif
5539     return RewriteMessageExpr(MessExpr);
5540   }
5541 
5542   if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5543         dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5544     return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5545   }
5546 
5547   if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5548     return RewriteObjCTryStmt(StmtTry);
5549 
5550   if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5551     return RewriteObjCSynchronizedStmt(StmtTry);
5552 
5553   if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5554     return RewriteObjCThrowStmt(StmtThrow);
5555 
5556   if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5557     return RewriteObjCProtocolExpr(ProtocolExp);
5558 
5559   if (ObjCForCollectionStmt *StmtForCollection =
5560         dyn_cast<ObjCForCollectionStmt>(S))
5561     return RewriteObjCForCollectionStmt(StmtForCollection,
5562                                         OrigStmtRange.getEnd());
5563   if (BreakStmt *StmtBreakStmt =
5564       dyn_cast<BreakStmt>(S))
5565     return RewriteBreakStmt(StmtBreakStmt);
5566   if (ContinueStmt *StmtContinueStmt =
5567       dyn_cast<ContinueStmt>(S))
5568     return RewriteContinueStmt(StmtContinueStmt);
5569 
5570   // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5571   // and cast exprs.
5572   if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5573     // FIXME: What we're doing here is modifying the type-specifier that
5574     // precedes the first Decl.  In the future the DeclGroup should have
5575     // a separate type-specifier that we can rewrite.
5576     // NOTE: We need to avoid rewriting the DeclStmt if it is within
5577     // the context of an ObjCForCollectionStmt. For example:
5578     //   NSArray *someArray;
5579     //   for (id <FooProtocol> index in someArray) ;
5580     // This is because RewriteObjCForCollectionStmt() does textual rewriting
5581     // and it depends on the original text locations/positions.
5582     if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5583       RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5584 
5585     // Blocks rewrite rules.
5586     for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5587          DI != DE; ++DI) {
5588       Decl *SD = *DI;
5589       if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5590         if (isTopLevelBlockPointerType(ND->getType()))
5591           RewriteBlockPointerDecl(ND);
5592         else if (ND->getType()->isFunctionPointerType())
5593           CheckFunctionPointerDecl(ND->getType(), ND);
5594         if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5595           if (VD->hasAttr<BlocksAttr>()) {
5596             static unsigned uniqueByrefDeclCount = 0;
5597             assert(!BlockByRefDeclNo.count(ND) &&
5598               "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5599             BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5600             RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5601           }
5602           else
5603             RewriteTypeOfDecl(VD);
5604         }
5605       }
5606       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5607         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5608           RewriteBlockPointerDecl(TD);
5609         else if (TD->getUnderlyingType()->isFunctionPointerType())
5610           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5611       }
5612     }
5613   }
5614 
5615   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5616     RewriteObjCQualifiedInterfaceTypes(CE);
5617 
5618   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5619       isa<DoStmt>(S) || isa<ForStmt>(S)) {
5620     assert(!Stmts.empty() && "Statement stack is empty");
5621     assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5622              isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5623             && "Statement stack mismatch");
5624     Stmts.pop_back();
5625   }
5626   // Handle blocks rewriting.
5627   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5628     ValueDecl *VD = DRE->getDecl();
5629     if (VD->hasAttr<BlocksAttr>())
5630       return RewriteBlockDeclRefExpr(DRE);
5631     if (HasLocalVariableExternalStorage(VD))
5632       return RewriteLocalVariableExternalStorage(DRE);
5633   }
5634 
5635   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5636     if (CE->getCallee()->getType()->isBlockPointerType()) {
5637       Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5638       ReplaceStmt(S, BlockCall);
5639       return BlockCall;
5640     }
5641   }
5642   if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5643     RewriteCastExpr(CE);
5644   }
5645   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5646     RewriteImplicitCastObjCExpr(ICE);
5647   }
5648 #if 0
5649 
5650   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5651     CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5652                                                    ICE->getSubExpr(),
5653                                                    SourceLocation());
5654     // Get the new text.
5655     std::string SStr;
5656     llvm::raw_string_ostream Buf(SStr);
5657     Replacement->printPretty(Buf);
5658     const std::string &Str = Buf.str();
5659 
5660     printf("CAST = %s\n", &Str[0]);
5661     InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5662     delete S;
5663     return Replacement;
5664   }
5665 #endif
5666   // Return this stmt unmodified.
5667   return S;
5668 }
5669 
5670 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5671   for (auto *FD : RD->fields()) {
5672     if (isTopLevelBlockPointerType(FD->getType()))
5673       RewriteBlockPointerDecl(FD);
5674     if (FD->getType()->isObjCQualifiedIdType() ||
5675         FD->getType()->isObjCQualifiedInterfaceType())
5676       RewriteObjCQualifiedInterfaceTypes(FD);
5677   }
5678 }
5679 
5680 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5681 /// main file of the input.
5682 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5683   switch (D->getKind()) {
5684     case Decl::Function: {
5685       FunctionDecl *FD = cast<FunctionDecl>(D);
5686       if (FD->isOverloadedOperator())
5687         return;
5688 
5689       // Since function prototypes don't have ParmDecl's, we check the function
5690       // prototype. This enables us to rewrite function declarations and
5691       // definitions using the same code.
5692       RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5693 
5694       if (!FD->isThisDeclarationADefinition())
5695         break;
5696 
5697       // FIXME: If this should support Obj-C++, support CXXTryStmt
5698       if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5699         CurFunctionDef = FD;
5700         CurrentBody = Body;
5701         Body =
5702         cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5703         FD->setBody(Body);
5704         CurrentBody = nullptr;
5705         if (PropParentMap) {
5706           delete PropParentMap;
5707           PropParentMap = nullptr;
5708         }
5709         // This synthesizes and inserts the block "impl" struct, invoke function,
5710         // and any copy/dispose helper functions.
5711         InsertBlockLiteralsWithinFunction(FD);
5712         RewriteLineDirective(D);
5713         CurFunctionDef = nullptr;
5714       }
5715       break;
5716     }
5717     case Decl::ObjCMethod: {
5718       ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5719       if (CompoundStmt *Body = MD->getCompoundBody()) {
5720         CurMethodDef = MD;
5721         CurrentBody = Body;
5722         Body =
5723           cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5724         MD->setBody(Body);
5725         CurrentBody = nullptr;
5726         if (PropParentMap) {
5727           delete PropParentMap;
5728           PropParentMap = nullptr;
5729         }
5730         InsertBlockLiteralsWithinMethod(MD);
5731         RewriteLineDirective(D);
5732         CurMethodDef = nullptr;
5733       }
5734       break;
5735     }
5736     case Decl::ObjCImplementation: {
5737       ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5738       ClassImplementation.push_back(CI);
5739       break;
5740     }
5741     case Decl::ObjCCategoryImpl: {
5742       ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5743       CategoryImplementation.push_back(CI);
5744       break;
5745     }
5746     case Decl::Var: {
5747       VarDecl *VD = cast<VarDecl>(D);
5748       RewriteObjCQualifiedInterfaceTypes(VD);
5749       if (isTopLevelBlockPointerType(VD->getType()))
5750         RewriteBlockPointerDecl(VD);
5751       else if (VD->getType()->isFunctionPointerType()) {
5752         CheckFunctionPointerDecl(VD->getType(), VD);
5753         if (VD->getInit()) {
5754           if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5755             RewriteCastExpr(CE);
5756           }
5757         }
5758       } else if (VD->getType()->isRecordType()) {
5759         RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
5760         if (RD->isCompleteDefinition())
5761           RewriteRecordBody(RD);
5762       }
5763       if (VD->getInit()) {
5764         GlobalVarDecl = VD;
5765         CurrentBody = VD->getInit();
5766         RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5767         CurrentBody = nullptr;
5768         if (PropParentMap) {
5769           delete PropParentMap;
5770           PropParentMap = nullptr;
5771         }
5772         SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5773         GlobalVarDecl = nullptr;
5774 
5775         // This is needed for blocks.
5776         if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5777             RewriteCastExpr(CE);
5778         }
5779       }
5780       break;
5781     }
5782     case Decl::TypeAlias:
5783     case Decl::Typedef: {
5784       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5785         if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5786           RewriteBlockPointerDecl(TD);
5787         else if (TD->getUnderlyingType()->isFunctionPointerType())
5788           CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5789         else
5790           RewriteObjCQualifiedInterfaceTypes(TD);
5791       }
5792       break;
5793     }
5794     case Decl::CXXRecord:
5795     case Decl::Record: {
5796       RecordDecl *RD = cast<RecordDecl>(D);
5797       if (RD->isCompleteDefinition())
5798         RewriteRecordBody(RD);
5799       break;
5800     }
5801     default:
5802       break;
5803   }
5804   // Nothing yet.
5805 }
5806 
5807 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5808 /// protocol reference symbols in the for of:
5809 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5810 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5811                                                  ObjCProtocolDecl *PDecl,
5812                                                  std::string &Result) {
5813   // Also output .objc_protorefs$B section and its meta-data.
5814   if (Context->getLangOpts().MicrosoftExt)
5815     Result += "static ";
5816   Result += "struct _protocol_t *";
5817   Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5818   Result += PDecl->getNameAsString();
5819   Result += " = &";
5820   Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5821   Result += ";\n";
5822 }
5823 
5824 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5825   if (Diags.hasErrorOccurred())
5826     return;
5827 
5828   RewriteInclude();
5829 
5830   for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5831     // translation of function bodies were postponed until all class and
5832     // their extensions and implementations are seen. This is because, we
5833     // cannot build grouping structs for bitfields until they are all seen.
5834     FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5835     HandleTopLevelSingleDecl(FDecl);
5836   }
5837 
5838   // Here's a great place to add any extra declarations that may be needed.
5839   // Write out meta data for each @protocol(<expr>).
5840   for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5841     RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5842     Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5843   }
5844 
5845   InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5846 
5847   if (ClassImplementation.size() || CategoryImplementation.size())
5848     RewriteImplementations();
5849 
5850   for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5851     ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5852     // Write struct declaration for the class matching its ivar declarations.
5853     // Note that for modern abi, this is postponed until the end of TU
5854     // because class extensions and the implementation might declare their own
5855     // private ivars.
5856     RewriteInterfaceDecl(CDecl);
5857   }
5858 
5859   // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
5860   // we are done.
5861   if (const RewriteBuffer *RewriteBuf =
5862       Rewrite.getRewriteBufferFor(MainFileID)) {
5863     //printf("Changed:\n");
5864     *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5865   } else {
5866     llvm::errs() << "No changes\n";
5867   }
5868 
5869   if (ClassImplementation.size() || CategoryImplementation.size() ||
5870       ProtocolExprDecls.size()) {
5871     // Rewrite Objective-c meta data*
5872     std::string ResultStr;
5873     RewriteMetaDataIntoBuffer(ResultStr);
5874     // Emit metadata.
5875     *OutFile << ResultStr;
5876   }
5877   // Emit ImageInfo;
5878   {
5879     std::string ResultStr;
5880     WriteImageInfo(ResultStr);
5881     *OutFile << ResultStr;
5882   }
5883   OutFile->flush();
5884 }
5885 
5886 void RewriteModernObjC::Initialize(ASTContext &context) {
5887   InitializeCommon(context);
5888 
5889   Preamble += "#ifndef __OBJC2__\n";
5890   Preamble += "#define __OBJC2__\n";
5891   Preamble += "#endif\n";
5892 
5893   // declaring objc_selector outside the parameter list removes a silly
5894   // scope related warning...
5895   if (IsHeader)
5896     Preamble = "#pragma once\n";
5897   Preamble += "struct objc_selector; struct objc_class;\n";
5898   Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5899   Preamble += "\n\tstruct objc_object *superClass; ";
5900   // Add a constructor for creating temporary objects.
5901   Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5902   Preamble += ": object(o), superClass(s) {} ";
5903   Preamble += "\n};\n";
5904 
5905   if (LangOpts.MicrosoftExt) {
5906     // Define all sections using syntax that makes sense.
5907     // These are currently generated.
5908     Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5909     Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5910     Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5911     Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5912     Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5913     // These are generated but not necessary for functionality.
5914     Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5915     Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5916     Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5917     Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5918 
5919     // These need be generated for performance. Currently they are not,
5920     // using API calls instead.
5921     Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5922     Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5923     Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5924 
5925   }
5926   Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5927   Preamble += "typedef struct objc_object Protocol;\n";
5928   Preamble += "#define _REWRITER_typedef_Protocol\n";
5929   Preamble += "#endif\n";
5930   if (LangOpts.MicrosoftExt) {
5931     Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5932     Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5933   }
5934   else
5935     Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5936 
5937   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5938   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5939   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5940   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5941   Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5942 
5943   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5944   Preamble += "(const char *);\n";
5945   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5946   Preamble += "(struct objc_class *);\n";
5947   Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5948   Preamble += "(const char *);\n";
5949   Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5950   // @synchronized hooks.
5951   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5952   Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5953   Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5954   Preamble += "#ifdef _WIN64\n";
5955   Preamble += "typedef unsigned long long  _WIN_NSUInteger;\n";
5956   Preamble += "#else\n";
5957   Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5958   Preamble += "#endif\n";
5959   Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5960   Preamble += "struct __objcFastEnumerationState {\n\t";
5961   Preamble += "unsigned long state;\n\t";
5962   Preamble += "void **itemsPtr;\n\t";
5963   Preamble += "unsigned long *mutationsPtr;\n\t";
5964   Preamble += "unsigned long extra[5];\n};\n";
5965   Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5966   Preamble += "#define __FASTENUMERATIONSTATE\n";
5967   Preamble += "#endif\n";
5968   Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5969   Preamble += "struct __NSConstantStringImpl {\n";
5970   Preamble += "  int *isa;\n";
5971   Preamble += "  int flags;\n";
5972   Preamble += "  char *str;\n";
5973   Preamble += "#if _WIN64\n";
5974   Preamble += "  long long length;\n";
5975   Preamble += "#else\n";
5976   Preamble += "  long length;\n";
5977   Preamble += "#endif\n";
5978   Preamble += "};\n";
5979   Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5980   Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5981   Preamble += "#else\n";
5982   Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5983   Preamble += "#endif\n";
5984   Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5985   Preamble += "#endif\n";
5986   // Blocks preamble.
5987   Preamble += "#ifndef BLOCK_IMPL\n";
5988   Preamble += "#define BLOCK_IMPL\n";
5989   Preamble += "struct __block_impl {\n";
5990   Preamble += "  void *isa;\n";
5991   Preamble += "  int Flags;\n";
5992   Preamble += "  int Reserved;\n";
5993   Preamble += "  void *FuncPtr;\n";
5994   Preamble += "};\n";
5995   Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5996   Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5997   Preamble += "extern \"C\" __declspec(dllexport) "
5998   "void _Block_object_assign(void *, const void *, const int);\n";
5999   Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6000   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6001   Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6002   Preamble += "#else\n";
6003   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6004   Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6005   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6006   Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6007   Preamble += "#endif\n";
6008   Preamble += "#endif\n";
6009   if (LangOpts.MicrosoftExt) {
6010     Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6011     Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6012     Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
6013     Preamble += "#define __attribute__(X)\n";
6014     Preamble += "#endif\n";
6015     Preamble += "#ifndef __weak\n";
6016     Preamble += "#define __weak\n";
6017     Preamble += "#endif\n";
6018     Preamble += "#ifndef __block\n";
6019     Preamble += "#define __block\n";
6020     Preamble += "#endif\n";
6021   }
6022   else {
6023     Preamble += "#define __block\n";
6024     Preamble += "#define __weak\n";
6025   }
6026 
6027   // Declarations required for modern objective-c array and dictionary literals.
6028   Preamble += "\n#include <stdarg.h>\n";
6029   Preamble += "struct __NSContainer_literal {\n";
6030   Preamble += "  void * *arr;\n";
6031   Preamble += "  __NSContainer_literal (unsigned int count, ...) {\n";
6032   Preamble += "\tva_list marker;\n";
6033   Preamble += "\tva_start(marker, count);\n";
6034   Preamble += "\tarr = new void *[count];\n";
6035   Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6036   Preamble += "\t  arr[i] = va_arg(marker, void *);\n";
6037   Preamble += "\tva_end( marker );\n";
6038   Preamble += "  };\n";
6039   Preamble += "  ~__NSContainer_literal() {\n";
6040   Preamble += "\tdelete[] arr;\n";
6041   Preamble += "  }\n";
6042   Preamble += "};\n";
6043 
6044   // Declaration required for implementation of @autoreleasepool statement.
6045   Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6046   Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6047   Preamble += "struct __AtAutoreleasePool {\n";
6048   Preamble += "  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6049   Preamble += "  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6050   Preamble += "  void * atautoreleasepoolobj;\n";
6051   Preamble += "};\n";
6052 
6053   // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6054   // as this avoids warning in any 64bit/32bit compilation model.
6055   Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6056 }
6057 
6058 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
6059 /// ivar offset.
6060 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6061                                                          std::string &Result) {
6062   Result += "__OFFSETOFIVAR__(struct ";
6063   Result += ivar->getContainingInterface()->getNameAsString();
6064   if (LangOpts.MicrosoftExt)
6065     Result += "_IMPL";
6066   Result += ", ";
6067   if (ivar->isBitField())
6068     ObjCIvarBitfieldGroupDecl(ivar, Result);
6069   else
6070     Result += ivar->getNameAsString();
6071   Result += ")";
6072 }
6073 
6074 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6075 /// struct _prop_t {
6076 ///   const char *name;
6077 ///   char *attributes;
6078 /// }
6079 
6080 /// struct _prop_list_t {
6081 ///   uint32_t entsize;      // sizeof(struct _prop_t)
6082 ///   uint32_t count_of_properties;
6083 ///   struct _prop_t prop_list[count_of_properties];
6084 /// }
6085 
6086 /// struct _protocol_t;
6087 
6088 /// struct _protocol_list_t {
6089 ///   long protocol_count;   // Note, this is 32/64 bit
6090 ///   struct _protocol_t * protocol_list[protocol_count];
6091 /// }
6092 
6093 /// struct _objc_method {
6094 ///   SEL _cmd;
6095 ///   const char *method_type;
6096 ///   char *_imp;
6097 /// }
6098 
6099 /// struct _method_list_t {
6100 ///   uint32_t entsize;  // sizeof(struct _objc_method)
6101 ///   uint32_t method_count;
6102 ///   struct _objc_method method_list[method_count];
6103 /// }
6104 
6105 /// struct _protocol_t {
6106 ///   id isa;  // NULL
6107 ///   const char *protocol_name;
6108 ///   const struct _protocol_list_t * protocol_list; // super protocols
6109 ///   const struct method_list_t *instance_methods;
6110 ///   const struct method_list_t *class_methods;
6111 ///   const struct method_list_t *optionalInstanceMethods;
6112 ///   const struct method_list_t *optionalClassMethods;
6113 ///   const struct _prop_list_t * properties;
6114 ///   const uint32_t size;  // sizeof(struct _protocol_t)
6115 ///   const uint32_t flags;  // = 0
6116 ///   const char ** extendedMethodTypes;
6117 /// }
6118 
6119 /// struct _ivar_t {
6120 ///   unsigned long int *offset;  // pointer to ivar offset location
6121 ///   const char *name;
6122 ///   const char *type;
6123 ///   uint32_t alignment;
6124 ///   uint32_t size;
6125 /// }
6126 
6127 /// struct _ivar_list_t {
6128 ///   uint32 entsize;  // sizeof(struct _ivar_t)
6129 ///   uint32 count;
6130 ///   struct _ivar_t list[count];
6131 /// }
6132 
6133 /// struct _class_ro_t {
6134 ///   uint32_t flags;
6135 ///   uint32_t instanceStart;
6136 ///   uint32_t instanceSize;
6137 ///   uint32_t reserved;  // only when building for 64bit targets
6138 ///   const uint8_t *ivarLayout;
6139 ///   const char *name;
6140 ///   const struct _method_list_t *baseMethods;
6141 ///   const struct _protocol_list_t *baseProtocols;
6142 ///   const struct _ivar_list_t *ivars;
6143 ///   const uint8_t *weakIvarLayout;
6144 ///   const struct _prop_list_t *properties;
6145 /// }
6146 
6147 /// struct _class_t {
6148 ///   struct _class_t *isa;
6149 ///   struct _class_t *superclass;
6150 ///   void *cache;
6151 ///   IMP *vtable;
6152 ///   struct _class_ro_t *ro;
6153 /// }
6154 
6155 /// struct _category_t {
6156 ///   const char *name;
6157 ///   struct _class_t *cls;
6158 ///   const struct _method_list_t *instance_methods;
6159 ///   const struct _method_list_t *class_methods;
6160 ///   const struct _protocol_list_t *protocols;
6161 ///   const struct _prop_list_t *properties;
6162 /// }
6163 
6164 /// MessageRefTy - LLVM for:
6165 /// struct _message_ref_t {
6166 ///   IMP messenger;
6167 ///   SEL name;
6168 /// };
6169 
6170 /// SuperMessageRefTy - LLVM for:
6171 /// struct _super_message_ref_t {
6172 ///   SUPER_IMP messenger;
6173 ///   SEL name;
6174 /// };
6175 
6176 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6177   static bool meta_data_declared = false;
6178   if (meta_data_declared)
6179     return;
6180 
6181   Result += "\nstruct _prop_t {\n";
6182   Result += "\tconst char *name;\n";
6183   Result += "\tconst char *attributes;\n";
6184   Result += "};\n";
6185 
6186   Result += "\nstruct _protocol_t;\n";
6187 
6188   Result += "\nstruct _objc_method {\n";
6189   Result += "\tstruct objc_selector * _cmd;\n";
6190   Result += "\tconst char *method_type;\n";
6191   Result += "\tvoid  *_imp;\n";
6192   Result += "};\n";
6193 
6194   Result += "\nstruct _protocol_t {\n";
6195   Result += "\tvoid * isa;  // NULL\n";
6196   Result += "\tconst char *protocol_name;\n";
6197   Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6198   Result += "\tconst struct method_list_t *instance_methods;\n";
6199   Result += "\tconst struct method_list_t *class_methods;\n";
6200   Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6201   Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6202   Result += "\tconst struct _prop_list_t * properties;\n";
6203   Result += "\tconst unsigned int size;  // sizeof(struct _protocol_t)\n";
6204   Result += "\tconst unsigned int flags;  // = 0\n";
6205   Result += "\tconst char ** extendedMethodTypes;\n";
6206   Result += "};\n";
6207 
6208   Result += "\nstruct _ivar_t {\n";
6209   Result += "\tunsigned long int *offset;  // pointer to ivar offset location\n";
6210   Result += "\tconst char *name;\n";
6211   Result += "\tconst char *type;\n";
6212   Result += "\tunsigned int alignment;\n";
6213   Result += "\tunsigned int  size;\n";
6214   Result += "};\n";
6215 
6216   Result += "\nstruct _class_ro_t {\n";
6217   Result += "\tunsigned int flags;\n";
6218   Result += "\tunsigned int instanceStart;\n";
6219   Result += "\tunsigned int instanceSize;\n";
6220   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6221   if (Triple.getArch() == llvm::Triple::x86_64)
6222     Result += "\tunsigned int reserved;\n";
6223   Result += "\tconst unsigned char *ivarLayout;\n";
6224   Result += "\tconst char *name;\n";
6225   Result += "\tconst struct _method_list_t *baseMethods;\n";
6226   Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6227   Result += "\tconst struct _ivar_list_t *ivars;\n";
6228   Result += "\tconst unsigned char *weakIvarLayout;\n";
6229   Result += "\tconst struct _prop_list_t *properties;\n";
6230   Result += "};\n";
6231 
6232   Result += "\nstruct _class_t {\n";
6233   Result += "\tstruct _class_t *isa;\n";
6234   Result += "\tstruct _class_t *superclass;\n";
6235   Result += "\tvoid *cache;\n";
6236   Result += "\tvoid *vtable;\n";
6237   Result += "\tstruct _class_ro_t *ro;\n";
6238   Result += "};\n";
6239 
6240   Result += "\nstruct _category_t {\n";
6241   Result += "\tconst char *name;\n";
6242   Result += "\tstruct _class_t *cls;\n";
6243   Result += "\tconst struct _method_list_t *instance_methods;\n";
6244   Result += "\tconst struct _method_list_t *class_methods;\n";
6245   Result += "\tconst struct _protocol_list_t *protocols;\n";
6246   Result += "\tconst struct _prop_list_t *properties;\n";
6247   Result += "};\n";
6248 
6249   Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6250   Result += "#pragma warning(disable:4273)\n";
6251   meta_data_declared = true;
6252 }
6253 
6254 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6255                                            long super_protocol_count) {
6256   Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6257   Result += "\tlong protocol_count;  // Note, this is 32/64 bit\n";
6258   Result += "\tstruct _protocol_t *super_protocols[";
6259   Result += utostr(super_protocol_count); Result += "];\n";
6260   Result += "}";
6261 }
6262 
6263 static void Write_method_list_t_TypeDecl(std::string &Result,
6264                                          unsigned int method_count) {
6265   Result += "struct /*_method_list_t*/"; Result += " {\n";
6266   Result += "\tunsigned int entsize;  // sizeof(struct _objc_method)\n";
6267   Result += "\tunsigned int method_count;\n";
6268   Result += "\tstruct _objc_method method_list[";
6269   Result += utostr(method_count); Result += "];\n";
6270   Result += "}";
6271 }
6272 
6273 static void Write__prop_list_t_TypeDecl(std::string &Result,
6274                                         unsigned int property_count) {
6275   Result += "struct /*_prop_list_t*/"; Result += " {\n";
6276   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6277   Result += "\tunsigned int count_of_properties;\n";
6278   Result += "\tstruct _prop_t prop_list[";
6279   Result += utostr(property_count); Result += "];\n";
6280   Result += "}";
6281 }
6282 
6283 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6284                                         unsigned int ivar_count) {
6285   Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6286   Result += "\tunsigned int entsize;  // sizeof(struct _prop_t)\n";
6287   Result += "\tunsigned int count;\n";
6288   Result += "\tstruct _ivar_t ivar_list[";
6289   Result += utostr(ivar_count); Result += "];\n";
6290   Result += "}";
6291 }
6292 
6293 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6294                                             ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6295                                             StringRef VarName,
6296                                             StringRef ProtocolName) {
6297   if (SuperProtocols.size() > 0) {
6298     Result += "\nstatic ";
6299     Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6300     Result += " "; Result += VarName;
6301     Result += ProtocolName;
6302     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6303     Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6304     for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6305       ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6306       Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6307       Result += SuperPD->getNameAsString();
6308       if (i == e-1)
6309         Result += "\n};\n";
6310       else
6311         Result += ",\n";
6312     }
6313   }
6314 }
6315 
6316 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6317                                             ASTContext *Context, std::string &Result,
6318                                             ArrayRef<ObjCMethodDecl *> Methods,
6319                                             StringRef VarName,
6320                                             StringRef TopLevelDeclName,
6321                                             bool MethodImpl) {
6322   if (Methods.size() > 0) {
6323     Result += "\nstatic ";
6324     Write_method_list_t_TypeDecl(Result, Methods.size());
6325     Result += " "; Result += VarName;
6326     Result += TopLevelDeclName;
6327     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6328     Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6329     Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6330     for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6331       ObjCMethodDecl *MD = Methods[i];
6332       if (i == 0)
6333         Result += "\t{{(struct objc_selector *)\"";
6334       else
6335         Result += "\t{(struct objc_selector *)\"";
6336       Result += (MD)->getSelector().getAsString(); Result += "\"";
6337       Result += ", ";
6338       std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6339       Result += "\""; Result += MethodTypeString; Result += "\"";
6340       Result += ", ";
6341       if (!MethodImpl)
6342         Result += "0";
6343       else {
6344         Result += "(void *)";
6345         Result += RewriteObj.MethodInternalNames[MD];
6346       }
6347       if (i  == e-1)
6348         Result += "}}\n";
6349       else
6350         Result += "},\n";
6351     }
6352     Result += "};\n";
6353   }
6354 }
6355 
6356 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6357                                            ASTContext *Context, std::string &Result,
6358                                            ArrayRef<ObjCPropertyDecl *> Properties,
6359                                            const Decl *Container,
6360                                            StringRef VarName,
6361                                            StringRef ProtocolName) {
6362   if (Properties.size() > 0) {
6363     Result += "\nstatic ";
6364     Write__prop_list_t_TypeDecl(Result, Properties.size());
6365     Result += " "; Result += VarName;
6366     Result += ProtocolName;
6367     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6368     Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6369     Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6370     for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6371       ObjCPropertyDecl *PropDecl = Properties[i];
6372       if (i == 0)
6373         Result += "\t{{\"";
6374       else
6375         Result += "\t{\"";
6376       Result += PropDecl->getName(); Result += "\",";
6377       std::string PropertyTypeString =
6378         Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6379       std::string QuotePropertyTypeString;
6380       RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6381       Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6382       if (i  == e-1)
6383         Result += "}}\n";
6384       else
6385         Result += "},\n";
6386     }
6387     Result += "};\n";
6388   }
6389 }
6390 
6391 // Metadata flags
6392 enum MetaDataDlags {
6393   CLS = 0x0,
6394   CLS_META = 0x1,
6395   CLS_ROOT = 0x2,
6396   OBJC2_CLS_HIDDEN = 0x10,
6397   CLS_EXCEPTION = 0x20,
6398 
6399   /// (Obsolete) ARC-specific: this class has a .release_ivars method
6400   CLS_HAS_IVAR_RELEASER = 0x40,
6401   /// class was compiled with -fobjc-arr
6402   CLS_COMPILED_BY_ARC = 0x80  // (1<<7)
6403 };
6404 
6405 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6406                                           unsigned int flags,
6407                                           const std::string &InstanceStart,
6408                                           const std::string &InstanceSize,
6409                                           ArrayRef<ObjCMethodDecl *>baseMethods,
6410                                           ArrayRef<ObjCProtocolDecl *>baseProtocols,
6411                                           ArrayRef<ObjCIvarDecl *>ivars,
6412                                           ArrayRef<ObjCPropertyDecl *>Properties,
6413                                           StringRef VarName,
6414                                           StringRef ClassName) {
6415   Result += "\nstatic struct _class_ro_t ";
6416   Result += VarName; Result += ClassName;
6417   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6418   Result += "\t";
6419   Result += llvm::utostr(flags); Result += ", ";
6420   Result += InstanceStart; Result += ", ";
6421   Result += InstanceSize; Result += ", \n";
6422   Result += "\t";
6423   const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6424   if (Triple.getArch() == llvm::Triple::x86_64)
6425     // uint32_t const reserved; // only when building for 64bit targets
6426     Result += "(unsigned int)0, \n\t";
6427   // const uint8_t * const ivarLayout;
6428   Result += "0, \n\t";
6429   Result += "\""; Result += ClassName; Result += "\",\n\t";
6430   bool metaclass = ((flags & CLS_META) != 0);
6431   if (baseMethods.size() > 0) {
6432     Result += "(const struct _method_list_t *)&";
6433     if (metaclass)
6434       Result += "_OBJC_$_CLASS_METHODS_";
6435     else
6436       Result += "_OBJC_$_INSTANCE_METHODS_";
6437     Result += ClassName;
6438     Result += ",\n\t";
6439   }
6440   else
6441     Result += "0, \n\t";
6442 
6443   if (!metaclass && baseProtocols.size() > 0) {
6444     Result += "(const struct _objc_protocol_list *)&";
6445     Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6446     Result += ",\n\t";
6447   }
6448   else
6449     Result += "0, \n\t";
6450 
6451   if (!metaclass && ivars.size() > 0) {
6452     Result += "(const struct _ivar_list_t *)&";
6453     Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6454     Result += ",\n\t";
6455   }
6456   else
6457     Result += "0, \n\t";
6458 
6459   // weakIvarLayout
6460   Result += "0, \n\t";
6461   if (!metaclass && Properties.size() > 0) {
6462     Result += "(const struct _prop_list_t *)&";
6463     Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6464     Result += ",\n";
6465   }
6466   else
6467     Result += "0, \n";
6468 
6469   Result += "};\n";
6470 }
6471 
6472 static void Write_class_t(ASTContext *Context, std::string &Result,
6473                           StringRef VarName,
6474                           const ObjCInterfaceDecl *CDecl, bool metaclass) {
6475   bool rootClass = (!CDecl->getSuperClass());
6476   const ObjCInterfaceDecl *RootClass = CDecl;
6477 
6478   if (!rootClass) {
6479     // Find the Root class
6480     RootClass = CDecl->getSuperClass();
6481     while (RootClass->getSuperClass()) {
6482       RootClass = RootClass->getSuperClass();
6483     }
6484   }
6485 
6486   if (metaclass && rootClass) {
6487     // Need to handle a case of use of forward declaration.
6488     Result += "\n";
6489     Result += "extern \"C\" ";
6490     if (CDecl->getImplementation())
6491       Result += "__declspec(dllexport) ";
6492     else
6493       Result += "__declspec(dllimport) ";
6494 
6495     Result += "struct _class_t OBJC_CLASS_$_";
6496     Result += CDecl->getNameAsString();
6497     Result += ";\n";
6498   }
6499   // Also, for possibility of 'super' metadata class not having been defined yet.
6500   if (!rootClass) {
6501     ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6502     Result += "\n";
6503     Result += "extern \"C\" ";
6504     if (SuperClass->getImplementation())
6505       Result += "__declspec(dllexport) ";
6506     else
6507       Result += "__declspec(dllimport) ";
6508 
6509     Result += "struct _class_t ";
6510     Result += VarName;
6511     Result += SuperClass->getNameAsString();
6512     Result += ";\n";
6513 
6514     if (metaclass && RootClass != SuperClass) {
6515       Result += "extern \"C\" ";
6516       if (RootClass->getImplementation())
6517         Result += "__declspec(dllexport) ";
6518       else
6519         Result += "__declspec(dllimport) ";
6520 
6521       Result += "struct _class_t ";
6522       Result += VarName;
6523       Result += RootClass->getNameAsString();
6524       Result += ";\n";
6525     }
6526   }
6527 
6528   Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6529   Result += VarName; Result += CDecl->getNameAsString();
6530   Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6531   Result += "\t";
6532   if (metaclass) {
6533     if (!rootClass) {
6534       Result += "0, // &"; Result += VarName;
6535       Result += RootClass->getNameAsString();
6536       Result += ",\n\t";
6537       Result += "0, // &"; Result += VarName;
6538       Result += CDecl->getSuperClass()->getNameAsString();
6539       Result += ",\n\t";
6540     }
6541     else {
6542       Result += "0, // &"; Result += VarName;
6543       Result += CDecl->getNameAsString();
6544       Result += ",\n\t";
6545       Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6546       Result += ",\n\t";
6547     }
6548   }
6549   else {
6550     Result += "0, // &OBJC_METACLASS_$_";
6551     Result += CDecl->getNameAsString();
6552     Result += ",\n\t";
6553     if (!rootClass) {
6554       Result += "0, // &"; Result += VarName;
6555       Result += CDecl->getSuperClass()->getNameAsString();
6556       Result += ",\n\t";
6557     }
6558     else
6559       Result += "0,\n\t";
6560   }
6561   Result += "0, // (void *)&_objc_empty_cache,\n\t";
6562   Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6563   if (metaclass)
6564     Result += "&_OBJC_METACLASS_RO_$_";
6565   else
6566     Result += "&_OBJC_CLASS_RO_$_";
6567   Result += CDecl->getNameAsString();
6568   Result += ",\n};\n";
6569 
6570   // Add static function to initialize some of the meta-data fields.
6571   // avoid doing it twice.
6572   if (metaclass)
6573     return;
6574 
6575   const ObjCInterfaceDecl *SuperClass =
6576     rootClass ? CDecl : CDecl->getSuperClass();
6577 
6578   Result += "static void OBJC_CLASS_SETUP_$_";
6579   Result += CDecl->getNameAsString();
6580   Result += "(void ) {\n";
6581   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6582   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6583   Result += RootClass->getNameAsString(); Result += ";\n";
6584 
6585   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6586   Result += ".superclass = ";
6587   if (rootClass)
6588     Result += "&OBJC_CLASS_$_";
6589   else
6590      Result += "&OBJC_METACLASS_$_";
6591 
6592   Result += SuperClass->getNameAsString(); Result += ";\n";
6593 
6594   Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6595   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6596 
6597   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6598   Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6599   Result += CDecl->getNameAsString(); Result += ";\n";
6600 
6601   if (!rootClass) {
6602     Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6603     Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6604     Result += SuperClass->getNameAsString(); Result += ";\n";
6605   }
6606 
6607   Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6608   Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6609   Result += "}\n";
6610 }
6611 
6612 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6613                              std::string &Result,
6614                              ObjCCategoryDecl *CatDecl,
6615                              ObjCInterfaceDecl *ClassDecl,
6616                              ArrayRef<ObjCMethodDecl *> InstanceMethods,
6617                              ArrayRef<ObjCMethodDecl *> ClassMethods,
6618                              ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6619                              ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6620   StringRef CatName = CatDecl->getName();
6621   StringRef ClassName = ClassDecl->getName();
6622   // must declare an extern class object in case this class is not implemented
6623   // in this TU.
6624   Result += "\n";
6625   Result += "extern \"C\" ";
6626   if (ClassDecl->getImplementation())
6627     Result += "__declspec(dllexport) ";
6628   else
6629     Result += "__declspec(dllimport) ";
6630 
6631   Result += "struct _class_t ";
6632   Result += "OBJC_CLASS_$_"; Result += ClassName;
6633   Result += ";\n";
6634 
6635   Result += "\nstatic struct _category_t ";
6636   Result += "_OBJC_$_CATEGORY_";
6637   Result += ClassName; Result += "_$_"; Result += CatName;
6638   Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6639   Result += "{\n";
6640   Result += "\t\""; Result += ClassName; Result += "\",\n";
6641   Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6642   Result += ",\n";
6643   if (InstanceMethods.size() > 0) {
6644     Result += "\t(const struct _method_list_t *)&";
6645     Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6646     Result += ClassName; Result += "_$_"; Result += CatName;
6647     Result += ",\n";
6648   }
6649   else
6650     Result += "\t0,\n";
6651 
6652   if (ClassMethods.size() > 0) {
6653     Result += "\t(const struct _method_list_t *)&";
6654     Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6655     Result += ClassName; Result += "_$_"; Result += CatName;
6656     Result += ",\n";
6657   }
6658   else
6659     Result += "\t0,\n";
6660 
6661   if (RefedProtocols.size() > 0) {
6662     Result += "\t(const struct _protocol_list_t *)&";
6663     Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6664     Result += ClassName; Result += "_$_"; Result += CatName;
6665     Result += ",\n";
6666   }
6667   else
6668     Result += "\t0,\n";
6669 
6670   if (ClassProperties.size() > 0) {
6671     Result += "\t(const struct _prop_list_t *)&";  Result += "_OBJC_$_PROP_LIST_";
6672     Result += ClassName; Result += "_$_"; Result += CatName;
6673     Result += ",\n";
6674   }
6675   else
6676     Result += "\t0,\n";
6677 
6678   Result += "};\n";
6679 
6680   // Add static function to initialize the class pointer in the category structure.
6681   Result += "static void OBJC_CATEGORY_SETUP_$_";
6682   Result += ClassDecl->getNameAsString();
6683   Result += "_$_";
6684   Result += CatName;
6685   Result += "(void ) {\n";
6686   Result += "\t_OBJC_$_CATEGORY_";
6687   Result += ClassDecl->getNameAsString();
6688   Result += "_$_";
6689   Result += CatName;
6690   Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6691   Result += ";\n}\n";
6692 }
6693 
6694 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6695                                            ASTContext *Context, std::string &Result,
6696                                            ArrayRef<ObjCMethodDecl *> Methods,
6697                                            StringRef VarName,
6698                                            StringRef ProtocolName) {
6699   if (Methods.size() == 0)
6700     return;
6701 
6702   Result += "\nstatic const char *";
6703   Result += VarName; Result += ProtocolName;
6704   Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6705   Result += "{\n";
6706   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6707     ObjCMethodDecl *MD = Methods[i];
6708     std::string MethodTypeString =
6709       Context->getObjCEncodingForMethodDecl(MD, true);
6710     std::string QuoteMethodTypeString;
6711     RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6712     Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6713     if (i == e-1)
6714       Result += "\n};\n";
6715     else {
6716       Result += ",\n";
6717     }
6718   }
6719 }
6720 
6721 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6722                                 ASTContext *Context,
6723                                 std::string &Result,
6724                                 ArrayRef<ObjCIvarDecl *> Ivars,
6725                                 ObjCInterfaceDecl *CDecl) {
6726   // FIXME. visibilty of offset symbols may have to be set; for Darwin
6727   // this is what happens:
6728   /**
6729    if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6730        Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6731        Class->getVisibility() == HiddenVisibility)
6732      Visibility should be: HiddenVisibility;
6733    else
6734      Visibility should be: DefaultVisibility;
6735   */
6736 
6737   Result += "\n";
6738   for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6739     ObjCIvarDecl *IvarDecl = Ivars[i];
6740     if (Context->getLangOpts().MicrosoftExt)
6741       Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6742 
6743     if (!Context->getLangOpts().MicrosoftExt ||
6744         IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6745         IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6746       Result += "extern \"C\" unsigned long int ";
6747     else
6748       Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6749     if (Ivars[i]->isBitField())
6750       RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6751     else
6752       WriteInternalIvarName(CDecl, IvarDecl, Result);
6753     Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6754     Result += " = ";
6755     RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6756     Result += ";\n";
6757     if (Ivars[i]->isBitField()) {
6758       // skip over rest of the ivar bitfields.
6759       SKIP_BITFIELDS(i , e, Ivars);
6760     }
6761   }
6762 }
6763 
6764 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6765                                            ASTContext *Context, std::string &Result,
6766                                            ArrayRef<ObjCIvarDecl *> OriginalIvars,
6767                                            StringRef VarName,
6768                                            ObjCInterfaceDecl *CDecl) {
6769   if (OriginalIvars.size() > 0) {
6770     Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6771     SmallVector<ObjCIvarDecl *, 8> Ivars;
6772     // strip off all but the first ivar bitfield from each group of ivars.
6773     // Such ivars in the ivar list table will be replaced by their grouping struct
6774     // 'ivar'.
6775     for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6776       if (OriginalIvars[i]->isBitField()) {
6777         Ivars.push_back(OriginalIvars[i]);
6778         // skip over rest of the ivar bitfields.
6779         SKIP_BITFIELDS(i , e, OriginalIvars);
6780       }
6781       else
6782         Ivars.push_back(OriginalIvars[i]);
6783     }
6784 
6785     Result += "\nstatic ";
6786     Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6787     Result += " "; Result += VarName;
6788     Result += CDecl->getNameAsString();
6789     Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6790     Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6791     Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6792     for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6793       ObjCIvarDecl *IvarDecl = Ivars[i];
6794       if (i == 0)
6795         Result += "\t{{";
6796       else
6797         Result += "\t {";
6798       Result += "(unsigned long int *)&";
6799       if (Ivars[i]->isBitField())
6800         RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6801       else
6802         WriteInternalIvarName(CDecl, IvarDecl, Result);
6803       Result += ", ";
6804 
6805       Result += "\"";
6806       if (Ivars[i]->isBitField())
6807         RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6808       else
6809         Result += IvarDecl->getName();
6810       Result += "\", ";
6811 
6812       QualType IVQT = IvarDecl->getType();
6813       if (IvarDecl->isBitField())
6814         IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6815 
6816       std::string IvarTypeString, QuoteIvarTypeString;
6817       Context->getObjCEncodingForType(IVQT, IvarTypeString,
6818                                       IvarDecl);
6819       RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6820       Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6821 
6822       // FIXME. this alignment represents the host alignment and need be changed to
6823       // represent the target alignment.
6824       unsigned Align = Context->getTypeAlign(IVQT)/8;
6825       Align = llvm::Log2_32(Align);
6826       Result += llvm::utostr(Align); Result += ", ";
6827       CharUnits Size = Context->getTypeSizeInChars(IVQT);
6828       Result += llvm::utostr(Size.getQuantity());
6829       if (i  == e-1)
6830         Result += "}}\n";
6831       else
6832         Result += "},\n";
6833     }
6834     Result += "};\n";
6835   }
6836 }
6837 
6838 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6839 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6840                                                     std::string &Result) {
6841 
6842   // Do not synthesize the protocol more than once.
6843   if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6844     return;
6845   WriteModernMetadataDeclarations(Context, Result);
6846 
6847   if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6848     PDecl = Def;
6849   // Must write out all protocol definitions in current qualifier list,
6850   // and in their nested qualifiers before writing out current definition.
6851   for (auto *I : PDecl->protocols())
6852     RewriteObjCProtocolMetaData(I, Result);
6853 
6854   // Construct method lists.
6855   std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6856   std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6857   for (auto *MD : PDecl->instance_methods()) {
6858     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6859       OptInstanceMethods.push_back(MD);
6860     } else {
6861       InstanceMethods.push_back(MD);
6862     }
6863   }
6864 
6865   for (auto *MD : PDecl->class_methods()) {
6866     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6867       OptClassMethods.push_back(MD);
6868     } else {
6869       ClassMethods.push_back(MD);
6870     }
6871   }
6872   std::vector<ObjCMethodDecl *> AllMethods;
6873   for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6874     AllMethods.push_back(InstanceMethods[i]);
6875   for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6876     AllMethods.push_back(ClassMethods[i]);
6877   for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6878     AllMethods.push_back(OptInstanceMethods[i]);
6879   for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6880     AllMethods.push_back(OptClassMethods[i]);
6881 
6882   Write__extendedMethodTypes_initializer(*this, Context, Result,
6883                                          AllMethods,
6884                                          "_OBJC_PROTOCOL_METHOD_TYPES_",
6885                                          PDecl->getNameAsString());
6886   // Protocol's super protocol list
6887   SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6888   Write_protocol_list_initializer(Context, Result, SuperProtocols,
6889                                   "_OBJC_PROTOCOL_REFS_",
6890                                   PDecl->getNameAsString());
6891 
6892   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6893                                   "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6894                                   PDecl->getNameAsString(), false);
6895 
6896   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6897                                   "_OBJC_PROTOCOL_CLASS_METHODS_",
6898                                   PDecl->getNameAsString(), false);
6899 
6900   Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6901                                   "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6902                                   PDecl->getNameAsString(), false);
6903 
6904   Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6905                                   "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6906                                   PDecl->getNameAsString(), false);
6907 
6908   // Protocol's property metadata.
6909   SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6910       PDecl->instance_properties());
6911   Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6912                                  /* Container */nullptr,
6913                                  "_OBJC_PROTOCOL_PROPERTIES_",
6914                                  PDecl->getNameAsString());
6915 
6916   // Writer out root metadata for current protocol: struct _protocol_t
6917   Result += "\n";
6918   if (LangOpts.MicrosoftExt)
6919     Result += "static ";
6920   Result += "struct _protocol_t _OBJC_PROTOCOL_";
6921   Result += PDecl->getNameAsString();
6922   Result += " __attribute__ ((used)) = {\n";
6923   Result += "\t0,\n"; // id is; is null
6924   Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6925   if (SuperProtocols.size() > 0) {
6926     Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6927     Result += PDecl->getNameAsString(); Result += ",\n";
6928   }
6929   else
6930     Result += "\t0,\n";
6931   if (InstanceMethods.size() > 0) {
6932     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6933     Result += PDecl->getNameAsString(); Result += ",\n";
6934   }
6935   else
6936     Result += "\t0,\n";
6937 
6938   if (ClassMethods.size() > 0) {
6939     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6940     Result += PDecl->getNameAsString(); Result += ",\n";
6941   }
6942   else
6943     Result += "\t0,\n";
6944 
6945   if (OptInstanceMethods.size() > 0) {
6946     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6947     Result += PDecl->getNameAsString(); Result += ",\n";
6948   }
6949   else
6950     Result += "\t0,\n";
6951 
6952   if (OptClassMethods.size() > 0) {
6953     Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6954     Result += PDecl->getNameAsString(); Result += ",\n";
6955   }
6956   else
6957     Result += "\t0,\n";
6958 
6959   if (ProtocolProperties.size() > 0) {
6960     Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6961     Result += PDecl->getNameAsString(); Result += ",\n";
6962   }
6963   else
6964     Result += "\t0,\n";
6965 
6966   Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6967   Result += "\t0,\n";
6968 
6969   if (AllMethods.size() > 0) {
6970     Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6971     Result += PDecl->getNameAsString();
6972     Result += "\n};\n";
6973   }
6974   else
6975     Result += "\t0\n};\n";
6976 
6977   if (LangOpts.MicrosoftExt)
6978     Result += "static ";
6979   Result += "struct _protocol_t *";
6980   Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6981   Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6982   Result += ";\n";
6983 
6984   // Mark this protocol as having been generated.
6985   if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6986     llvm_unreachable("protocol already synthesized");
6987 }
6988 
6989 /// hasObjCExceptionAttribute - Return true if this class or any super
6990 /// class has the __objc_exception__ attribute.
6991 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6992 static bool hasObjCExceptionAttribute(ASTContext &Context,
6993                                       const ObjCInterfaceDecl *OID) {
6994   if (OID->hasAttr<ObjCExceptionAttr>())
6995     return true;
6996   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6997     return hasObjCExceptionAttribute(Context, Super);
6998   return false;
6999 }
7000 
7001 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7002                                            std::string &Result) {
7003   ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7004 
7005   // Explicitly declared @interface's are already synthesized.
7006   if (CDecl->isImplicitInterfaceDecl())
7007     assert(false &&
7008            "Legacy implicit interface rewriting not supported in moder abi");
7009 
7010   WriteModernMetadataDeclarations(Context, Result);
7011   SmallVector<ObjCIvarDecl *, 8> IVars;
7012 
7013   for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7014       IVD; IVD = IVD->getNextIvar()) {
7015     // Ignore unnamed bit-fields.
7016     if (!IVD->getDeclName())
7017       continue;
7018     IVars.push_back(IVD);
7019   }
7020 
7021   Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7022                                  "_OBJC_$_INSTANCE_VARIABLES_",
7023                                  CDecl);
7024 
7025   // Build _objc_method_list for class's instance methods if needed
7026   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7027 
7028   // If any of our property implementations have associated getters or
7029   // setters, produce metadata for them as well.
7030   for (const auto *Prop : IDecl->property_impls()) {
7031     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7032       continue;
7033     if (!Prop->getPropertyIvarDecl())
7034       continue;
7035     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7036     if (!PD)
7037       continue;
7038     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7039       if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7040         InstanceMethods.push_back(Getter);
7041     if (PD->isReadOnly())
7042       continue;
7043     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7044       if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7045         InstanceMethods.push_back(Setter);
7046   }
7047 
7048   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7049                                   "_OBJC_$_INSTANCE_METHODS_",
7050                                   IDecl->getNameAsString(), true);
7051 
7052   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7053 
7054   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7055                                   "_OBJC_$_CLASS_METHODS_",
7056                                   IDecl->getNameAsString(), true);
7057 
7058   // Protocols referenced in class declaration?
7059   // Protocol's super protocol list
7060   std::vector<ObjCProtocolDecl *> RefedProtocols;
7061   const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7062   for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7063        E = Protocols.end();
7064        I != E; ++I) {
7065     RefedProtocols.push_back(*I);
7066     // Must write out all protocol definitions in current qualifier list,
7067     // and in their nested qualifiers before writing out current definition.
7068     RewriteObjCProtocolMetaData(*I, Result);
7069   }
7070 
7071   Write_protocol_list_initializer(Context, Result,
7072                                   RefedProtocols,
7073                                   "_OBJC_CLASS_PROTOCOLS_$_",
7074                                   IDecl->getNameAsString());
7075 
7076   // Protocol's property metadata.
7077   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7078       CDecl->instance_properties());
7079   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7080                                  /* Container */IDecl,
7081                                  "_OBJC_$_PROP_LIST_",
7082                                  CDecl->getNameAsString());
7083 
7084   // Data for initializing _class_ro_t  metaclass meta-data
7085   uint32_t flags = CLS_META;
7086   std::string InstanceSize;
7087   std::string InstanceStart;
7088 
7089   bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7090   if (classIsHidden)
7091     flags |= OBJC2_CLS_HIDDEN;
7092 
7093   if (!CDecl->getSuperClass())
7094     // class is root
7095     flags |= CLS_ROOT;
7096   InstanceSize = "sizeof(struct _class_t)";
7097   InstanceStart = InstanceSize;
7098   Write__class_ro_t_initializer(Context, Result, flags,
7099                                 InstanceStart, InstanceSize,
7100                                 ClassMethods,
7101                                 nullptr,
7102                                 nullptr,
7103                                 nullptr,
7104                                 "_OBJC_METACLASS_RO_$_",
7105                                 CDecl->getNameAsString());
7106 
7107   // Data for initializing _class_ro_t meta-data
7108   flags = CLS;
7109   if (classIsHidden)
7110     flags |= OBJC2_CLS_HIDDEN;
7111 
7112   if (hasObjCExceptionAttribute(*Context, CDecl))
7113     flags |= CLS_EXCEPTION;
7114 
7115   if (!CDecl->getSuperClass())
7116     // class is root
7117     flags |= CLS_ROOT;
7118 
7119   InstanceSize.clear();
7120   InstanceStart.clear();
7121   if (!ObjCSynthesizedStructs.count(CDecl)) {
7122     InstanceSize = "0";
7123     InstanceStart = "0";
7124   }
7125   else {
7126     InstanceSize = "sizeof(struct ";
7127     InstanceSize += CDecl->getNameAsString();
7128     InstanceSize += "_IMPL)";
7129 
7130     ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7131     if (IVD) {
7132       RewriteIvarOffsetComputation(IVD, InstanceStart);
7133     }
7134     else
7135       InstanceStart = InstanceSize;
7136   }
7137   Write__class_ro_t_initializer(Context, Result, flags,
7138                                 InstanceStart, InstanceSize,
7139                                 InstanceMethods,
7140                                 RefedProtocols,
7141                                 IVars,
7142                                 ClassProperties,
7143                                 "_OBJC_CLASS_RO_$_",
7144                                 CDecl->getNameAsString());
7145 
7146   Write_class_t(Context, Result,
7147                 "OBJC_METACLASS_$_",
7148                 CDecl, /*metaclass*/true);
7149 
7150   Write_class_t(Context, Result,
7151                 "OBJC_CLASS_$_",
7152                 CDecl, /*metaclass*/false);
7153 
7154   if (ImplementationIsNonLazy(IDecl))
7155     DefinedNonLazyClasses.push_back(CDecl);
7156 }
7157 
7158 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7159   int ClsDefCount = ClassImplementation.size();
7160   if (!ClsDefCount)
7161     return;
7162   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7163   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7164   Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7165   for (int i = 0; i < ClsDefCount; i++) {
7166     ObjCImplementationDecl *IDecl = ClassImplementation[i];
7167     ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7168     Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7169     Result  += CDecl->getName(); Result += ",\n";
7170   }
7171   Result += "};\n";
7172 }
7173 
7174 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7175   int ClsDefCount = ClassImplementation.size();
7176   int CatDefCount = CategoryImplementation.size();
7177 
7178   // For each implemented class, write out all its meta data.
7179   for (int i = 0; i < ClsDefCount; i++)
7180     RewriteObjCClassMetaData(ClassImplementation[i], Result);
7181 
7182   RewriteClassSetupInitHook(Result);
7183 
7184   // For each implemented category, write out all its meta data.
7185   for (int i = 0; i < CatDefCount; i++)
7186     RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7187 
7188   RewriteCategorySetupInitHook(Result);
7189 
7190   if (ClsDefCount > 0) {
7191     if (LangOpts.MicrosoftExt)
7192       Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7193     Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7194     Result += llvm::utostr(ClsDefCount); Result += "]";
7195     Result +=
7196       " __attribute__((used, section (\"__DATA, __objc_classlist,"
7197       "regular,no_dead_strip\")))= {\n";
7198     for (int i = 0; i < ClsDefCount; i++) {
7199       Result += "\t&OBJC_CLASS_$_";
7200       Result += ClassImplementation[i]->getNameAsString();
7201       Result += ",\n";
7202     }
7203     Result += "};\n";
7204 
7205     if (!DefinedNonLazyClasses.empty()) {
7206       if (LangOpts.MicrosoftExt)
7207         Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7208       Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7209       for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7210         Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7211         Result += ",\n";
7212       }
7213       Result += "};\n";
7214     }
7215   }
7216 
7217   if (CatDefCount > 0) {
7218     if (LangOpts.MicrosoftExt)
7219       Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7220     Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7221     Result += llvm::utostr(CatDefCount); Result += "]";
7222     Result +=
7223     " __attribute__((used, section (\"__DATA, __objc_catlist,"
7224     "regular,no_dead_strip\")))= {\n";
7225     for (int i = 0; i < CatDefCount; i++) {
7226       Result += "\t&_OBJC_$_CATEGORY_";
7227       Result +=
7228         CategoryImplementation[i]->getClassInterface()->getNameAsString();
7229       Result += "_$_";
7230       Result += CategoryImplementation[i]->getNameAsString();
7231       Result += ",\n";
7232     }
7233     Result += "};\n";
7234   }
7235 
7236   if (!DefinedNonLazyCategories.empty()) {
7237     if (LangOpts.MicrosoftExt)
7238       Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7239     Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7240     for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7241       Result += "\t&_OBJC_$_CATEGORY_";
7242       Result +=
7243         DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7244       Result += "_$_";
7245       Result += DefinedNonLazyCategories[i]->getNameAsString();
7246       Result += ",\n";
7247     }
7248     Result += "};\n";
7249   }
7250 }
7251 
7252 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7253   if (LangOpts.MicrosoftExt)
7254     Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7255 
7256   Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7257   // version 0, ObjCABI is 2
7258   Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7259 }
7260 
7261 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7262 /// implementation.
7263 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7264                                               std::string &Result) {
7265   WriteModernMetadataDeclarations(Context, Result);
7266   ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7267   // Find category declaration for this implementation.
7268   ObjCCategoryDecl *CDecl
7269     = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7270 
7271   std::string FullCategoryName = ClassDecl->getNameAsString();
7272   FullCategoryName += "_$_";
7273   FullCategoryName += CDecl->getNameAsString();
7274 
7275   // Build _objc_method_list for class's instance methods if needed
7276   SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7277 
7278   // If any of our property implementations have associated getters or
7279   // setters, produce metadata for them as well.
7280   for (const auto *Prop : IDecl->property_impls()) {
7281     if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7282       continue;
7283     if (!Prop->getPropertyIvarDecl())
7284       continue;
7285     ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7286     if (!PD)
7287       continue;
7288     if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
7289       InstanceMethods.push_back(Getter);
7290     if (PD->isReadOnly())
7291       continue;
7292     if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
7293       InstanceMethods.push_back(Setter);
7294   }
7295 
7296   Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7297                                   "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7298                                   FullCategoryName, true);
7299 
7300   SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7301 
7302   Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7303                                   "_OBJC_$_CATEGORY_CLASS_METHODS_",
7304                                   FullCategoryName, true);
7305 
7306   // Protocols referenced in class declaration?
7307   // Protocol's super protocol list
7308   SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7309   for (auto *I : CDecl->protocols())
7310     // Must write out all protocol definitions in current qualifier list,
7311     // and in their nested qualifiers before writing out current definition.
7312     RewriteObjCProtocolMetaData(I, Result);
7313 
7314   Write_protocol_list_initializer(Context, Result,
7315                                   RefedProtocols,
7316                                   "_OBJC_CATEGORY_PROTOCOLS_$_",
7317                                   FullCategoryName);
7318 
7319   // Protocol's property metadata.
7320   SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7321       CDecl->instance_properties());
7322   Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7323                                 /* Container */IDecl,
7324                                 "_OBJC_$_PROP_LIST_",
7325                                 FullCategoryName);
7326 
7327   Write_category_t(*this, Context, Result,
7328                    CDecl,
7329                    ClassDecl,
7330                    InstanceMethods,
7331                    ClassMethods,
7332                    RefedProtocols,
7333                    ClassProperties);
7334 
7335   // Determine if this category is also "non-lazy".
7336   if (ImplementationIsNonLazy(IDecl))
7337     DefinedNonLazyCategories.push_back(CDecl);
7338 }
7339 
7340 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7341   int CatDefCount = CategoryImplementation.size();
7342   if (!CatDefCount)
7343     return;
7344   Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7345   Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7346   Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7347   for (int i = 0; i < CatDefCount; i++) {
7348     ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7349     ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7350     ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7351     Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7352     Result += ClassDecl->getName();
7353     Result += "_$_";
7354     Result += CatDecl->getName();
7355     Result += ",\n";
7356   }
7357   Result += "};\n";
7358 }
7359 
7360 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7361 /// class methods.
7362 template<typename MethodIterator>
7363 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7364                                              MethodIterator MethodEnd,
7365                                              bool IsInstanceMethod,
7366                                              StringRef prefix,
7367                                              StringRef ClassName,
7368                                              std::string &Result) {
7369   if (MethodBegin == MethodEnd) return;
7370 
7371   if (!objc_impl_method) {
7372     /* struct _objc_method {
7373      SEL _cmd;
7374      char *method_types;
7375      void *_imp;
7376      }
7377      */
7378     Result += "\nstruct _objc_method {\n";
7379     Result += "\tSEL _cmd;\n";
7380     Result += "\tchar *method_types;\n";
7381     Result += "\tvoid *_imp;\n";
7382     Result += "};\n";
7383 
7384     objc_impl_method = true;
7385   }
7386 
7387   // Build _objc_method_list for class's methods if needed
7388 
7389   /* struct  {
7390    struct _objc_method_list *next_method;
7391    int method_count;
7392    struct _objc_method method_list[];
7393    }
7394    */
7395   unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7396   Result += "\n";
7397   if (LangOpts.MicrosoftExt) {
7398     if (IsInstanceMethod)
7399       Result += "__declspec(allocate(\".inst_meth$B\")) ";
7400     else
7401       Result += "__declspec(allocate(\".cls_meth$B\")) ";
7402   }
7403   Result += "static struct {\n";
7404   Result += "\tstruct _objc_method_list *next_method;\n";
7405   Result += "\tint method_count;\n";
7406   Result += "\tstruct _objc_method method_list[";
7407   Result += utostr(NumMethods);
7408   Result += "];\n} _OBJC_";
7409   Result += prefix;
7410   Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7411   Result += "_METHODS_";
7412   Result += ClassName;
7413   Result += " __attribute__ ((used, section (\"__OBJC, __";
7414   Result += IsInstanceMethod ? "inst" : "cls";
7415   Result += "_meth\")))= ";
7416   Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7417 
7418   Result += "\t,{{(SEL)\"";
7419   Result += (*MethodBegin)->getSelector().getAsString().c_str();
7420   std::string MethodTypeString;
7421   Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7422   Result += "\", \"";
7423   Result += MethodTypeString;
7424   Result += "\", (void *)";
7425   Result += MethodInternalNames[*MethodBegin];
7426   Result += "}\n";
7427   for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7428     Result += "\t  ,{(SEL)\"";
7429     Result += (*MethodBegin)->getSelector().getAsString().c_str();
7430     std::string MethodTypeString;
7431     Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7432     Result += "\", \"";
7433     Result += MethodTypeString;
7434     Result += "\", (void *)";
7435     Result += MethodInternalNames[*MethodBegin];
7436     Result += "}\n";
7437   }
7438   Result += "\t }\n};\n";
7439 }
7440 
7441 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7442   SourceRange OldRange = IV->getSourceRange();
7443   Expr *BaseExpr = IV->getBase();
7444 
7445   // Rewrite the base, but without actually doing replaces.
7446   {
7447     DisableReplaceStmtScope S(*this);
7448     BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7449     IV->setBase(BaseExpr);
7450   }
7451 
7452   ObjCIvarDecl *D = IV->getDecl();
7453 
7454   Expr *Replacement = IV;
7455 
7456     if (BaseExpr->getType()->isObjCObjectPointerType()) {
7457       const ObjCInterfaceType *iFaceDecl =
7458         dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7459       assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7460       // lookup which class implements the instance variable.
7461       ObjCInterfaceDecl *clsDeclared = nullptr;
7462       iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7463                                                    clsDeclared);
7464       assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7465 
7466       // Build name of symbol holding ivar offset.
7467       std::string IvarOffsetName;
7468       if (D->isBitField())
7469         ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7470       else
7471         WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7472 
7473       ReferencedIvars[clsDeclared].insert(D);
7474 
7475       // cast offset to "char *".
7476       CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7477                                                     Context->getPointerType(Context->CharTy),
7478                                                     CK_BitCast,
7479                                                     BaseExpr);
7480       VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7481                                        SourceLocation(), &Context->Idents.get(IvarOffsetName),
7482                                        Context->UnsignedLongTy, nullptr,
7483                                        SC_Extern);
7484       DeclRefExpr *DRE = new (Context)
7485           DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7486                       VK_LValue, SourceLocation());
7487       BinaryOperator *addExpr =
7488         new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7489                                      Context->getPointerType(Context->CharTy),
7490                                      VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
7491       // Don't forget the parens to enforce the proper binding.
7492       ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7493                                               SourceLocation(),
7494                                               addExpr);
7495       QualType IvarT = D->getType();
7496       if (D->isBitField())
7497         IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7498 
7499       if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7500         RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
7501         RD = RD->getDefinition();
7502         if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7503           // decltype(((Foo_IMPL*)0)->bar) *
7504           ObjCContainerDecl *CDecl =
7505             dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7506           // ivar in class extensions requires special treatment.
7507           if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7508             CDecl = CatDecl->getClassInterface();
7509           std::string RecName = CDecl->getName();
7510           RecName += "_IMPL";
7511           RecordDecl *RD = RecordDecl::Create(
7512               *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7513               &Context->Idents.get(RecName));
7514           QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7515           unsigned UnsignedIntSize =
7516             static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7517           Expr *Zero = IntegerLiteral::Create(*Context,
7518                                               llvm::APInt(UnsignedIntSize, 0),
7519                                               Context->UnsignedIntTy, SourceLocation());
7520           Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7521           ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7522                                                   Zero);
7523           FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7524                                             SourceLocation(),
7525                                             &Context->Idents.get(D->getNameAsString()),
7526                                             IvarT, nullptr,
7527                                             /*BitWidth=*/nullptr,
7528                                             /*Mutable=*/true, ICIS_NoInit);
7529           MemberExpr *ME = MemberExpr::CreateImplicit(
7530               *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
7531           IvarT = Context->getDecltypeType(ME, ME->getType());
7532         }
7533       }
7534       convertObjCTypeToCStyleType(IvarT);
7535       QualType castT = Context->getPointerType(IvarT);
7536 
7537       castExpr = NoTypeInfoCStyleCastExpr(Context,
7538                                           castT,
7539                                           CK_BitCast,
7540                                           PE);
7541 
7542 
7543       Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7544                                               VK_LValue, OK_Ordinary,
7545                                               SourceLocation(), false);
7546       PE = new (Context) ParenExpr(OldRange.getBegin(),
7547                                    OldRange.getEnd(),
7548                                    Exp);
7549 
7550       if (D->isBitField()) {
7551         FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7552                                           SourceLocation(),
7553                                           &Context->Idents.get(D->getNameAsString()),
7554                                           D->getType(), nullptr,
7555                                           /*BitWidth=*/D->getBitWidth(),
7556                                           /*Mutable=*/true, ICIS_NoInit);
7557         MemberExpr *ME =
7558             MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
7559                                        FD->getType(), VK_LValue, OK_Ordinary);
7560         Replacement = ME;
7561 
7562       }
7563       else
7564         Replacement = PE;
7565     }
7566 
7567     ReplaceStmtWithRange(IV, Replacement, OldRange);
7568     return Replacement;
7569 }
7570 
7571 #endif // CLANG_ENABLE_OBJC_REWRITER
7572