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