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