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