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