Clang Project

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