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