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