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