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