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