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