blob: 67b2bdef5de40c36cee0fcf3b265899062cb1ff1 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000030#include <memory>
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000031
Alp Toker0621cb22014-07-16 16:48:33 +000032#ifdef CLANG_ENABLE_OBJC_REWRITER
33
Chris Lattnere99c8322007-10-11 00:43:27 +000034using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000035using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000036
Chris Lattnere99c8322007-10-11 00:43:27 +000037namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian83077422011-12-08 18:25:15 +000039 protected:
40
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000041 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000042 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000043 block, ... */
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
46 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000047 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000048 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000049 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000050 support routines */
51 BLOCK_BYREF_CURRENT_MAX = 256
52 };
53
54 enum {
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
61 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000062 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000063
Chris Lattner0bd1c972007-10-16 21:07:07 +000064 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000065 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000066 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000067 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000068 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000069 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000070 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000071 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000072 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000074 std::string InFileName;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000085
Fariborz Jahanian8efef602011-12-05 19:50:04 +000086 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
Fariborz Jahanian83077422011-12-08 18:25:15 +000089 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000090 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000109 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000120
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000127
John McCall113bee02012-03-10 09:33:50 +0000128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff22216db2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000145
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000146 // Needed for header files being rewritten
147 bool IsHeader;
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
150
Steve Naroff08628db2008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000152 class DisableReplaceStmtScope {
153 RewriteObjC &R;
154 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000155
John McCallfe96e0b2011-11-06 09:01:30 +0000156 public:
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
160 }
161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
163 }
164 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000165 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattnere99c8322007-10-11 00:43:27 +0000167 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000168
Chris Lattner3c799d72007-10-24 17:06:59 +0000169 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000170 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000172 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173 if (!Class->isThisDeclarationADefinition()) {
174 RewriteForwardClassDecl(D);
175 break;
176 }
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000177 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000178
Douglas Gregorf6102672012-01-01 21:23:57 +0000179 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
182 break;
183 }
184 }
185
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000186 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000187 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000188 return true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000189 }
190 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000191 void HandleDeclInMainFile(Decl *D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000192 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000193 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000194 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000195
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000196 ~RewriteObjC() override {}
Mike Stump11289f42009-09-09 15:08:12 +0000197
Craig Topperfb6b25b2014-03-15 04:29:04 +0000198 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump11289f42009-09-09 15:08:12 +0000199
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000200 void ReplaceStmt(Stmt *Old, Stmt *New) {
Daniel Jasper4475a242014-10-23 19:47:36 +0000201 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Chris Lattner2e0d2602008-01-31 19:37:57 +0000202 }
Steve Naroff08628db2008-12-09 12:56:34 +0000203
204 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Richard Trieuddd01ce2014-06-09 22:53:25 +0000205 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Daniel Jasper4475a242014-10-23 19:47:36 +0000206
207 Stmt *ReplacingStmt = ReplacedNodes[Old];
208 if (ReplacingStmt)
209 return; // We can't rewrite the same node twice.
210
John McCallfe96e0b2011-11-06 09:01:30 +0000211 if (DisableReplaceStmt)
212 return;
213
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000214 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000215 int Size = Rewrite.getRangeSize(SrcRange);
216 if (Size == -1) {
217 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
218 << Old->getSourceRange();
219 return;
220 }
221 // Get the new text.
222 std::string SStr;
223 llvm::raw_string_ostream S(SStr);
Craig Topper8ae12032014-05-07 06:21:57 +0000224 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000225 const std::string &Str = S.str();
226
227 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000228 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000229 ReplacedNodes[Old] = New;
230 return;
231 }
232 if (SilenceRewriteMacroWarning)
233 return;
234 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
235 << Old->getSourceRange();
236 }
237
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000238 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000239 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner1780a852008-01-31 19:42:41 +0000245 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
246 }
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattner9cc55f52008-01-31 19:51:04 +0000248 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000249 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000250 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000251 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000252 SilenceRewriteMacroWarning)
253 return;
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattner9cc55f52008-01-31 19:51:04 +0000255 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Chris Lattner3c799d72007-10-24 17:06:59 +0000258 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000259 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000260 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000261 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000262 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000263 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000264 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000265 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000266 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
267 ObjCImplementationDecl *IMD,
268 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000269 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000270 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000271 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
272 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000273 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
274 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000275 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000276 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000277 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
278 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000279 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000280 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000281 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000282 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000283 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000284 void RewriteBlockPointerType(std::string& Str, QualType Type);
285 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000286 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000288 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000289 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000290
Chris Lattner3c799d72007-10-24 17:06:59 +0000291 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000292 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000293 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000294 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
295 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000296 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000297 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000298 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000299 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000300 void RewriteTryReturnStmts(Stmt *S);
301 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000302 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000303 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000304 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000305 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
306 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000309 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000310
Steve Naroff677ab3a2008-10-27 17:20:55 +0000311 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000312 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000313
Mike Stump11289f42009-09-09 15:08:12 +0000314 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000315 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000316 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000317 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000318 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000320
321 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
322 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000323
David Blaikie1cbb9712014-11-14 19:09:44 +0000324 void Initialize(ASTContext &context) override = 0;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000325
Fariborz Jahanian83077422011-12-08 18:25:15 +0000326 // Metadata Rewriting.
327 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
328 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
329 StringRef prefix,
330 StringRef ClassName,
331 std::string &Result) = 0;
332 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
333 std::string &Result) = 0;
334 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
339 std::string &Result) = 0;
340
341 // Rewriting ivar access
342 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
343 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
344 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000345
Benjamin Kramer474261a2012-06-02 10:20:41 +0000346 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000347 // rewriting routines on the new ASTs.
348 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Craig Toppercf2126e2015-10-22 03:13:07 +0000349 ArrayRef<Expr *> Args,
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000350 SourceLocation StartLoc=SourceLocation(),
351 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000352 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
353 QualType msgSendType,
354 QualType returnType,
355 SmallVectorImpl<QualType> &ArgTypes,
356 SmallVectorImpl<Expr*> &MsgExprs,
357 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000358 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
361
362 void SynthCountByEnumWithState(std::string &buf);
363 void SynthMsgSendFunctionDecl();
364 void SynthMsgSendSuperFunctionDecl();
365 void SynthMsgSendStretFunctionDecl();
366 void SynthMsgSendFpretFunctionDecl();
367 void SynthMsgSendSuperStretFunctionDecl();
368 void SynthGetClassFunctionDecl();
369 void SynthGetMetaClassFunctionDecl();
370 void SynthGetSuperClassFunctionDecl();
371 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000372 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000373
374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000375 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000376 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000377 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000378 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000379 std::string SynthesizeBlockImpl(BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
382 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000383 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000384 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000385 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000386 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000387 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000388 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
389 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000390 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000391
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000392 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000393 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000394 void WarnAboutReturnGotoStmts(Stmt *S);
395 void HasReturnStmts(Stmt *S, bool &hasReturns);
396 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
397 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
398 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
399
400 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000401 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000403 void GetInnerBlockDeclRefExprs(Stmt *S,
404 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +0000405 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000406
Steve Naroff677ab3a2008-10-27 17:20:55 +0000407 // We avoid calling Type::isBlockPointerType(), since it operates on the
408 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000409 bool isTopLevelBlockPointerType(QualType T) {
410 return isa<BlockPointerType>(T);
411 }
Mike Stump11289f42009-09-09 15:08:12 +0000412
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000413 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
414 /// to a function pointer type and upon success, returns true; false
415 /// otherwise.
416 bool convertBlockPointerToFunctionPointer(QualType &T) {
417 if (isTopLevelBlockPointerType(T)) {
418 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
419 T = Context->getPointerType(BPT->getPointeeType());
420 return true;
421 }
422 return false;
423 }
424
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000425 bool needToScanForQualifiers(QualType T);
426 QualType getSuperStructType();
427 QualType getConstantStringStructType();
428 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
429 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
430
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000431 void convertToUnqualifiedObjCType(QualType &T) {
432 if (T->isObjCQualifiedIdType())
433 T = Context->getObjCIdType();
434 else if (T->isObjCQualifiedClassType())
435 T = Context->getObjCClassType();
436 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000437 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
438 if (const ObjCObjectPointerType * OBJPT =
439 T->getAsObjCInterfacePointerType()) {
440 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
441 T = QualType(IFaceT, 0);
442 T = Context->getPointerType(T);
443 }
444 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000445 }
446
Steve Naroff677ab3a2008-10-27 17:20:55 +0000447 // FIXME: This predicate seems like it would be useful to add to ASTContext.
448 bool isObjCType(QualType T) {
449 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
450 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000451
Steve Naroff677ab3a2008-10-27 17:20:55 +0000452 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000453
Steve Naroff677ab3a2008-10-27 17:20:55 +0000454 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
455 OCT == Context->getCanonicalType(Context->getObjCClassType()))
456 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000458 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000459 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000460 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000461 return true;
462 }
463 return false;
464 }
465 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000466 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000467 void GetExtentOfArgList(const char *Name, const char *&LParen,
468 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000469
Steve Naroffd9803712009-04-29 16:37:50 +0000470 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000471 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000472 if (From[i] == '"')
473 To += "\\\"";
474 else
475 To += From[i];
476 }
477 }
John McCalldb40c7f2010-12-14 08:05:40 +0000478
479 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000480 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000481 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000482 if (result == Context->getObjCInstanceType())
483 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000484 FunctionProtoType::ExtProtoInfo fpi;
485 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000486 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000487 }
John McCall97513962010-01-15 18:39:57 +0000488
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000489 // Helper function: create a CStyleCastExpr with trivial type source info.
490 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
491 CastKind Kind, Expr *E) {
492 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Craig Topper8ae12032014-05-07 06:21:57 +0000493 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
494 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000495 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000496
497 StringLiteral *getStringLiteral(StringRef Str) {
498 QualType StrType = Context->getConstantArrayType(
499 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
500 0);
501 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
502 /*Pascal=*/false, StrType, SourceLocation());
503 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000504 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000505
506 class RewriteObjCFragileABI : public RewriteObjC {
507 public:
508
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512 D, LOpts,
513 silenceMacroWarn) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000514
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000515 ~RewriteObjCFragileABI() override {}
David Blaikie1cbb9712014-11-14 19:09:44 +0000516 void Initialize(ASTContext &context) override;
Craig Topperfb6b25b2014-03-15 04:29:04 +0000517
Fariborz Jahanian83077422011-12-08 18:25:15 +0000518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000526 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix, StringRef ClassName,
528 std::string &Result) override;
529 void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result) override;
532 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result) override;
534 void RewriteMetaDataIntoBuffer(std::string &Result) override;
535 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result) override;
537
Fariborz Jahanian83077422011-12-08 18:25:15 +0000538 // Rewriting ivar
Craig Topperfb6b25b2014-03-15 04:29:04 +0000539 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result) override;
541 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahanian83077422011-12-08 18:25:15 +0000542 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000543}
Chris Lattnere99c8322007-10-11 00:43:27 +0000544
Mike Stump11289f42009-09-09 15:08:12 +0000545void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000547 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000549 for (const auto &I : fproto->param_types())
550 if (isTopLevelBlockPointerType(I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000551 // All the args are checked/rewritten. Don't call twice!
552 RewriteBlockPointerDecl(D);
553 break;
554 }
555 }
556}
557
558void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000559 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000561 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562}
563
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000564static bool IsHeaderFile(const std::string &Filename) {
565 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000566
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000567 if (DotPos == std::string::npos) {
568 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000569 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000570 }
Mike Stump11289f42009-09-09 15:08:12 +0000571
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
573 // C header: .h
574 // C++ header: .hh or .H;
575 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000576}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000577
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000578RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000579 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000583 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000584 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000585 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000590}
591
David Blaikie6beb6aa2014-08-10 19:56:51 +0000592std::unique_ptr<ASTConsumer>
593clang::CreateObjCRewriter(const std::string &InFile, raw_ostream *OS,
594 DiagnosticsEngine &Diags, const LangOptions &LOpts,
595 bool SilenceRewriteMacroWarning) {
596 return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
597 SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000598}
Chris Lattnere99c8322007-10-11 00:43:27 +0000599
Fariborz Jahanian83077422011-12-08 18:25:15 +0000600void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000601 Context = &context;
602 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000603 TUDecl = Context->getTranslationUnitDecl();
Craig Topper8ae12032014-05-07 06:21:57 +0000604 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;
Chris Lattner187f6262008-01-31 19:38:44 +0000623 BcLabelCount = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000624 SuperConstructorFunctionDecl = nullptr;
Steve Naroffce8e8862008-03-15 00:55:56 +0000625 NumObjCStringLiterals = 0;
Craig Topper8ae12032014-05-07 06:21:57 +0000626 PropParentMap = nullptr;
627 CurrentBody = nullptr;
Steve Naroff08628db2008-12-09 12:56:34 +0000628 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000629 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner187f6262008-01-31 19:38:44 +0000631 // 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();
Mike Stump11289f42009-09-09 15:08:12 +0000636
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000638}
639
Chris Lattner3c799d72007-10-24 17:06:59 +0000640//===----------------------------------------------------------------------===//
641// Top Level Driver Code
642//===----------------------------------------------------------------------===//
643
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000644void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000645 if (Diags.hasErrorOccurred())
646 return;
647
Chris Lattner0bd1c972007-10-16 21:07:07 +0000648 // 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();
Chandler Carruth35f53202011-07-25 16:49:02 +0000652 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000653
Chris Lattner0bd1c972007-10-16 21:07:07 +0000654 // If this is for a builtin, ignore it.
655 if (Loc.isInvalid()) return;
656
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000657 // Look for built-in declarations that we need to refer during the rewrite.
658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000659 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000660 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000661 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000662 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000663 ConstantStringClassReference = FVD;
664 return;
665 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000666 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667 if (ID->isThisDeclarationADefinition())
668 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000669 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000670 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000671 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000674 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000676 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000678 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000679 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
682 SourceLocation StartLoc = IFace->getLocStart();
683 do {
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
687 DG.push_back(*DI);
688 else
689 break;
690
Douglas Gregordc9166c2011-12-15 20:29:51 +0000691 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000692 } while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
694 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000695 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000696 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000697
698 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
701 SourceLocation StartLoc = Proto->getLocStart();
702 do {
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
706 DG.push_back(*DI);
707 else
708 break;
709
710 ++DI;
711 } while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
713 continue;
714 }
715 }
716
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000717 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000718 ++DI;
719 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000720 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000721 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000722 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000723 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000724}
725
Chris Lattner3c799d72007-10-24 17:06:59 +0000726//===----------------------------------------------------------------------===//
727// Syntactic (non-AST) Rewriting Code
728//===----------------------------------------------------------------------===//
729
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000730void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000732 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000735 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000736
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000737 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000738 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
Mike Stump11289f42009-09-09 15:08:12 +0000747 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000748 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000749 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000750 BufPtr += ImportLen;
751 }
752 }
753 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000754}
755
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000756static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000762 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000763 return S;
764}
765
Steve Naroffc038b3a2008-12-02 17:36:43 +0000766void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000771 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000772 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000773 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 ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000777 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000778 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000782
Steve Naroff9af94912008-12-02 15:48:25 +0000783 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000786
Steve Naroff003d00e2008-12-02 16:05:55 +0000787 if (!OID)
788 return;
Bill Wendling44426052012-12-20 19:22:21 +0000789 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000790 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000793 ObjCPropertyDecl::OBJC_PR_copy));
794 std::string Getr;
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000800 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
803 Getr += "{ ";
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808 Getr += "typedef ";
Craig Topper8ae12032014-05-07 06:21:57 +0000809 const FunctionType *FPRetType = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000811 FPRetType);
812 Getr += " _TYPE";
813 if (FPRetType) {
814 Getr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000819 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000820 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000821 std::string ParamStr =
822 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000823 Getr += ParamStr;
824 }
825 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000826 if (FT->getNumParams())
827 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000837 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000844 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000847 return;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Steve Naroff9af94912008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000867 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000870 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000872 Setr += "0, ";
873 else
874 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000886}
Chris Lattner16a0de42007-10-11 18:38:32 +0000887
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000888static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
899}
900
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000901void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000902 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000903 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000910void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000911 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000914 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000920 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000923 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000924 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000926}
Mike Stump11289f42009-09-09 15:08:12 +0000927
Craig Topper5603df42013-07-05 19:34:19 +0000928void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000929 std::string typedefString;
930 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000931 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000932 if (i == 0) {
933 typedefString += "// @class ";
934 typedefString += ForwardDecl->getNameAsString();
935 typedefString += ";\n";
936 }
937 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
938 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000939 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000940}
941
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000942void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000943 // When method is a synthesized one, such as a getter/setter there is
944 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000945 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000946 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000947 SourceLocation LocStart = Method->getLocStart();
948 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000949
Chandler Carruthd48db212011-07-25 21:09:52 +0000950 if (SM->getExpansionLineNumber(LocEnd) >
951 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000952 InsertText(LocStart, "#if 0\n");
953 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000954 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000955 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000956 }
957}
958
Mike Stump11289f42009-09-09 15:08:12 +0000959void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000960 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000961
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000962 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000963 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000964}
965
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000966void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000967 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000968
Steve Naroff5448cf62007-10-30 13:30:57 +0000969 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000970 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000971
Manman Rena7a8b1f2016-01-26 18:05:23 +0000972 for (auto *I : CatDecl->instance_properties())
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000973 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000974 for (auto *I : CatDecl->instance_methods())
975 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000976 for (auto *I : CatDecl->class_methods())
977 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000978
Steve Naroff5448cf62007-10-30 13:30:57 +0000979 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000980 ReplaceText(CatDecl->getAtEndRange().getBegin(),
981 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000982}
983
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000984void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000985 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000986 assert(PDecl->isThisDeclarationADefinition());
987
Steve Narofff921385f2007-10-30 16:42:30 +0000988 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000989 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000990
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000991 for (auto *I : PDecl->instance_methods())
992 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +0000993 for (auto *I : PDecl->class_methods())
994 RewriteMethodDeclaration(I);
Manman Rena7a8b1f2016-01-26 18:05:23 +0000995 for (auto *I : PDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000996 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000997
Steve Narofff921385f2007-10-30 16:42:30 +0000998 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000999 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001000 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001001
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001002 // Must comment out @optional/@required
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
1005 for (const char *p = startBuf; p < endBuf; p++) {
1006 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001007 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001008 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001009
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001010 }
1011 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001012 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001013 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001014
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001015 }
1016 }
Steve Narofff921385f2007-10-30 16:42:30 +00001017}
1018
Douglas Gregorf6102672012-01-01 21:23:57 +00001019void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020 SourceLocation LocStart = (*D.begin())->getLocStart();
1021 if (LocStart.isInvalid())
1022 llvm_unreachable("Invalid SourceLocation");
1023 // FIXME: handle forward protocol that are declared across multiple lines.
1024 ReplaceText(LocStart, 0, "// ");
1025}
1026
1027void
Craig Topper5603df42013-07-05 19:34:19 +00001028RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001029 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001030 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001031 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001032 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001033 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001034}
1035
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001036void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037 const FunctionType *&FPRetType) {
1038 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001039 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001040 else if (T->isFunctionPointerType() ||
1041 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001042 // needs special handling, since pointer-to-functions have special
1043 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001044 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001045 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001046 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001047 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001048 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001049 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001050 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001051 ResultStr +=
1052 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001053 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001054 }
1055 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001056 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001057}
1058
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001059void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001061 std::string &ResultStr) {
1062 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001063 const FunctionType *FPRetType = nullptr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001064 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001065 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001066 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001067
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001068 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001069 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregorffca3a22009-01-09 17:18:27 +00001071 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001072 NameStr += "_I_";
1073 else
1074 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001075
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001076 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001077 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001078
1079 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001080 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001081 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001082 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001083 }
Mike Stump11289f42009-09-09 15:08:12 +00001084 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001085 {
1086 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 int len = selString.size();
1088 for (int i = 0; i < len; i++)
1089 if (selString[i] == ':')
1090 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001091 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001092 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001093 // Remember this name for metadata emission
1094 MethodInternalNames[OMD] = NameStr;
1095 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 // Rewrite arguments
1098 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001099
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001101 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001102 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001103 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001104 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001105 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001106 ResultStr += "struct ";
1107 }
1108 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001109 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001110 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001111 }
1112 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001113 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001114 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001115
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001116 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001117 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001118 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001119
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001120 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001121 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001122 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001123 if (PDecl->getType()->isObjCQualifiedIdType()) {
1124 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001125 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001126 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001127 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001128 QualType QT = PDecl->getType();
1129 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001130 (void)convertBlockPointerToFunctionPointer(QT);
1131 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001132 ResultStr += Name;
1133 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001134 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001137 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001138
Steve Naroffb067bbd2008-07-16 14:40:40 +00001139 if (FPRetType) {
1140 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroffb067bbd2008-07-16 14:40:40 +00001142 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001144 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001145 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001146 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001147 std::string ParamStr =
1148 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001149 ResultStr += ParamStr;
1150 }
1151 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001152 if (FT->getNumParams())
1153 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001154 ResultStr += "...";
1155 }
1156 ResultStr += ")";
1157 } else {
1158 ResultStr += "()";
1159 }
1160 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001161}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001162void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001163 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1164 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001165
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001166 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001167
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001168 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001169 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001170 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001172 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001173
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001174 const char *startBuf = SM->getCharacterData(LocStart);
1175 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001176 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001179 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001180 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001181 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001182 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001183 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001184
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185 const char *startBuf = SM->getCharacterData(LocStart);
1186 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001187 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001188 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001189 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1190 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001191
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001192 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001193}
1194
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001195void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001196 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001197 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001198 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001199 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001201 ResultStr += "\n";
1202 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001204 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001205 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001207 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001208 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001209 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001210 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001211 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Manman Rena7a8b1f2016-01-26 18:05:23 +00001213 for (auto *I : ClassDecl->instance_properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001214 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001215 for (auto *I : ClassDecl->instance_methods())
1216 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001217 for (auto *I : ClassDecl->class_methods())
1218 RewriteMethodDeclaration(I);
Steve Naroff3ce37a62007-12-14 23:37:57 +00001219
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001220 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001221 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1222 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001223}
1224
John McCallfe96e0b2011-11-06 09:01:30 +00001225Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1226 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001227
John McCallfe96e0b2011-11-06 09:01:30 +00001228 // We just magically know some things about the structure of this
1229 // expression.
1230 ObjCMessageExpr *OldMsg =
1231 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1232 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001233
John McCallfe96e0b2011-11-06 09:01:30 +00001234 // Because the rewriter doesn't allow us to rewrite rewritten code,
1235 // we need to suppress rewriting the sub-statements.
1236 Expr *Base, *RHS;
1237 {
1238 DisableReplaceStmtScope S(*this);
1239
1240 // Rebuild the base expression if we have one.
Craig Topper8ae12032014-05-07 06:21:57 +00001241 Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001242 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1243 Base = OldMsg->getInstanceReceiver();
1244 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1246 }
1247
1248 // Rebuild the RHS.
1249 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1250 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1252 }
1253
1254 // TODO: avoid this copy.
1255 SmallVector<SourceLocation, 1> SelLocs;
1256 OldMsg->getSelectorLocs(SelLocs);
1257
Craig Topper8ae12032014-05-07 06:21:57 +00001258 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001259 switch (OldMsg->getReceiverKind()) {
1260 case ObjCMessageExpr::Class:
1261 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1262 OldMsg->getValueKind(),
1263 OldMsg->getLeftLoc(),
1264 OldMsg->getClassReceiverTypeInfo(),
1265 OldMsg->getSelector(),
1266 SelLocs,
1267 OldMsg->getMethodDecl(),
1268 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001269 OldMsg->getRightLoc(),
1270 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001271 break;
1272
1273 case ObjCMessageExpr::Instance:
1274 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1275 OldMsg->getValueKind(),
1276 OldMsg->getLeftLoc(),
1277 Base,
1278 OldMsg->getSelector(),
1279 SelLocs,
1280 OldMsg->getMethodDecl(),
1281 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001282 OldMsg->getRightLoc(),
1283 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001284 break;
1285
1286 case ObjCMessageExpr::SuperClass:
1287 case ObjCMessageExpr::SuperInstance:
1288 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1289 OldMsg->getValueKind(),
1290 OldMsg->getLeftLoc(),
1291 OldMsg->getSuperLoc(),
1292 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1293 OldMsg->getSuperType(),
1294 OldMsg->getSelector(),
1295 SelLocs,
1296 OldMsg->getMethodDecl(),
1297 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001298 OldMsg->getRightLoc(),
1299 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001300 break;
1301 }
1302
1303 Stmt *Replacement = SynthMessageExpr(NewMsg);
1304 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1305 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001306}
1307
John McCallfe96e0b2011-11-06 09:01:30 +00001308Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1309 SourceRange OldRange = PseudoOp->getSourceRange();
1310
1311 // We just magically know some things about the structure of this
1312 // expression.
1313 ObjCMessageExpr *OldMsg =
1314 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1315
1316 // Because the rewriter doesn't allow us to rewrite rewritten code,
1317 // we need to suppress rewriting the sub-statements.
Craig Topper8ae12032014-05-07 06:21:57 +00001318 Expr *Base = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001319 {
1320 DisableReplaceStmtScope S(*this);
1321
1322 // Rebuild the base expression if we have one.
1323 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1324 Base = OldMsg->getInstanceReceiver();
1325 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1326 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001327 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001328 }
Steve Narofff326f402008-12-03 00:56:33 +00001329
John McCallfe96e0b2011-11-06 09:01:30 +00001330 // Intentionally empty.
1331 SmallVector<SourceLocation, 1> SelLocs;
1332 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001333
Craig Topper8ae12032014-05-07 06:21:57 +00001334 ObjCMessageExpr *NewMsg = nullptr;
John McCallfe96e0b2011-11-06 09:01:30 +00001335 switch (OldMsg->getReceiverKind()) {
1336 case ObjCMessageExpr::Class:
1337 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1338 OldMsg->getValueKind(),
1339 OldMsg->getLeftLoc(),
1340 OldMsg->getClassReceiverTypeInfo(),
1341 OldMsg->getSelector(),
1342 SelLocs,
1343 OldMsg->getMethodDecl(),
1344 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001345 OldMsg->getRightLoc(),
1346 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001347 break;
1348
1349 case ObjCMessageExpr::Instance:
1350 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1351 OldMsg->getValueKind(),
1352 OldMsg->getLeftLoc(),
1353 Base,
1354 OldMsg->getSelector(),
1355 SelLocs,
1356 OldMsg->getMethodDecl(),
1357 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001358 OldMsg->getRightLoc(),
1359 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001360 break;
1361
1362 case ObjCMessageExpr::SuperClass:
1363 case ObjCMessageExpr::SuperInstance:
1364 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1365 OldMsg->getValueKind(),
1366 OldMsg->getLeftLoc(),
1367 OldMsg->getSuperLoc(),
1368 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1369 OldMsg->getSuperType(),
1370 OldMsg->getSelector(),
1371 SelLocs,
1372 OldMsg->getMethodDecl(),
1373 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001374 OldMsg->getRightLoc(),
1375 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001376 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001377 }
John McCallfe96e0b2011-11-06 09:01:30 +00001378
1379 Stmt *Replacement = SynthMessageExpr(NewMsg);
1380 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1381 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001382}
1383
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384/// SynthCountByEnumWithState - To print:
1385/// ((unsigned int (*)
1386/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001387/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001388/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001389/// "countByEnumeratingWithState:objects:count:"),
1390/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001391/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001392///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001393void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1395 "id *, unsigned int))(void *)objc_msgSend)";
1396 buf += "\n\t\t";
1397 buf += "((id)l_collection,\n\t\t";
1398 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1399 buf += "\n\t\t";
1400 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001401 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001403
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001404/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1405/// statement to exit to its outer synthesized loop.
1406///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001407Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001408 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1409 return S;
1410 // replace break with goto __break_label
1411 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001413 SourceLocation startLoc = S->getLocStart();
1414 buf = "goto __break_label_";
1415 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001416 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001417
Craig Topper8ae12032014-05-07 06:21:57 +00001418 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001419}
1420
1421/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1422/// statement to continue with its inner synthesized loop.
1423///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001424Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001425 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1426 return S;
1427 // replace continue with goto __continue_label
1428 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001429
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001430 SourceLocation startLoc = S->getLocStart();
1431 buf = "goto __continue_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001433 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001434
Craig Topper8ae12032014-05-07 06:21:57 +00001435 return nullptr;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001436}
1437
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001438/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001439/// It rewrites:
1440/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001442/// Into:
1443/// {
Mike Stump11289f42009-09-09 15:08:12 +00001444/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001445/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001446/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001448/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001449/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001450/// if (limit) {
1451/// unsigned long startMutations = *enumState.mutationsPtr;
1452/// do {
1453/// unsigned long counter = 0;
1454/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001455/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001457/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001458/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001459/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001460/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001461/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001462/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001464/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001465/// }
1466/// else
1467/// elem = nil;
1468/// }
1469///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001470Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001471 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001472 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001473 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001474 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001475 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001476 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001477
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001480 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001481 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 std::string buf;
1483 buf = "\n{\n\t";
1484 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1485 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001486 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001487 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001488 if (ElementType->isObjCQualifiedIdType() ||
1489 ElementType->isObjCQualifiedInterfaceType())
1490 // Simply use 'id' for all qualified types.
1491 elementTypeAsString = "id";
1492 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001493 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001494 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001495 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001496 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 buf += elementName;
1498 buf += ";\n\t";
1499 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001500 else {
1501 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001502 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001503 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1504 if (VD->getType()->isObjCQualifiedIdType() ||
1505 VD->getType()->isObjCQualifiedInterfaceType())
1506 // Simply use 'id' for all qualified types.
1507 elementTypeAsString = "id";
1508 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001509 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 // struct __objcFastEnumerationState enumState = { 0 };
1513 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001514 // id __rw_items[16];
1515 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001516 // id l_collection = (id)
1517 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001518 // Find start location of 'collection' the hard way!
1519 const char *startCollectionBuf = startBuf;
1520 startCollectionBuf += 3; // skip 'for'
1521 startCollectionBuf = strchr(startCollectionBuf, '(');
1522 startCollectionBuf++; // skip '('
1523 // find 'in' and skip it.
1524 while (*startCollectionBuf != ' ' ||
1525 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1526 (*(startCollectionBuf+3) != ' ' &&
1527 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1528 startCollectionBuf++;
1529 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001530
1531 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001532 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001533 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001534 SourceLocation rightParenLoc = S->getRParenLoc();
1535 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001536 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001538
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001540 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001541 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001542 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001543 // ((unsigned int (*)
1544 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001545 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001546 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001547 // "countByEnumeratingWithState:objects:count:"),
1548 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001549 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 buf += "unsigned long limit =\n\t\t";
1551 SynthCountByEnumWithState(buf);
1552 buf += ";\n\t";
1553 /// if (limit) {
1554 /// unsigned long startMutations = *enumState.mutationsPtr;
1555 /// do {
1556 /// unsigned long counter = 0;
1557 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001558 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001559 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001560 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001561 buf += "if (limit) {\n\t";
1562 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1563 buf += "do {\n\t\t";
1564 buf += "unsigned long counter = 0;\n\t\t";
1565 buf += "do {\n\t\t\t";
1566 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1567 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1568 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001569 buf += " = (";
1570 buf += elementTypeAsString;
1571 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001572 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001573 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001574
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001575 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001576 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001577 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001578 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001580 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001581 /// }
1582 /// else
1583 /// elem = nil;
1584 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001585 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001586 buf = ";\n\t";
1587 buf += "__continue_label_";
1588 buf += utostr(ObjCBcLabelNo.back());
1589 buf += ": ;";
1590 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001591 buf += "} while (counter < limit);\n\t";
1592 buf += "} while (limit = ";
1593 SynthCountByEnumWithState(buf);
1594 buf += ");\n\t";
1595 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001596 buf += " = ((";
1597 buf += elementTypeAsString;
1598 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001599 buf += "__break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
1601 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001602 buf += "}\n\t";
1603 buf += "else\n\t\t";
1604 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001605 buf += " = ((";
1606 buf += elementTypeAsString;
1607 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001608 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001609
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001611 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001612 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001613 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001614 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001615 } else {
1616 /* Need to treat single statements specially. For example:
1617 *
1618 * for (A *a in b) if (stuff()) break;
1619 * for (A *a in b) xxxyy;
1620 *
1621 * The following code simply scans ahead to the semi to find the actual end.
1622 */
1623 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1624 const char *semiBuf = strchr(stmtBuf, ';');
1625 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001626 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001627 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001628 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001629 Stmts.pop_back();
1630 ObjCBcLabelNo.pop_back();
Craig Topper8ae12032014-05-07 06:21:57 +00001631 return nullptr;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001632}
1633
Mike Stump11289f42009-09-09 15:08:12 +00001634/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001635/// This routine rewrites @synchronized(expr) stmt;
1636/// into:
1637/// objc_sync_enter(expr);
1638/// @try stmt @finally { objc_sync_exit(expr); }
1639///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001640Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001641 // Get the start location and compute the semi location.
1642 SourceLocation startLoc = S->getLocStart();
1643 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001645 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001646
1647 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001648 buf = "objc_sync_enter((id)";
1649 const char *lparenBuf = startBuf;
1650 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001651 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001652 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1653 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001654 // been rewritten! (which implies the SourceLocation's are invalid).
1655 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001656 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001657 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001658 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001659 buf = ");\n";
1660 // declare a new scope with two variables, _stack and _rethrow.
1661 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1662 buf += "int buf[18/*32-bit i386*/];\n";
1663 buf += "char *pointers[4];} _stack;\n";
1664 buf += "id volatile _rethrow = 0;\n";
1665 buf += "objc_exception_try_enter(&_stack);\n";
1666 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001667 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001668 startLoc = S->getSynchBody()->getLocEnd();
1669 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001670
Steve Naroffad7013b2008-08-19 13:04:19 +00001671 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001672 SourceLocation lastCurlyLoc = startLoc;
1673 buf = "}\nelse {\n";
1674 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001675 buf += "}\n";
1676 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001677 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001678
1679 std::string syncBuf;
1680 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001681
1682 Expr *syncExpr = S->getSynchExpr();
1683 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1684 ? CK_BitCast :
1685 syncExpr->getType()->isBlockPointerType()
1686 ? CK_BlockPointerToObjCPointerCast
1687 : CK_CPointerToObjCPointerCast;
1688 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1689 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001690 std::string syncExprBufS;
1691 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Trieuddd01ce2014-06-09 22:53:25 +00001692 assert(syncExpr != nullptr && "Expected non-null Expr");
Craig Topper8ae12032014-05-07 06:21:57 +00001693 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001694 syncBuf += syncExprBuf.str();
1695 syncBuf += ");";
1696
1697 buf += syncBuf;
1698 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001699 buf += "}\n";
1700 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001701
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001702 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001703
1704 bool hasReturns = false;
1705 HasReturnStmts(S->getSynchBody(), hasReturns);
1706 if (hasReturns)
1707 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1708
Craig Topper8ae12032014-05-07 06:21:57 +00001709 return nullptr;
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001710}
1711
Steve Naroffec60b432009-12-05 21:43:12 +00001712void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1713{
Steve Naroff6d6da252008-12-05 17:03:39 +00001714 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001715 for (Stmt *SubStmt : S->children())
1716 if (SubStmt)
1717 WarnAboutReturnGotoStmts(SubStmt);
Steve Naroff6d6da252008-12-05 17:03:39 +00001718
Steve Naroffec60b432009-12-05 21:43:12 +00001719 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001720 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001721 TryFinallyContainsReturnDiag);
1722 }
1723 return;
1724}
1725
Steve Naroffec60b432009-12-05 21:43:12 +00001726void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1727{
1728 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001729 for (Stmt *SubStmt : S->children())
1730 if (SubStmt)
1731 HasReturnStmts(SubStmt, hasReturns);
Steve Naroffec60b432009-12-05 21:43:12 +00001732
1733 if (isa<ReturnStmt>(S))
1734 hasReturns = true;
1735 return;
1736}
1737
1738void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001740 for (Stmt *SubStmt : S->children())
1741 if (SubStmt) {
1742 RewriteTryReturnStmts(SubStmt);
Steve Naroffec60b432009-12-05 21:43:12 +00001743 }
1744 if (isa<ReturnStmt>(S)) {
1745 SourceLocation startLoc = S->getLocStart();
1746 const char *startBuf = SM->getCharacterData(startLoc);
1747
1748 const char *semiBuf = strchr(startBuf, ';');
1749 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001750 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001751
1752 std::string buf;
1753 buf = "{ objc_exception_try_exit(&_stack); return";
1754
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001755 ReplaceText(startLoc, 6, buf);
1756 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001757 }
1758 return;
1759}
1760
1761void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1762 // Perform a bottom up traversal of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00001763 for (Stmt *SubStmt : S->children())
1764 if (SubStmt) {
1765 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
Steve Naroffec60b432009-12-05 21:43:12 +00001766 }
1767 if (isa<ReturnStmt>(S)) {
1768 SourceLocation startLoc = S->getLocStart();
1769 const char *startBuf = SM->getCharacterData(startLoc);
1770
1771 const char *semiBuf = strchr(startBuf, ';');
1772 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001773 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001774
1775 std::string buf;
1776 buf = "{ objc_exception_try_exit(&_stack);";
1777 buf += syncExitBuf;
1778 buf += " return";
1779
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001780 ReplaceText(startLoc, 6, buf);
1781 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001782 }
1783 return;
1784}
1785
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001786Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001787 // Get the start location and compute the semi location.
1788 SourceLocation startLoc = S->getLocStart();
1789 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Steve Naroffbf478ec2007-11-07 04:08:17 +00001791 assert((*startBuf == '@') && "bogus @try location");
1792
1793 std::string buf;
1794 // declare a new scope with two variables, _stack and _rethrow.
1795 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1796 buf += "int buf[18/*32-bit i386*/];\n";
1797 buf += "char *pointers[4];} _stack;\n";
1798 buf += "id volatile _rethrow = 0;\n";
1799 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001800 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001801
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001802 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001803
Steve Naroffbf478ec2007-11-07 04:08:17 +00001804 startLoc = S->getTryBody()->getLocEnd();
1805 startBuf = SM->getCharacterData(startLoc);
1806
1807 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001808
Steve Naroffbf478ec2007-11-07 04:08:17 +00001809 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001810 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001811 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001812 buf = " /* @catch begin */ else {\n";
1813 buf += " id _caught = objc_exception_extract(&_stack);\n";
1814 buf += " objc_exception_try_enter (&_stack);\n";
1815 buf += " if (_setjmp(_stack.buf))\n";
1816 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1817 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001818
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001819 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001820 } else { /* no catch list */
1821 buf = "}\nelse {\n";
1822 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1823 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001824 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001825 }
Craig Topper8ae12032014-05-07 06:21:57 +00001826 Stmt *lastCatchBody = nullptr;
Douglas Gregor96c79492010-04-23 22:50:49 +00001827 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1828 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001829 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001830
Douglas Gregor96c79492010-04-23 22:50:49 +00001831 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001832 buf = "if ("; // we are generating code for the first catch clause
1833 else
1834 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001835 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001836 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001837
Steve Naroffbf478ec2007-11-07 04:08:17 +00001838 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001839
Steve Naroffbf478ec2007-11-07 04:08:17 +00001840 const char *lParenLoc = strchr(startBuf, '(');
1841
Douglas Gregor96c79492010-04-23 22:50:49 +00001842 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001843 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001844 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001845 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1846 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001847 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001848 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001849 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001850
Steve Naroffedb5bc62008-02-01 20:02:07 +00001851 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001852 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001853 } else if (catchDecl) {
1854 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001855 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001857 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001858 } else if (const ObjCObjectPointerType *Ptr =
1859 t->getAs<ObjCObjectPointerType>()) {
1860 // Should be a pointer to a class.
1861 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1862 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001863 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001864 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001865 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001867 }
1868 }
1869 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001870 lastCatchBody = Catch->getCatchBody();
1871 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001872 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1873 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1874 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1875 assert((*rParenBuf == ')') && "bogus @catch paren location");
1876 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001877
Mike Stump11289f42009-09-09 15:08:12 +00001878 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001879 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001880 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001881 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001882 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001883 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001884 }
1885 // Complete the catch list...
1886 if (lastCatchBody) {
1887 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001888 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1889 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001890
Steve Naroff4adbe312008-09-11 15:29:03 +00001891 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001892 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001893 buf = "} /* last catch end */\n";
1894 buf += "else {\n";
1895 buf += " _rethrow = _caught;\n";
1896 buf += " objc_exception_try_exit(&_stack);\n";
1897 buf += "} } /* @catch end */\n";
1898 if (!S->getFinallyStmt())
1899 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001900 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Steve Naroffbf478ec2007-11-07 04:08:17 +00001902 // Set lastCurlyLoc
1903 lastCurlyLoc = lastCatchBody->getLocEnd();
1904 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001905 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001906 startLoc = finalStmt->getLocStart();
1907 startBuf = SM->getCharacterData(startLoc);
1908 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001909
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001910 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001911
Steve Naroffbf478ec2007-11-07 04:08:17 +00001912 Stmt *body = finalStmt->getFinallyBody();
1913 SourceLocation startLoc = body->getLocStart();
1914 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001915 assert(*SM->getCharacterData(startLoc) == '{' &&
1916 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001917 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001918 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001919
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001920 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001922 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001923 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001924
Steve Naroffbf478ec2007-11-07 04:08:17 +00001925 // Set lastCurlyLoc
1926 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001927
Steve Naroff6d6da252008-12-05 17:03:39 +00001928 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001929 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001930 } else { /* no finally clause - make sure we synthesize an implicit one */
1931 buf = "{ /* implicit finally clause */\n";
1932 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1933 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1934 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001935 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001936
1937 // Now check for any return/continue/go statements within the @try.
1938 // The implicit finally clause won't called if the @try contains any
1939 // jump statements.
1940 bool hasReturns = false;
1941 HasReturnStmts(S->getTryBody(), hasReturns);
1942 if (hasReturns)
1943 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001944 }
1945 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001946 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001947 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Craig Topper8ae12032014-05-07 06:21:57 +00001948 return nullptr;
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001949}
1950
Mike Stump11289f42009-09-09 15:08:12 +00001951// This can't be done with ReplaceStmt(S, ThrowExpr), since
1952// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001953// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001954Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001955 // Get the start location and compute the semi location.
1956 SourceLocation startLoc = S->getLocStart();
1957 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001958
Steve Naroffa733c7f2007-11-07 15:32:26 +00001959 assert((*startBuf == '@') && "bogus @throw location");
1960
1961 std::string buf;
1962 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001963 if (S->getThrowExpr())
1964 buf = "objc_exception_throw(";
1965 else // add an implicit argument
1966 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001967
Steve Naroff29788342008-07-25 15:41:30 +00001968 // handle "@ throw" correctly.
1969 const char *wBuf = strchr(startBuf, 'w');
1970 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001971 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001972
Steve Naroffa733c7f2007-11-07 15:32:26 +00001973 const char *semiBuf = strchr(startBuf, ';');
1974 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001975 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001976 ReplaceText(semiLoc, 1, ");");
Craig Topper8ae12032014-05-07 06:21:57 +00001977 return nullptr;
Steve Naroffa733c7f2007-11-07 15:32:26 +00001978}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001979
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001981 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00001982 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001983 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00001984 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00001985 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001986
Chris Lattner4431a1b2007-11-30 22:53:43 +00001987 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001988 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001989 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001990}
1991
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001992Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001993 if (!SelGetUidFunctionDecl)
1994 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001995 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1996 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001997 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00001998 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002000 SelExprs);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002001 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002002 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002003 return SelExp;
2004}
2005
Craig Toppercf2126e2015-10-22 03:13:07 +00002006CallExpr *
2007RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2008 ArrayRef<Expr *> Args,
2009 SourceLocation StartLoc,
2010 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002011 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002012 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002013
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002014 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002015 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2016 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002017
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002018 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002019 QualType pToFunc = Context->getPointerType(msgSendType);
Craig Topper8ae12032014-05-07 06:21:57 +00002020 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002021 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Craig Topper8ae12032014-05-07 06:21:57 +00002022 DRE, nullptr, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002023
John McCall9dd450b2009-09-21 23:43:11 +00002024 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002025
Craig Toppercf2126e2015-10-22 03:13:07 +00002026 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2027 FT->getCallResultType(*Context),
2028 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002029 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002030}
2031
Steve Naroff50d42052007-11-01 13:24:47 +00002032static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2033 const char *&startRef, const char *&endRef) {
2034 while (startBuf < endBuf) {
2035 if (*startBuf == '<')
2036 startRef = startBuf; // mark the start.
2037 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002038 if (startRef && *startRef == '<') {
2039 endRef = startBuf; // mark the end.
2040 return true;
2041 }
2042 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002043 }
2044 startBuf++;
2045 }
2046 return false;
2047}
2048
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002049static void scanToNextArgument(const char *&argRef) {
2050 int angle = 0;
2051 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2052 if (*argRef == '<')
2053 angle++;
2054 else if (*argRef == '>')
2055 angle--;
2056 argRef++;
2057 }
2058 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2059}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002060
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002061bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002062 if (T->isObjCQualifiedIdType())
2063 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002064 if (const PointerType *PT = T->getAs<PointerType>()) {
2065 if (PT->getPointeeType()->isObjCQualifiedIdType())
2066 return true;
2067 }
2068 if (T->isObjCObjectPointerType()) {
2069 T = T->getPointeeType();
2070 return T->isObjCQualifiedInterfaceType();
2071 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002072 if (T->isArrayType()) {
2073 QualType ElemTy = Context->getBaseElementType(T);
2074 return needToScanForQualifiers(ElemTy);
2075 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002076 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002077}
2078
Steve Naroff873bd842008-07-29 18:15:38 +00002079void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2080 QualType Type = E->getType();
2081 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002082 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Steve Naroffdbfc6932008-11-19 21:15:47 +00002084 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2085 Loc = ECE->getLParenLoc();
2086 EndLoc = ECE->getRParenLoc();
2087 } else {
2088 Loc = E->getLocStart();
2089 EndLoc = E->getLocEnd();
2090 }
2091 // This will defend against trying to rewrite synthesized expressions.
2092 if (Loc.isInvalid() || EndLoc.isInvalid())
2093 return;
2094
Steve Naroff873bd842008-07-29 18:15:38 +00002095 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002096 const char *endBuf = SM->getCharacterData(EndLoc);
Craig Topper8ae12032014-05-07 06:21:57 +00002097 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff873bd842008-07-29 18:15:38 +00002098 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2099 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002100 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2101 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002102 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002103 InsertText(LessLoc, "/*");
2104 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002105 }
2106 }
2107}
2108
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002109void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002110 SourceLocation Loc;
2111 QualType Type;
Craig Topper8ae12032014-05-07 06:21:57 +00002112 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002113 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2114 Loc = VD->getLocation();
2115 Type = VD->getType();
2116 }
2117 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2118 Loc = FD->getLocation();
2119 // Check for ObjC 'id' and class types that have been adorned with protocol
2120 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002121 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002122 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002123 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002124 if (!proto)
2125 return;
Alp Toker314cc812014-01-25 16:55:45 +00002126 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002127 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002128 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2129 Loc = FD->getLocation();
2130 Type = FD->getType();
2131 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002132 else
2133 return;
Mike Stump11289f42009-09-09 15:08:12 +00002134
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002135 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002136 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002137
Steve Naroff50d42052007-11-01 13:24:47 +00002138 const char *endBuf = SM->getCharacterData(Loc);
2139 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002140 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002141 startBuf--; // scan backward (from the decl location) for return type.
Craig Topper8ae12032014-05-07 06:21:57 +00002142 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002143 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2144 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002145 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2146 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002147 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002148 InsertText(LessLoc, "/*");
2149 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002150 }
2151 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152 if (!proto)
2153 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002154 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002155 const char *startBuf = SM->getCharacterData(Loc);
2156 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002157 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2158 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002159 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002160
Steve Naroff50d42052007-11-01 13:24:47 +00002161 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002162 // scan forward (from the decl location) for argument types.
2163 scanToNextArgument(endBuf);
Craig Topper8ae12032014-05-07 06:21:57 +00002164 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff50d42052007-11-01 13:24:47 +00002165 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2166 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002167 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002168 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002169 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002170 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002171 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002172 InsertText(LessLoc, "/*");
2173 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002174 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002175 startBuf = ++endBuf;
2176 }
2177 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002178 // If the function name is derived from a macro expansion, then the
2179 // argument buffer will not follow the name. Need to speak with Chris.
2180 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002181 startBuf++; // scan forward (from the decl location) for argument types.
2182 startBuf++;
2183 }
Steve Naroff50d42052007-11-01 13:24:47 +00002184 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002185}
2186
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002187void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2188 QualType QT = ND->getType();
2189 const Type* TypePtr = QT->getAs<Type>();
2190 if (!isa<TypeOfExprType>(TypePtr))
2191 return;
2192 while (isa<TypeOfExprType>(TypePtr)) {
2193 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2194 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2195 TypePtr = QT->getAs<Type>();
2196 }
2197 // FIXME. This will not work for multiple declarators; as in:
2198 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002199 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002200 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2201 const char *startBuf = SM->getCharacterData(DeclLoc);
2202 if (ND->getInit()) {
2203 std::string Name(ND->getNameAsString());
2204 TypeAsString += " " + Name + " = ";
2205 Expr *E = ND->getInit();
2206 SourceLocation startLoc;
2207 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2208 startLoc = ECE->getLParenLoc();
2209 else
2210 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002211 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002212 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002213 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002214 }
2215 else {
2216 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002217 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002218 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002219 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002220 }
2221}
2222
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002223// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002224void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002225 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002226 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002227 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002228 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002229 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002230 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002231 SourceLocation(),
2232 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002233 SelGetUidIdent, getFuncType,
2234 nullptr, SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002235}
2236
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002237void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002238 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002239 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002240 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002241 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002242 return;
2243 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002244 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002245}
2246
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002247void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002248 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002249 const char *argPtr = TypeString.c_str();
2250 if (!strchr(argPtr, '^')) {
2251 Str += TypeString;
2252 return;
2253 }
2254 while (*argPtr) {
2255 Str += (*argPtr == '^' ? '*' : *argPtr);
2256 argPtr++;
2257 }
2258}
2259
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002260// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002261void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2262 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002263 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002264 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002265 const char *argPtr = TypeString.c_str();
2266 int paren = 0;
2267 while (*argPtr) {
2268 switch (*argPtr) {
2269 case '(':
2270 Str += *argPtr;
2271 paren++;
2272 break;
2273 case ')':
2274 Str += *argPtr;
2275 paren--;
2276 break;
2277 case '^':
2278 Str += '*';
2279 if (paren == 1)
2280 Str += VD->getNameAsString();
2281 break;
2282 default:
2283 Str += *argPtr;
2284 break;
2285 }
2286 argPtr++;
2287 }
2288}
2289
2290
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002291void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2292 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2293 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2294 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2295 if (!proto)
2296 return;
Alp Toker314cc812014-01-25 16:55:45 +00002297 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002298 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002299 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002300 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002301 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002302 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002303 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002304 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002305 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002306 if (i+1 < numArgs)
2307 FdStr += ", ";
2308 }
2309 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002310 InsertText(FunLocStart, FdStr);
Craig Topper8ae12032014-05-07 06:21:57 +00002311 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002312}
2313
Benjamin Kramer60509af2013-09-09 14:48:42 +00002314// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2315void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2316 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002317 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002318 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002320 QualType argT = Context->getObjCIdType();
2321 assert(!argT.isNull() && "Can't find 'id' type");
2322 ArgTys.push_back(argT);
2323 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002324 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002325 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002326 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002327 SourceLocation(),
2328 SourceLocation(),
2329 msgSendIdent, msgSendType,
Craig Topper8ae12032014-05-07 06:21:57 +00002330 nullptr, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002331}
2332
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002333// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002334void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002335 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002336 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002337 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002338 assert(!argT.isNull() && "Can't find 'id' type");
2339 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002340 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002341 assert(!argT.isNull() && "Can't find 'SEL' type");
2342 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002343 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002344 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002345 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002346 SourceLocation(),
2347 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002348 msgSendIdent, msgSendType,
2349 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002350}
2351
Steve Naroff7fa2f042007-11-15 10:28:18 +00002352// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002353void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002354 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002355 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002356 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002357 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002358 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002359 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2360 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2361 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002362 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002363 assert(!argT.isNull() && "Can't find 'SEL' type");
2364 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002365 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002366 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002367 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002368 SourceLocation(),
2369 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002370 msgSendIdent, msgSendType,
2371 nullptr, SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002372}
2373
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002374// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002375void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002376 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002377 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002378 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002379 assert(!argT.isNull() && "Can't find 'id' type");
2380 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002381 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002382 assert(!argT.isNull() && "Can't find 'SEL' type");
2383 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002384 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002385 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002386 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002387 SourceLocation(),
2388 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002389 msgSendIdent, msgSendType,
2390 nullptr, SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002391}
2392
Mike Stump11289f42009-09-09 15:08:12 +00002393// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002394// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002395void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002396 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002397 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002398 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002399 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002400 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002401 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002402 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2403 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2404 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002405 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002406 assert(!argT.isNull() && "Can't find 'SEL' type");
2407 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002408 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002409 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002410 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002411 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002412 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002413 msgSendIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002414 msgSendType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002415 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002416}
2417
Steve Naroff2e4e3852008-05-08 22:02:18 +00002418// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002419void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002420 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002422 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002423 assert(!argT.isNull() && "Can't find 'id' type");
2424 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002425 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002426 assert(!argT.isNull() && "Can't find 'SEL' type");
2427 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002428 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002429 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002430 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002431 SourceLocation(),
2432 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002433 msgSendIdent, msgSendType,
2434 nullptr, SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002435}
2436
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002437// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002438void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002439 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002440 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002441 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002442 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002443 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002444 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002445 SourceLocation(),
2446 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002447 getClassIdent, getClassType,
2448 nullptr, SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002449}
2450
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002451// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2452void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2453 IdentifierInfo *getSuperClassIdent =
2454 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002455 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002456 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002457 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002458 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002459 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002460 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002461 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002462 getSuperClassIdent,
Craig Topper8ae12032014-05-07 06:21:57 +00002463 getClassType, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002464 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002465}
2466
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002467// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002468void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002469 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002470 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002471 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002472 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002473 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002474 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002475 SourceLocation(),
2476 SourceLocation(),
2477 getClassIdent, getClassType,
Craig Topper8ae12032014-05-07 06:21:57 +00002478 nullptr, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002479}
2480
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002481Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00002482 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffce8e8862008-03-15 00:55:56 +00002483 QualType strType = getConstantStringStructType();
2484
2485 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002486
2487 std::string tmpName = InFileName;
2488 unsigned i;
2489 for (i=0; i < tmpName.length(); i++) {
2490 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002491 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002492 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002493 tmpName[i] = '_';
2494 }
2495 S += tmpName;
2496 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002497 S += utostr(NumObjCStringLiterals++);
2498
Steve Naroff00a31762008-03-27 22:29:16 +00002499 Preamble += "static __NSConstantStringImpl " + S;
2500 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2501 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002502 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002503 std::string prettyBufS;
2504 llvm::raw_string_ostream prettyBuf(prettyBufS);
Craig Topper8ae12032014-05-07 06:21:57 +00002505 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002506 Preamble += prettyBuf.str();
2507 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002508 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002509
2510 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002511 SourceLocation(), &Context->Idents.get(S),
Craig Topper8ae12032014-05-07 06:21:57 +00002512 strType, nullptr, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002513 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002514 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002515 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002516 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002517 VK_RValue, OK_Ordinary,
2518 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002519 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002520 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002521 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002522 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002523 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002524 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002525}
2526
Steve Naroff7fa2f042007-11-15 10:28:18 +00002527// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002528QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002529 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002530 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002531 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002532 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002533 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002534
Steve Naroff7fa2f042007-11-15 10:28:18 +00002535 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002536 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002537 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002538 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002539
Steve Naroff7fa2f042007-11-15 10:28:18 +00002540 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002541 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002542 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002543 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002544 SourceLocation(), nullptr,
2545 FieldTypes[i], nullptr,
2546 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002547 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002548 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregord5058122010-02-11 01:19:42 +00002551 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002552 }
2553 return Context->getTagDeclType(SuperStructDecl);
2554}
2555
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002556QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002557 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002558 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002559 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002560 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002561 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002562
Steve Naroffce8e8862008-03-15 00:55:56 +00002563 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002564 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002565 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002566 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002567 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002568 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002569 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002570 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002571
Steve Naroffce8e8862008-03-15 00:55:56 +00002572 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002573 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002574 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2575 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002576 SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00002577 SourceLocation(), nullptr,
2578 FieldTypes[i], nullptr,
2579 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00002580 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002581 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002582 }
2583
Douglas Gregord5058122010-02-11 01:19:42 +00002584 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002585 }
2586 return Context->getTagDeclType(ConstantStringDecl);
2587}
2588
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002589CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2590 QualType msgSendType,
2591 QualType returnType,
2592 SmallVectorImpl<QualType> &ArgTypes,
2593 SmallVectorImpl<Expr*> &MsgExprs,
2594 ObjCMethodDecl *Method) {
2595 // Create a reference to the objc_msgSend_stret() declaration.
2596 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2597 false, msgSendType,
2598 VK_LValue, SourceLocation());
2599 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2600 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2601 Context->getPointerType(Context->VoidTy),
2602 CK_BitCast, STDRE);
2603 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002604 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2605 Method ? Method->isVariadic()
2606 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002607 castType = Context->getPointerType(castType);
2608 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2609 cast);
2610
2611 // Don't forget the parens to enforce the proper binding.
2612 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2613
2614 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002615 CallExpr *STCE = new (Context) CallExpr(
2616 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002617 return STCE;
2618
2619}
2620
2621
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002622Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2623 SourceLocation StartLoc,
2624 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002625 if (!SelGetUidFunctionDecl)
2626 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002627 if (!MsgSendFunctionDecl)
2628 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002629 if (!MsgSendSuperFunctionDecl)
2630 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002631 if (!MsgSendStretFunctionDecl)
2632 SynthMsgSendStretFunctionDecl();
2633 if (!MsgSendSuperStretFunctionDecl)
2634 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002635 if (!MsgSendFpretFunctionDecl)
2636 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002637 if (!GetClassFunctionDecl)
2638 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002639 if (!GetSuperClassFunctionDecl)
2640 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002641 if (!GetMetaClassFunctionDecl)
2642 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002643
Steve Naroff7fa2f042007-11-15 10:28:18 +00002644 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002645 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2646 // May need to use objc_msgSend_stret() as well.
Craig Topper8ae12032014-05-07 06:21:57 +00002647 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroffd9803712009-04-29 16:37:50 +00002648 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002649 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002650 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002651 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002652 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002653 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002654 }
Mike Stump11289f42009-09-09 15:08:12 +00002655
Steve Naroff574440f2007-10-24 22:48:43 +00002656 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002657 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002658 switch (Exp->getReceiverKind()) {
2659 case ObjCMessageExpr::SuperClass: {
2660 MsgSendFlavor = MsgSendSuperFunctionDecl;
2661 if (MsgSendStretFlavor)
2662 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2663 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002664
Douglas Gregor9a129192010-04-21 00:45:42 +00002665 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002667 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002668
Douglas Gregor9a129192010-04-21 00:45:42 +00002669 // set the receiver to self, the first argument to all methods.
2670 InitExprs.push_back(
2671 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002672 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002673 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002674 false,
John McCall7decc9e2010-11-18 06:31:45 +00002675 Context->getObjCIdType(),
2676 VK_RValue,
2677 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002678 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002679
Douglas Gregor9a129192010-04-21 00:45:42 +00002680 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002681 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002682 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002683 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002684 ClsExprs, StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002685 // (Class)objc_getClass("CurrentClass")
2686 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2687 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002688 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002689 ClsExprs.clear();
2690 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002691 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002692 StartLoc, EndLoc);
Douglas Gregor9a129192010-04-21 00:45:42 +00002693 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2694 // To turn off a warning, type-cast to 'id'
2695 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2696 NoTypeInfoCStyleCastExpr(Context,
2697 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002698 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002699 // struct objc_super
2700 QualType superType = getSuperStructType();
2701 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002702
Francois Pichet0706d202011-09-17 17:15:52 +00002703 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002704 SynthSuperConstructorFunctionDecl();
2705 // Simulate a constructor call...
2706 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002707 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002708 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002709 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002710 superType, VK_LValue,
2711 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002712 // 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 //
John McCalle3027922010-08-25 11:45:40 +00002718 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002719 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002720 VK_RValue, OK_Ordinary,
2721 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002722 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2723 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002724 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002725 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002726 // (struct objc_super) { <exprs from above> }
2727 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002728 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002729 SourceLocation());
2730 TypeSourceInfo *superTInfo
2731 = Context->getTrivialTypeSourceInfo(superType);
2732 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002733 superType, VK_LValue,
2734 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002735 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002736 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002737 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002738 VK_RValue, OK_Ordinary,
2739 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002740 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 MsgExprs.push_back(SuperRep);
2742 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002743 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002744
2745 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002746 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002747 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002748 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002749 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002750 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002751 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002752 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();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002763 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002764
2765 InitExprs.push_back(
2766 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002767 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002768 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002769 false,
John McCall7decc9e2010-11-18 06:31:45 +00002770 Context->getObjCIdType(),
2771 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 ); // set the 'receiver'.
2773
2774 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002775 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002776 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Craig Toppercf2126e2015-10-22 03:13:07 +00002777 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002778 StartLoc, EndLoc);
2779 // (Class)objc_getClass("CurrentClass")
2780 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2781 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002782 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002783 ClsExprs.clear();
2784 ClsExprs.push_back(ArgExpr);
Craig Toppercf2126e2015-10-22 03:13:07 +00002785 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002786 StartLoc, EndLoc);
2787
2788 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2789 // To turn off a warning, type-cast to 'id'
2790 InitExprs.push_back(
2791 // set 'super class', using class_getSuperclass().
2792 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002793 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002794 // struct objc_super
2795 QualType superType = getSuperStructType();
2796 Expr *SuperRep;
2797
Francois Pichet0706d202011-09-17 17:15:52 +00002798 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002799 SynthSuperConstructorFunctionDecl();
2800 // Simulate a constructor call...
2801 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002802 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002803 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002804 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002805 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002806 // The code for super is a little tricky to prevent collision with
2807 // the structure definition in the header. The rewriter has it's own
2808 // internal definition (__rw_objc_super) that is uses. This is why
2809 // we need the cast below. For example:
2810 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2811 //
John McCalle3027922010-08-25 11:45:40 +00002812 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002813 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002814 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002815 SourceLocation());
2816 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2817 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002818 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002819 } else {
2820 // (struct objc_super) { <exprs from above> }
2821 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002822 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002823 SourceLocation());
2824 TypeSourceInfo *superTInfo
2825 = Context->getTrivialTypeSourceInfo(superType);
2826 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002827 superType, VK_RValue, ILE,
2828 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002829 }
2830 MsgExprs.push_back(SuperRep);
2831 break;
2832 }
2833
2834 case ObjCMessageExpr::Instance: {
2835 // Remove all type-casts because it may contain objc-style types; e.g.
2836 // Foo<Proto> *.
2837 Expr *recExpr = Exp->getInstanceReceiver();
2838 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2839 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002840 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2841 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2842 ? CK_BlockPointerToObjCPointerCast
2843 : CK_CPointerToObjCPointerCast;
2844
Douglas Gregor9a129192010-04-21 00:45:42 +00002845 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002846 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002847 MsgExprs.push_back(recExpr);
2848 break;
2849 }
2850 }
2851
Steve Naroffa397efd2007-11-03 11:27:19 +00002852 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002853 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002854 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002855 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Craig Toppercf2126e2015-10-22 03:13:07 +00002856 SelExprs, StartLoc, EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002857 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002858
Steve Naroff574440f2007-10-24 22:48:43 +00002859 // Now push any user supplied arguments.
2860 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002861 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002862 // Make all implicit casts explicit...ICE comes in handy:-)
2863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2864 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002865 QualType type = ICE->getType();
2866 if (needToScanForQualifiers(type))
2867 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002868 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002869 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002870 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002871 CastKind CK;
2872 if (SubExpr->getType()->isIntegralType(*Context) &&
2873 type->isBooleanType()) {
2874 CK = CK_IntegralToBoolean;
2875 } else if (type->isObjCObjectPointerType()) {
2876 if (SubExpr->getType()->isBlockPointerType()) {
2877 CK = CK_BlockPointerToObjCPointerCast;
2878 } else if (SubExpr->getType()->isPointerType()) {
2879 CK = CK_CPointerToObjCPointerCast;
2880 } else {
2881 CK = CK_BitCast;
2882 }
2883 } else {
2884 CK = CK_BitCast;
2885 }
2886
2887 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002888 }
2889 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002890 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002891 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002892 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002893 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002894 CastKind CK;
2895 if (userExpr->getType()->isIntegralType(*Context)) {
2896 CK = CK_IntegralToPointer;
2897 } else if (userExpr->getType()->isBlockPointerType()) {
2898 CK = CK_BlockPointerToObjCPointerCast;
2899 } else if (userExpr->getType()->isPointerType()) {
2900 CK = CK_CPointerToObjCPointerCast;
2901 } else {
2902 CK = CK_BitCast;
2903 }
John McCall97513962010-01-15 18:39:57 +00002904 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002905 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002906 }
Mike Stump11289f42009-09-09 15:08:12 +00002907 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002908 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002909 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2910 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002911 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002912 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002913 }
Steve Narofff36987c2007-11-04 22:37:50 +00002914 // Generate the funky cast.
2915 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002916 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002917 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Steve Narofff36987c2007-11-04 22:37:50 +00002919 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002920 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2921 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2922 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002923 ArgTypes.push_back(Context->getObjCIdType());
2924 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002925 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002926 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002927 for (const auto *PI : OMD->params()) {
2928 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002929 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002930 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002931 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002932 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002933 ArgTypes.push_back(t);
2934 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002935 returnType = Exp->getType();
2936 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002937 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002938 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002939 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002940 }
2941 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002942 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002943
Steve Narofff36987c2007-11-04 22:37:50 +00002944 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002945 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002946 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002947
Mike Stump11289f42009-09-09 15:08:12 +00002948 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002949 // If we don't do this cast, we get the following bizarre warning/note:
2950 // xx.m:13: warning: function called through a non-compatible type
2951 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002952 cast = NoTypeInfoCStyleCastExpr(Context,
2953 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002954 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002955
Steve Narofff36987c2007-11-04 22:37:50 +00002956 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002957 // If we don't have a method decl, force a variadic cast.
2958 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002959 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002960 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002961 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002962 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002963 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002964
2965 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002966 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002967
John McCall9dd450b2009-09-21 23:43:11 +00002968 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002969 CallExpr *CE = new (Context)
2970 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002971 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002972 if (MsgSendStretFlavor) {
2973 // We have the method which returns a struct/union. Must also generate
2974 // call to objc_msgSend_stret and hang both varieties on a conditional
2975 // expression which dictate which one to envoke depending on size of
2976 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002977
2978 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2979 msgSendType, returnType,
2980 ArgTypes, MsgExprs,
2981 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002982
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002983 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002984 UnaryExprOrTypeTraitExpr *sizeofExpr =
2985 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2986 Context->getTrivialTypeSourceInfo(returnType),
2987 Context->getSizeType(), SourceLocation(),
2988 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002989 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2990 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2991 // For X86 it is more complicated and some kind of target specific routine
2992 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002993 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002994 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002995 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2996 llvm::APInt(IntSize, 8),
2997 Context->IntTy,
2998 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00002999 BinaryOperator *lessThanExpr =
3000 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003001 VK_RValue, OK_Ordinary, SourceLocation(),
3002 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003003 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003004 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003005 new (Context) ConditionalOperator(lessThanExpr,
3006 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003007 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003008 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003009 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3010 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003011 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003012 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003013 return ReplacingStmt;
3014}
3015
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003016Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003017 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3018 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003019
Steve Naroff574440f2007-10-24 22:48:43 +00003020 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003021 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003022
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003023 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003024 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003025}
3026
Steve Naroffd9803712009-04-29 16:37:50 +00003027// typedef struct objc_object Protocol;
3028QualType RewriteObjC::getProtocolType() {
3029 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003030 TypeSourceInfo *TInfo
3031 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003032 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003033 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003034 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003035 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003036 }
3037 return Context->getTypeDeclType(ProtocolTypeDecl);
3038}
3039
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003040/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003041/// a synthesized/forward data reference (to the protocol's metadata).
3042/// The forward references (and metadata) are generated in
3043/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003044Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003045 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3046 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003047 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00003048 SourceLocation(), ID, getProtocolType(),
3049 nullptr, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003050 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3051 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003052 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003053 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003054 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003055 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003056 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003057 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003058 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003059 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003060 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003061 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003062
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003063}
3064
Mike Stump11289f42009-09-09 15:08:12 +00003065bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003066 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
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003091/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003092/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003093void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003094 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003095 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003096 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003097 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003098 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003099 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003100 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003101 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003102 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003103 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003104 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003105
Steve Naroffdde78982007-11-14 19:25:57 +00003106 const char *startBuf = SM->getCharacterData(LocStart);
3107 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003108
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003109 // 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.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003111 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003112 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003113 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003114 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003115 return;
3116 }
Mike Stump11289f42009-09-09 15:08:12 +00003117
3118 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003119 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003120 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003121 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003122 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003123 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003124
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003125 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003126 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003127 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003128 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003129 // 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)) {
Mike Stump11289f42009-09-09 15:08:12 +00003145 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003146 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003147 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003148 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003149
Chris Lattnerf5b77512009-02-20 18:18:36 +00003150 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003151 // advance to the end of the referenced protocols.
3152 while (endHeader < cursor && *endHeader != '>') endHeader++;
3153 endHeader++;
3154 }
3155 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003156 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003157 } else {
3158 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003159 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003160 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003161 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003162 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003163 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003164 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003165 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003166 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003167
Steve Naroffdde78982007-11-14 19:25:57 +00003168 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003169 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003170 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003171 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003172 }
3173 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003174
Steve Naroffdde78982007-11-14 19:25:57 +00003175 // Now comment out any visibility specifiers.
3176 while (cursor < endBuf) {
3177 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003178 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003179 // Skip whitespace.
3180 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3181 /*scan*/;
3182
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003183 // FIXME: presence of @public, etc. inside comment results in
3184 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003185 if (!strncmp(cursor, "public", strlen("public")) ||
3186 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003187 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003188 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003189 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003190 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003191 // 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 == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003195 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003196 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003197 cursor = strchr(cursor, '>');
3198 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003199 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003200 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003201 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003202 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003203 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003204 }
Steve Naroffdde78982007-11-14 19:25:57 +00003205 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003206 }
Steve Naroffdde78982007-11-14 19:25:57 +00003207 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003208 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003209 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003210 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003211 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003212 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003213 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003214 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003215 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003216 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003217 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003218 // Mark this struct as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00003219 if (!ObjCSynthesizedStructs.insert(CDecl).second)
David Blaikie83d382b2011-09-23 05:06:16 +00003220 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003221}
3222
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003223//===----------------------------------------------------------------------===//
3224// Meta Data Emission
3225//===----------------------------------------------------------------------===//
3226
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003227
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003228/// RewriteImplementations - This routine rewrites all method implementations
3229/// and emits meta-data.
3230
Steve Narofff8cfd162008-11-13 20:07:04 +00003231void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003232 int ClsDefCount = ClassImplementation.size();
3233 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003234
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003235 // Rewrite implemented methods
3236 for (int i = 0; i < ClsDefCount; i++)
3237 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003238
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003239 for (int i = 0; i < CatDefCount; i++)
3240 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003241}
Mike Stump11289f42009-09-09 15:08:12 +00003242
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003243void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3244 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003245 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003246 assert(BlockByRefDeclNo.count(VD) &&
3247 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003248 if (def)
3249 ResultStr += "struct ";
3250 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003251 "_" + utostr(BlockByRefDeclNo[VD]) ;
3252}
3253
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003254static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3255 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3256 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3257 return false;
3258}
3259
Steve Naroff677ab3a2008-10-27 17:20:55 +00003260std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003261 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003262 std::string Tag) {
3263 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003264 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003265 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003266 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003267 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003268
Steve Naroff677ab3a2008-10-27 17:20:55 +00003269 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003270
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003271 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003272 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003273 // block (to reference imported block decl refs).
3274 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003275 } else if (BD->param_empty()) {
3276 S += "(" + StructRef + " *__cself)";
3277 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003278 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003279 assert(FT && "SynthesizeBlockFunc: No function proto");
3280 S += '(';
3281 // first add the implicit argument.
3282 S += StructRef + " *__cself, ";
3283 std::string ParamStr;
3284 for (BlockDecl::param_iterator AI = BD->param_begin(),
3285 E = BD->param_end(); AI != E; ++AI) {
3286 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003287 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003288 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003289 (void)convertBlockPointerToFunctionPointer(QT);
3290 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003291 S += ParamStr;
3292 }
3293 if (FT->isVariadic()) {
3294 if (!BD->param_empty()) S += ", ";
3295 S += "...";
3296 }
3297 S += ')';
3298 }
3299 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003300
Steve Naroff677ab3a2008-10-27 17:20:55 +00003301 // Create local declarations to avoid rewriting all closure decl ref exprs.
3302 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003303 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003304 E = BlockByRefDecls.end(); I != E; ++I) {
3305 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003306 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003307 std::string TypeString;
3308 RewriteByRefString(TypeString, Name, (*I));
3309 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003310 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003311 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003312 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003313 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003315 E = BlockByCopyDecls.end(); I != E; ++I) {
3316 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003317 // Handle nested closure invocation. For example:
3318 //
3319 // void (^myImportedClosure)(void);
3320 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003321 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003322 // void (^anotherClosure)(void);
3323 // anotherClosure = ^(void) {
3324 // myImportedClosure(); // import and invoke the closure
3325 // };
3326 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003327 if (isTopLevelBlockPointerType((*I)->getType())) {
3328 RewriteBlockPointerTypeVariable(S, (*I));
3329 S += " = (";
3330 RewriteBlockPointerType(S, (*I)->getType());
3331 S += ")";
3332 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3333 }
3334 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003335 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003336 QualType QT = (*I)->getType();
3337 if (HasLocalVariableExternalStorage(*I))
3338 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003339 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003340 S += Name + " = __cself->" +
3341 (*I)->getNameAsString() + "; // bound by copy\n";
3342 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003343 }
3344 std::string RewrittenStr = RewrittenBlockExprs[CE];
3345 const char *cstr = RewrittenStr.c_str();
3346 while (*cstr++ != '{') ;
3347 S += cstr;
3348 S += "\n";
3349 return S;
3350}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003351
Steve Naroff677ab3a2008-10-27 17:20:55 +00003352std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003353 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003354 std::string Tag) {
3355 std::string StructRef = "struct " + Tag;
3356 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003357
Steve Naroff677ab3a2008-10-27 17:20:55 +00003358 S += funcName;
3359 S += "_block_copy_" + utostr(i);
3360 S += "(" + StructRef;
3361 S += "*dst, " + StructRef;
3362 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003363 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003364 S += "_Block_object_assign((void*)&dst->";
Craig Topperc6914d02014-08-25 04:15:02 +00003365 S += VD->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003366 S += ", (void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003367 S += VD->getNameAsString();
3368 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003369 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003370 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003371 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003372 else
3373 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003374 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003375 S += "}\n";
3376
Steve Naroff677ab3a2008-10-27 17:20:55 +00003377 S += "\nstatic void __";
3378 S += funcName;
3379 S += "_block_dispose_" + utostr(i);
3380 S += "(" + StructRef;
3381 S += "*src) {";
Craig Topperc6914d02014-08-25 04:15:02 +00003382 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003383 S += "_Block_object_dispose((void*)src->";
Craig Topperc6914d02014-08-25 04:15:02 +00003384 S += VD->getNameAsString();
3385 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003386 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003387 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003388 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003389 else
3390 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003391 }
Mike Stump11289f42009-09-09 15:08:12 +00003392 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003393 return S;
3394}
3395
Steve Naroff30484702009-12-06 21:14:13 +00003396std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3397 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003398 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003399 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Steve Naroff677ab3a2008-10-27 17:20:55 +00003401 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003402 S += " struct " + Desc;
3403 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003404
Steve Naroff30484702009-12-06 21:14:13 +00003405 Constructor += "(void *fp, "; // Invoke function pointer.
3406 Constructor += "struct " + Desc; // Descriptor pointer.
3407 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003408
Steve Naroff677ab3a2008-10-27 17:20:55 +00003409 if (BlockDeclRefs.size()) {
3410 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003411 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003412 E = BlockByCopyDecls.end(); I != E; ++I) {
3413 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003414 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003415 std::string ArgName = "_" + FieldName;
3416 // Handle nested closure invocation. For example:
3417 //
3418 // void (^myImportedBlock)(void);
3419 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003420 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003421 // void (^anotherBlock)(void);
3422 // anotherBlock = ^(void) {
3423 // myImportedBlock(); // import and invoke the closure
3424 // };
3425 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003426 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003427 S += "struct __block_impl *";
3428 Constructor += ", void *" + ArgName;
3429 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003430 QualType QT = (*I)->getType();
3431 if (HasLocalVariableExternalStorage(*I))
3432 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003433 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3434 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003435 Constructor += ", " + ArgName;
3436 }
3437 S += FieldName + ";\n";
3438 }
3439 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003440 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003441 E = BlockByRefDecls.end(); I != E; ++I) {
3442 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003443 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003444 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003445 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003446 std::string TypeString;
3447 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003448 TypeString += " *";
3449 FieldName = TypeString + FieldName;
3450 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003451 Constructor += ", " + ArgName;
3452 }
3453 S += FieldName + "; // by ref\n";
3454 }
3455 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003456 Constructor += ", int flags=0)";
3457 // Initialize all "by copy" arguments.
3458 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003459 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003460 E = BlockByCopyDecls.end(); I != E; ++I) {
3461 std::string Name = (*I)->getNameAsString();
3462 if (firsTime) {
3463 Constructor += " : ";
3464 firsTime = false;
3465 }
3466 else
3467 Constructor += ", ";
3468 if (isTopLevelBlockPointerType((*I)->getType()))
3469 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3470 else
3471 Constructor += Name + "(_" + Name + ")";
3472 }
3473 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003474 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003475 E = BlockByRefDecls.end(); I != E; ++I) {
3476 std::string Name = (*I)->getNameAsString();
3477 if (firsTime) {
3478 Constructor += " : ";
3479 firsTime = false;
3480 }
3481 else
3482 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003483 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003484 }
3485
3486 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003487 if (GlobalVarDecl)
3488 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3489 else
3490 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003491 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003492
Steve Naroff30484702009-12-06 21:14:13 +00003493 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003494 } else {
3495 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003496 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003497 if (GlobalVarDecl)
3498 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3499 else
3500 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003501 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3502 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003503 }
3504 Constructor += " ";
3505 Constructor += "}\n";
3506 S += Constructor;
3507 S += "};\n";
3508 return S;
3509}
3510
Steve Naroff30484702009-12-06 21:14:13 +00003511std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3512 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003513 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003514 unsigned hasCopy) {
3515 std::string S = "\nstatic struct " + DescTag;
3516
3517 S += " {\n unsigned long reserved;\n";
3518 S += " unsigned long Block_size;\n";
3519 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003520 S += " void (*copy)(struct ";
3521 S += ImplTag; S += "*, struct ";
3522 S += ImplTag; S += "*);\n";
3523
3524 S += " void (*dispose)(struct ";
3525 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003526 }
3527 S += "} ";
3528
3529 S += DescTag + "_DATA = { 0, sizeof(struct ";
3530 S += ImplTag + ")";
3531 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003532 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3533 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003534 }
3535 S += "};\n";
3536 return S;
3537}
3538
Steve Naroff677ab3a2008-10-27 17:20:55 +00003539void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003540 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003541 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003542 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003543 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003544 bool RewriteSC = (GlobalVarDecl &&
3545 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003546 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003547 GlobalVarDecl->getType().getCVRQualifiers());
3548 if (RewriteSC) {
3549 std::string SC(" void __");
3550 SC += GlobalVarDecl->getNameAsString();
3551 SC += "() {}";
3552 InsertText(FunLocStart, SC);
3553 }
3554
Steve Naroff677ab3a2008-10-27 17:20:55 +00003555 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003556 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3557 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003558 // Need to copy-in the inner copied-in variables not actually used in this
3559 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003560 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003561 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003562 ValueDecl *VD = Exp->getDecl();
3563 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003564 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003565 BlockByCopyDeclsPtrSet.insert(VD);
3566 BlockByCopyDecls.push_back(VD);
3567 }
John McCall113bee02012-03-10 09:33:50 +00003568 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003569 BlockByRefDeclsPtrSet.insert(VD);
3570 BlockByRefDecls.push_back(VD);
3571 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003572 // imported objects in the inner blocks not used in the outer
3573 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003574 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003575 VD->getType()->isObjCObjectPointerType() ||
3576 VD->getType()->isBlockPointerType())
3577 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003578 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003579
Daniel Dunbar56df9772010-08-17 22:39:59 +00003580 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3581 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Steve Naroff30484702009-12-06 21:14:13 +00003583 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003584
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003585 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003586
Steve Naroff30484702009-12-06 21:14:13 +00003587 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003588
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003589 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003590
3591 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003592 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003593 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003594 }
Steve Naroff30484702009-12-06 21:14:13 +00003595 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3596 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003597 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003598
Steve Naroff677ab3a2008-10-27 17:20:55 +00003599 BlockDeclRefs.clear();
3600 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003601 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003602 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003603 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003604 ImportedBlockDecls.clear();
3605 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003606 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003607 // Must insert any 'const/volatile/static here. Since it has been
3608 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003609 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003610 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003611 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003612 if (GlobalVarDecl->getType().isConstQualified())
3613 SC += "const ";
3614 if (GlobalVarDecl->getType().isVolatileQualified())
3615 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003616 if (GlobalVarDecl->getType().isRestrictQualified())
3617 SC += "restrict ";
3618 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003619 }
3620
Steve Naroff677ab3a2008-10-27 17:20:55 +00003621 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003622 InnerDeclRefsCount.clear();
3623 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003624 RewrittenBlockExprs.clear();
3625}
3626
3627void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3628 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003629 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003630
Steve Naroff677ab3a2008-10-27 17:20:55 +00003631 SynthesizeBlockLiterals(FunLocStart, FuncName);
3632}
3633
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003634static void BuildUniqueMethodName(std::string &Name,
3635 ObjCMethodDecl *MD) {
3636 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003637 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003638 Name += "__" + MD->getSelector().getAsString();
3639 // Convert colons to underscores.
3640 std::string::size_type loc = 0;
3641 while ((loc = Name.find(":", loc)) != std::string::npos)
3642 Name.replace(loc, 1, "_");
3643}
3644
Steve Naroff677ab3a2008-10-27 17:20:55 +00003645void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003646 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3647 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003648 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003649 std::string FuncName;
3650 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003651 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003652}
3653
3654void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003655 for (Stmt *SubStmt : S->children())
3656 if (SubStmt) {
3657 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003658 GetBlockDeclRefExprs(CBE->getBody());
3659 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003660 GetBlockDeclRefExprs(SubStmt);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003661 }
3662 // Handle specific things.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003663 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003664 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003665 HasLocalVariableExternalStorage(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003666 // FIXME: Handle enums.
Alexey Bataevf841bd92014-12-16 07:00:22 +00003667 BlockDeclRefs.push_back(DRE);
3668
Steve Naroff677ab3a2008-10-27 17:20:55 +00003669 return;
3670}
3671
Craig Topper5603df42013-07-05 19:34:19 +00003672void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3673 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Craig Topper4dd9b432014-08-17 23:49:53 +00003674 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00003675 for (Stmt *SubStmt : S->children())
3676 if (SubStmt) {
3677 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003678 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003679 GetInnerBlockDeclRefExprs(CBE->getBody(),
3680 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003681 InnerContexts);
3682 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003683 else
Benjamin Kramer642f1732015-07-02 21:03:14 +00003684 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003685 }
3686 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003687 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003688 if (DRE->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003689 HasLocalVariableExternalStorage(DRE->getDecl())) {
3690 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCall113bee02012-03-10 09:33:50 +00003691 InnerBlockDeclRefs.push_back(DRE);
Alexey Bataevf841bd92014-12-16 07:00:22 +00003692 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCall113bee02012-03-10 09:33:50 +00003693 if (Var->isFunctionOrMethodVarDecl())
3694 ImportedLocalExternalDecls.insert(Var);
3695 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003696 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003697
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003698 return;
3699}
3700
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003701/// convertFunctionTypeOfBlocks - This routine converts a function type
3702/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003703/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003704/// all block pointers to function pointers.
3705QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3706 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3707 // FTP will be null for closures that don't take arguments.
3708 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003709 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003710 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003711 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003712
3713 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003714 for (auto &I : FTP->param_types()) {
3715 QualType t = I;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003716 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003717 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003718 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003719 ArgTypes.push_back(t);
3720 }
3721 }
3722 QualType FuncType;
3723 // FIXME. Does this work if block takes no argument but has a return type
3724 // which is of block type?
3725 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003726 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003727 else FuncType = QualType(FT, 0);
3728 return FuncType;
3729}
3730
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003731Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003732 // Navigate to relevant type information.
Craig Topper8ae12032014-05-07 06:21:57 +00003733 const BlockPointerType *CPT = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003734
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003735 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003736 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003737 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003738 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003739 }
3740 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3741 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3742 }
3743 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3744 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3745 else if (const ConditionalOperator *CEXPR =
3746 dyn_cast<ConditionalOperator>(BlockExp)) {
3747 Expr *LHSExp = CEXPR->getLHS();
3748 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3749 Expr *RHSExp = CEXPR->getRHS();
3750 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3751 Expr *CONDExp = CEXPR->getCond();
3752 ConditionalOperator *CondExpr =
3753 new (Context) ConditionalOperator(CONDExp,
3754 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003755 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003756 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003757 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003758 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3759 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003760 } else if (const PseudoObjectExpr *POE
3761 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3762 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003763 } else {
3764 assert(1 && "RewriteBlockClass: Bad type");
3765 }
3766 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003767 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003768 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003769 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003770 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003771
Abramo Bagnara6150c882010-05-11 21:36:43 +00003772 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003773 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003774 &Context->Idents.get("__block_impl"));
3775 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003776
Steve Naroff350b6652008-10-30 10:07:53 +00003777 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003778 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003779
Steve Naroff350b6652008-10-30 10:07:53 +00003780 // Push the block argument type.
3781 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003783 for (auto &I : FTP->param_types()) {
3784 QualType t = I;
Steve Naroff350b6652008-10-30 10:07:53 +00003785 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003786 if (!convertBlockPointerToFunctionPointer(t))
3787 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003788 ArgTypes.push_back(t);
3789 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003790 }
Steve Naroff350b6652008-10-30 10:07:53 +00003791 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003792 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003793
Steve Naroff350b6652008-10-30 10:07:53 +00003794 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003795
John McCall97513962010-01-15 18:39:57 +00003796 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003797 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003798 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003799 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003800 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3801 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003802 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003803
Craig Topper8ae12032014-05-07 06:21:57 +00003804 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003805 SourceLocation(),
3806 &Context->Idents.get("FuncPtr"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003807 Context->VoidPtrTy, nullptr,
3808 /*BitWidth=*/nullptr, /*Mutable=*/true,
3809 ICIS_NoInit);
3810 MemberExpr *ME =
3811 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
3812 FD->getType(), VK_LValue, OK_Ordinary);
3813
3814 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3815 CK_BitCast, ME);
3816 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003818 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003819 // Add the implicit argument.
3820 BlkExprs.push_back(BlkCast);
3821 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003822 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003823 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003824 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003825 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003826 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003827 Exp->getType(), VK_RValue,
3828 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003829 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003830}
3831
Steve Naroffd9803712009-04-29 16:37:50 +00003832// We need to return the rewritten expression to handle cases where the
3833// BlockDeclRefExpr is embedded in another expression being rewritten.
3834// For example:
3835//
3836// int main() {
3837// __block Foo *f;
3838// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003839//
Steve Naroffd9803712009-04-29 16:37:50 +00003840// void (^myblock)() = ^() {
3841// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3842// i = 77;
3843// };
3844//}
John McCall113bee02012-03-10 09:33:50 +00003845Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003846 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003847 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003848 ValueDecl *VD = DeclRefExp->getDecl();
Alexey Bataev19acc3d2015-01-12 10:17:46 +00003849 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
Alexey Bataevf841bd92014-12-16 07:00:22 +00003850 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Craig Topper8ae12032014-05-07 06:21:57 +00003851
3852 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003853 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003854 &Context->Idents.get("__forwarding"),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003855 Context->VoidPtrTy, nullptr,
3856 /*BitWidth=*/nullptr, /*Mutable=*/true,
3857 ICIS_NoInit);
3858 MemberExpr *ME = new (Context)
3859 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
3860 FD->getType(), VK_LValue, OK_Ordinary);
3861
3862 StringRef Name = VD->getName();
3863 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003864 &Context->Idents.get(Name),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00003865 Context->VoidPtrTy, nullptr,
3866 /*BitWidth=*/nullptr, /*Mutable=*/true,
3867 ICIS_NoInit);
3868 ME =
3869 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
3870 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3871
3872 // Need parens to enforce precedence.
3873 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3874 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003875 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003876 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003877 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878}
3879
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003880// Rewrites the imported local variable V with external storage
3881// (static, extern, etc.) as *V
3882//
3883Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3884 ValueDecl *VD = DRE->getDecl();
3885 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3886 if (!ImportedLocalExternalDecls.count(Var))
3887 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003888 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3889 VK_LValue, OK_Ordinary,
3890 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003891 // Need parens to enforce precedence.
3892 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3893 Exp);
3894 ReplaceStmt(DRE, PE);
3895 return PE;
3896}
3897
Steve Naroffc989a7b2008-11-03 23:29:32 +00003898void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3899 SourceLocation LocStart = CE->getLParenLoc();
3900 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003901
3902 // Need to avoid trying to rewrite synthesized casts.
3903 if (LocStart.isInvalid())
3904 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003905 // Need to avoid trying to rewrite casts contained in macros.
3906 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3907 return;
Mike Stump11289f42009-09-09 15:08:12 +00003908
Steve Naroff677ab3a2008-10-27 17:20:55 +00003909 const char *startBuf = SM->getCharacterData(LocStart);
3910 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003911 QualType QT = CE->getType();
3912 const Type* TypePtr = QT->getAs<Type>();
3913 if (isa<TypeOfExprType>(TypePtr)) {
3914 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3915 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3916 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003917 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003918 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003919 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003920 return;
3921 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 // advance the location to startArgList.
3923 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003924
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 while (*argPtr++ && (argPtr < endBuf)) {
3926 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003927 case '^':
3928 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003929 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003930 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003931 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003932 }
3933 }
3934 return;
3935}
3936
3937void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3938 SourceLocation DeclLoc = FD->getLocation();
3939 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003940
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941 // We have 1 or more arguments that have closure pointers.
3942 const char *startBuf = SM->getCharacterData(DeclLoc);
3943 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003944
Steve Naroff677ab3a2008-10-27 17:20:55 +00003945 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003946
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947 parenCount++;
3948 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003949 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003950 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00003951
Steve Naroff677ab3a2008-10-27 17:20:55 +00003952 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00003953
Steve Naroff677ab3a2008-10-27 17:20:55 +00003954 while (*argPtr++ && parenCount) {
3955 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003956 case '^':
3957 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003958 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003959 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003960 break;
3961 case '(':
3962 parenCount++;
3963 break;
3964 case ')':
3965 parenCount--;
3966 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 }
3968 }
3969 return;
3970}
3971
3972bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003973 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003974 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003975 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00003976 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003977 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003978 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003979 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00003980 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003981 }
3982 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003983 for (const auto &I : FTP->param_types())
3984 if (isTopLevelBlockPointerType(I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985 return true;
3986 }
3987 return false;
3988}
3989
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00003990bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3991 const FunctionProtoType *FTP;
3992 const PointerType *PT = QT->getAs<PointerType>();
3993 if (PT) {
3994 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3995 } else {
3996 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3997 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3998 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3999 }
4000 if (FTP) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004001 for (const auto &I : FTP->param_types()) {
4002 if (I->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004003 return true;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004004 if (I->isObjCObjectPointerType() &&
4005 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004006 return true;
4007 }
4008
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004009 }
4010 return false;
4011}
4012
Ted Kremenek5a201952009-02-07 01:47:29 +00004013void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4014 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004015 const char *argPtr = strchr(Name, '(');
4016 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004017
Steve Naroff677ab3a2008-10-27 17:20:55 +00004018 LParen = argPtr; // output the start.
4019 argPtr++; // skip past the left paren.
4020 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004021
Steve Naroff677ab3a2008-10-27 17:20:55 +00004022 while (*argPtr && parenCount) {
4023 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004024 case '(': parenCount++; break;
4025 case ')': parenCount--; break;
4026 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004027 }
4028 if (parenCount) argPtr++;
4029 }
4030 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4031 RParen = argPtr; // output the end
4032}
4033
4034void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4035 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4036 RewriteBlockPointerFunctionArgs(FD);
4037 return;
Mike Stump11289f42009-09-09 15:08:12 +00004038 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004039 // Handle Variables and Typedefs.
4040 SourceLocation DeclLoc = ND->getLocation();
4041 QualType DeclT;
4042 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4043 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004044 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004045 DeclT = TDD->getUnderlyingType();
4046 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4047 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004048 else
David Blaikie83d382b2011-09-23 05:06:16 +00004049 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004050
Steve Naroff677ab3a2008-10-27 17:20:55 +00004051 const char *startBuf = SM->getCharacterData(DeclLoc);
4052 const char *endBuf = startBuf;
4053 // scan backward (from the decl location) for the end of the previous decl.
4054 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4055 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004056 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004057 std::string buf;
4058 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004059 // *startBuf != '^' if we are dealing with a pointer to function that
4060 // may take block argument types (which will be handled below).
4061 if (*startBuf == '^') {
4062 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004063 buf = '*';
4064 startBuf++;
4065 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004067 while (*startBuf != ')') {
4068 buf += *startBuf;
4069 startBuf++;
4070 OrigLength++;
4071 }
4072 buf += ')';
4073 OrigLength++;
4074
4075 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4076 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004077 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004078 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 DeclLoc = ND->getLocation();
4080 startBuf = SM->getCharacterData(DeclLoc);
4081 const char *argListBegin, *argListEnd;
4082 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4083 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004084 if (*argListBegin == '^')
4085 buf += '*';
4086 else if (*argListBegin == '<') {
4087 buf += "/*";
4088 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004089 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004090 while (*argListBegin != '>') {
4091 buf += *argListBegin++;
4092 OrigLength++;
4093 }
4094 buf += *argListBegin;
4095 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004097 else
4098 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004099 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004100 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004102 buf += ')';
4103 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004104 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004105 ReplaceText(Start, OrigLength, buf);
4106
Steve Naroff677ab3a2008-10-27 17:20:55 +00004107 return;
4108}
4109
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004110
4111/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4112/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4113/// struct Block_byref_id_object *src) {
4114/// _Block_object_assign (&_dest->object, _src->object,
4115/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4116/// [|BLOCK_FIELD_IS_WEAK]) // object
4117/// _Block_object_assign(&_dest->object, _src->object,
4118/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4119/// [|BLOCK_FIELD_IS_WEAK]) // block
4120/// }
4121/// And:
4122/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4123/// _Block_object_dispose(_src->object,
4124/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4125/// [|BLOCK_FIELD_IS_WEAK]) // object
4126/// _Block_object_dispose(_src->object,
4127/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4128/// [|BLOCK_FIELD_IS_WEAK]) // block
4129/// }
4130
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004131std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4132 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004133 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004134 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004135 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004136 CopyDestroyCache.insert(flag);
4137 S = "static void __Block_byref_id_object_copy_";
4138 S += utostr(flag);
4139 S += "(void *dst, void *src) {\n";
4140
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004141 // offset into the object pointer is computed as:
4142 // void * + void* + int + int + void* + void *
4143 unsigned IntSize =
4144 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4145 unsigned VoidPtrSize =
4146 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4147
Ken Dyckd9c83e62011-04-30 16:08:27 +00004148 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004149 S += " _Block_object_assign((char*)dst + ";
4150 S += utostr(offset);
4151 S += ", *(void * *) ((char*)src + ";
4152 S += utostr(offset);
4153 S += "), ";
4154 S += utostr(flag);
4155 S += ");\n}\n";
4156
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004157 S += "static void __Block_byref_id_object_dispose_";
4158 S += utostr(flag);
4159 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004160 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4161 S += utostr(offset);
4162 S += "), ";
4163 S += utostr(flag);
4164 S += ");\n}\n";
4165 return S;
4166}
4167
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004168/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4169/// the declaration into:
4170/// struct __Block_byref_ND {
4171/// void *__isa; // NULL for everything except __weak pointers
4172/// struct __Block_byref_ND *__forwarding;
4173/// int32_t __flags;
4174/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004175/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4176/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004177/// typex ND;
4178/// };
4179///
4180/// It then replaces declaration of ND variable with:
4181/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4182/// __size=sizeof(struct __Block_byref_ND),
4183/// ND=initializer-if-any};
4184///
4185///
4186void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004187 // Insert declaration for the function in which block literal is
4188 // used.
4189 if (CurFunctionDeclToDeclareForBlock)
4190 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004191 int flag = 0;
4192 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004193 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004194 if (DeclLoc.isInvalid())
4195 // If type location is missing, it is because of missing type (a warning).
4196 // Use variable's location which is good for this case.
4197 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004198 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004199 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004200 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004201 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004202 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004203 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004204 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004205 ByrefType += " {\n";
4206 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004207 RewriteByRefString(ByrefType, Name, ND);
4208 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004209 ByrefType += " int __flags;\n";
4210 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004211 // Add void *__Block_byref_id_object_copy;
4212 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004213 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004214 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004215 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004216 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4217 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004218 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004219
4220 QualType T = Ty;
4221 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004222 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004223
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004224 ByrefType += " " + Name + ";\n";
4225 ByrefType += "};\n";
4226 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004227 SourceLocation FunLocStart;
4228 if (CurFunctionDef)
4229 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4230 else {
4231 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4232 FunLocStart = CurMethodDef->getLocStart();
4233 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004234 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004235 if (Ty.isObjCGCWeak()) {
4236 flag |= BLOCK_FIELD_IS_WEAK;
4237 isa = 1;
4238 }
4239
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004240 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004241 flag = BLOCK_BYREF_CALLER;
4242 QualType Ty = ND->getType();
4243 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4244 if (Ty->isBlockPointerType())
4245 flag |= BLOCK_FIELD_IS_BLOCK;
4246 else
4247 flag |= BLOCK_FIELD_IS_OBJECT;
4248 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004249 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004250 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004251 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004252
4253 // struct __Block_byref_ND ND =
4254 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4255 // initializer-if-any};
Craig Topper8ae12032014-05-07 06:21:57 +00004256 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004257 unsigned flags = 0;
4258 if (HasCopyAndDispose)
4259 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004260 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004261 ByrefType.clear();
4262 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004263 std::string ForwardingCastType("(");
4264 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004265 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004266 ByrefType += " " + Name + " = {(void*)";
4267 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004268 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004269 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004270 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004271 ByrefType += "sizeof(";
4272 RewriteByRefString(ByrefType, Name, ND);
4273 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004274 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004275 ByrefType += ", __Block_byref_id_object_copy_";
4276 ByrefType += utostr(flag);
4277 ByrefType += ", __Block_byref_id_object_dispose_";
4278 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004279 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004280 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004281 unsigned nameSize = Name.size();
4282 // for block or function pointer declaration. Name is aleady
4283 // part of the declaration.
4284 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4285 nameSize = 1;
4286 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004287 }
4288 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004289 SourceLocation startLoc;
4290 Expr *E = ND->getInit();
4291 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4292 startLoc = ECE->getLParenLoc();
4293 else
4294 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004295 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004296 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004297 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004298 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004299 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004300 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004301 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004302 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004303 ByrefType += "sizeof(";
4304 RewriteByRefString(ByrefType, Name, ND);
4305 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004306 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004307 ByrefType += "__Block_byref_id_object_copy_";
4308 ByrefType += utostr(flag);
4309 ByrefType += ", __Block_byref_id_object_dispose_";
4310 ByrefType += utostr(flag);
4311 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004312 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004313 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004314
4315 // Complete the newly synthesized compound expression by inserting a right
4316 // curly brace before the end of the declaration.
4317 // FIXME: This approach avoids rewriting the initializer expression. It
4318 // also assumes there is only one declarator. For example, the following
4319 // isn't currently supported by this routine (in general):
4320 //
4321 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4322 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004323 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4324 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004325 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4326 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004327 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004328
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004329 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004330 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004331 return;
4332}
4333
Mike Stump11289f42009-09-09 15:08:12 +00004334void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004335 // Add initializers for any closure decl refs.
4336 GetBlockDeclRefExprs(Exp->getBody());
4337 if (BlockDeclRefs.size()) {
4338 // Unique all "by copy" declarations.
4339 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004340 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004341 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4342 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4343 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4344 }
4345 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004346 // Unique all "by ref" declarations.
4347 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004348 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004349 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4350 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4351 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4352 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004353 }
4354 // Find any imported blocks...they will need special attention.
4355 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004356 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004357 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004358 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004359 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004360 }
4361}
4362
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004363FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004364 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004365 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004366 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Craig Topper8ae12032014-05-07 06:21:57 +00004367 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004368 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004369}
4370
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004371Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004372 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004373 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004374 Blocks.push_back(Exp);
4375
4376 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004377
4378 // Add inner imported variables now used in current block.
4379 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004380 if (!InnerBlockDeclRefs.empty()) {
4381 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004382 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004383 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004384 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004385 // We need to save the copied-in variables in nested
4386 // blocks because it is needed at the end for some of the API generations.
4387 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004388 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4389 BlockDeclRefs.push_back(Exp);
4390 BlockByCopyDeclsPtrSet.insert(VD);
4391 BlockByCopyDecls.push_back(VD);
4392 }
John McCall113bee02012-03-10 09:33:50 +00004393 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004394 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4395 BlockDeclRefs.push_back(Exp);
4396 BlockByRefDeclsPtrSet.insert(VD);
4397 BlockByRefDecls.push_back(VD);
4398 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004399 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004400 // Find any imported blocks...they will need special attention.
4401 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004402 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004403 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4404 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4405 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004406 }
4407 InnerDeclRefsCount.push_back(countOfInnerDecls);
4408
Steve Narofff4b992a2008-10-28 20:29:00 +00004409 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Steve Narofff4b992a2008-10-28 20:29:00 +00004411 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004412 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004413 else if (CurMethodDef)
4414 BuildUniqueMethodName(FuncName, CurMethodDef);
4415 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004416 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004417
Steve Narofff4b992a2008-10-28 20:29:00 +00004418 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004419
Steve Narofff4b992a2008-10-28 20:29:00 +00004420 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4421 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004422
Steve Narofff4b992a2008-10-28 20:29:00 +00004423 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004424 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4425 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004426
4427 FunctionDecl *FD;
4428 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004429
Benjamin Kramer60509af2013-09-09 14:48:42 +00004430 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004431 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004432 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004433 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004434
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004435 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004436
Steve Naroffe2514232008-10-29 21:23:59 +00004437 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004438 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004439 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4440 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004441 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004442 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004443 InitExprs.push_back(castExpr);
4444
Steve Naroff30484702009-12-06 21:14:13 +00004445 // Initialize the block descriptor.
4446 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004447
Abramo Bagnaradff19302011-03-08 08:55:46 +00004448 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4449 SourceLocation(), SourceLocation(),
4450 &Context->Idents.get(DescData.c_str()),
Craig Topper8ae12032014-05-07 06:21:57 +00004451 Context->VoidPtrTy, nullptr,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004452 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004453 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004454 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004455 Context->VoidPtrTy,
4456 VK_LValue,
4457 SourceLocation()),
4458 UO_AddrOf,
4459 Context->getPointerType(Context->VoidPtrTy),
4460 VK_RValue, OK_Ordinary,
4461 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004462 InitExprs.push_back(DescRefExpr);
4463
Steve Narofff4b992a2008-10-28 20:29:00 +00004464 // Add initializers for any closure decl refs.
4465 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004466 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004467 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004468 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004469 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004470 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004471 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004472 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004473 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004474 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004475 if (HasLocalVariableExternalStorage(*I)) {
4476 QualType QT = (*I)->getType();
4477 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004478 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4479 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004480 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004481 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004482 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004483 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004484 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004485 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004486 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004487 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004488 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004489 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004490 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004491 if (HasLocalVariableExternalStorage(*I)) {
4492 QualType QT = (*I)->getType();
4493 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004494 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4495 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004496 }
4497
Steve Narofff4b992a2008-10-28 20:29:00 +00004498 }
Mike Stump11289f42009-09-09 15:08:12 +00004499 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004500 }
4501 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004502 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004503 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004504 ValueDecl *ND = (*I);
4505 std::string Name(ND->getNameAsString());
4506 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004507 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004508 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4509 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004510 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004511 SourceLocation(), SourceLocation(),
4512 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004513 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4514 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4515
Daniel Dunbar56df9772010-08-17 22:39:59 +00004516 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004517 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004518 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004519 bool isNestedCapturedVar = false;
4520 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00004521 for (const auto &CI : block->captures()) {
4522 const VarDecl *variable = CI.getVariable();
4523 if (variable == ND && CI.isNested()) {
4524 assert (CI.isByRef() &&
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004525 "SynthBlockInitExpr - captured block variable is not byref");
4526 isNestedCapturedVar = true;
4527 break;
4528 }
4529 }
4530 // captured nested byref variable has its address passed. Do not take
4531 // its address again.
4532 if (!isNestedCapturedVar)
4533 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004534 Context->getPointerType(Exp->getType()),
4535 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004536 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004537 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004538 }
4539 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004540 if (ImportedBlockDecls.size()) {
4541 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4542 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004543 unsigned IntSize =
4544 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004545 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4546 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004547 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004548 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004549 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004550 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004551 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004552 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004553 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004554 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004555 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004556 BlockDeclRefs.clear();
4557 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004558 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004559 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004560 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004561 ImportedBlockDecls.clear();
4562 return NewRep;
4563}
4564
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004565bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4566 if (const ObjCForCollectionStmt * CS =
4567 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4568 return CS->getElement() == DS;
4569 return false;
4570}
4571
Steve Narofff4b992a2008-10-28 20:29:00 +00004572//===----------------------------------------------------------------------===//
4573// Function Body / Expression rewriting
4574//===----------------------------------------------------------------------===//
4575
4576Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004577 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004578 isa<DoStmt>(S) || isa<ForStmt>(S))
4579 Stmts.push_back(S);
4580 else if (isa<ObjCForCollectionStmt>(S)) {
4581 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004582 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
John McCallfe96e0b2011-11-06 09:01:30 +00004585 // Pseudo-object operations and ivar references need special
4586 // treatment because we're going to recursively rewrite them.
4587 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4588 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4589 return RewritePropertyOrImplicitSetter(PseudoOp);
4590 } else {
4591 return RewritePropertyOrImplicitGetter(PseudoOp);
4592 }
4593 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4594 return RewriteObjCIvarRefExpr(IvarRefExpr);
4595 }
4596
Steve Narofff4b992a2008-10-28 20:29:00 +00004597 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004598
Steve Narofff4b992a2008-10-28 20:29:00 +00004599 // Perform a bottom up rewrite of all children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00004600 for (Stmt *&childStmt : S->children())
4601 if (childStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004602 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004603 if (newStmt) {
Benjamin Kramer642f1732015-07-02 21:03:14 +00004604 childStmt = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004605 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004606 }
Mike Stump11289f42009-09-09 15:08:12 +00004607
Steve Narofff4b992a2008-10-28 20:29:00 +00004608 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004609 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004610 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4611 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004612 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004613 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004614 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004615 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004616 Stmt *SaveCurrentBody = CurrentBody;
4617 CurrentBody = BE->getBody();
Craig Topper8ae12032014-05-07 06:21:57 +00004618 PropParentMap = nullptr;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004619 // block literal on rhs of a property-dot-sytax assignment
4620 // must be replaced by its synthesize ast so getRewrittenText
4621 // works as expected. In this case, what actually ends up on RHS
4622 // is the blockTranscribed which is the helper function for the
4623 // block literal; as in: self.c = ^() {[ace ARR];};
4624 bool saveDisableReplaceStmt = DisableReplaceStmt;
4625 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004626 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004627 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004628 CurrentBody = SaveCurrentBody;
Craig Topper8ae12032014-05-07 06:21:57 +00004629 PropParentMap = nullptr;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004630 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004631 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004632 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004633 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004634
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004635 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4636
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004638 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004639 return blockTranscribed;
4640 }
4641 // Handle specific things.
4642 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4643 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004644
Steve Narofff4b992a2008-10-28 20:29:00 +00004645 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4646 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004647
Steve Narofff4b992a2008-10-28 20:29:00 +00004648 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4649 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004652#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004653 // Before we rewrite it, put the original message expression in a comment.
4654 SourceLocation startLoc = MessExpr->getLocStart();
4655 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004656
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 const char *startBuf = SM->getCharacterData(startLoc);
4658 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004659
Steve Narofff4b992a2008-10-28 20:29:00 +00004660 std::string messString;
4661 messString += "// ";
4662 messString.append(startBuf, endBuf-startBuf+1);
4663 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004664
4665 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004666 // InsertText(clang::SourceLocation, char const*, unsigned int).
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004667 // InsertText(startLoc, messString);
Steve Narofff4b992a2008-10-28 20:29:00 +00004668 // Tried this, but it didn't work either...
4669 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004670#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004671 return RewriteMessageExpr(MessExpr);
4672 }
Mike Stump11289f42009-09-09 15:08:12 +00004673
Steve Narofff4b992a2008-10-28 20:29:00 +00004674 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4675 return RewriteObjCTryStmt(StmtTry);
4676
4677 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4678 return RewriteObjCSynchronizedStmt(StmtTry);
4679
4680 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4681 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004682
Steve Narofff4b992a2008-10-28 20:29:00 +00004683 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4684 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004685
4686 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004688 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004689 OrigStmtRange.getEnd());
4690 if (BreakStmt *StmtBreakStmt =
4691 dyn_cast<BreakStmt>(S))
4692 return RewriteBreakStmt(StmtBreakStmt);
4693 if (ContinueStmt *StmtContinueStmt =
4694 dyn_cast<ContinueStmt>(S))
4695 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004696
4697 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004698 // and cast exprs.
4699 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4700 // FIXME: What we're doing here is modifying the type-specifier that
4701 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004702 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004703 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4704 // the context of an ObjCForCollectionStmt. For example:
4705 // NSArray *someArray;
4706 // for (id <FooProtocol> index in someArray) ;
4707 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4708 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004709 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004710 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004711
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 // Blocks rewrite rules.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004713 for (auto *SD : DS->decls()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004715 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004716 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004717 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004718 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004719 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004720 if (VD->hasAttr<BlocksAttr>()) {
4721 static unsigned uniqueByrefDeclCount = 0;
4722 assert(!BlockByRefDeclNo.count(ND) &&
4723 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4724 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004725 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004726 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004727 else
4728 RewriteTypeOfDecl(VD);
4729 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004730 }
Richard Smithdda56e42011-04-15 14:24:37 +00004731 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004732 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004733 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004734 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004735 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4736 }
4737 }
4738 }
Mike Stump11289f42009-09-09 15:08:12 +00004739
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4741 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004742
4743 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004744 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4745 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004746 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4747 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004748 && "Statement stack mismatch");
4749 Stmts.pop_back();
4750 }
4751 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004752 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4753 ValueDecl *VD = DRE->getDecl();
4754 if (VD->hasAttr<BlocksAttr>())
4755 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004756 if (HasLocalVariableExternalStorage(VD))
4757 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004758 }
4759
Steve Narofff4b992a2008-10-28 20:29:00 +00004760 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004761 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004762 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004763 ReplaceStmt(S, BlockCall);
4764 return BlockCall;
4765 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004767 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004768 RewriteCastExpr(CE);
4769 }
4770#if 0
4771 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004772 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4773 ICE->getSubExpr(),
4774 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004775 // Get the new text.
4776 std::string SStr;
4777 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004778 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 const std::string &Str = Buf.str();
4780
4781 printf("CAST = %s\n", &Str[0]);
Craig Toppera2a8d9c2015-10-22 03:13:10 +00004782 InsertText(ICE->getSubExpr()->getLocStart(), Str);
Steve Narofff4b992a2008-10-28 20:29:00 +00004783 delete S;
4784 return Replacement;
4785 }
4786#endif
4787 // Return this stmt unmodified.
4788 return S;
4789}
4790
Steve Naroffe70a52a2009-12-05 15:55:59 +00004791void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004792 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004793 if (isTopLevelBlockPointerType(FD->getType()))
4794 RewriteBlockPointerDecl(FD);
4795 if (FD->getType()->isObjCQualifiedIdType() ||
4796 FD->getType()->isObjCQualifiedInterfaceType())
4797 RewriteObjCQualifiedInterfaceTypes(FD);
4798 }
4799}
4800
Steve Narofff4b992a2008-10-28 20:29:00 +00004801/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4802/// main file of the input.
4803void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004804 switch (D->getKind()) {
4805 case Decl::Function: {
4806 FunctionDecl *FD = cast<FunctionDecl>(D);
4807 if (FD->isOverloadedOperator())
4808 return;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004810 // Since function prototypes don't have ParmDecl's, we check the function
4811 // prototype. This enables us to rewrite function declarations and
4812 // definitions using the same code.
4813 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004814
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004815 if (!FD->isThisDeclarationADefinition())
4816 break;
4817
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004818 // FIXME: If this should support Obj-C++, support CXXTryStmt
4819 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4820 CurFunctionDef = FD;
4821 CurFunctionDeclToDeclareForBlock = FD;
4822 CurrentBody = Body;
4823 Body =
4824 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4825 FD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004826 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004827 if (PropParentMap) {
4828 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004829 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004830 }
4831 // This synthesizes and inserts the block "impl" struct, invoke function,
4832 // and any copy/dispose helper functions.
4833 InsertBlockLiteralsWithinFunction(FD);
Craig Topper8ae12032014-05-07 06:21:57 +00004834 CurFunctionDef = nullptr;
4835 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004836 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004837 break;
Mike Stump11289f42009-09-09 15:08:12 +00004838 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004839 case Decl::ObjCMethod: {
4840 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4841 if (CompoundStmt *Body = MD->getCompoundBody()) {
4842 CurMethodDef = MD;
4843 CurrentBody = Body;
4844 Body =
4845 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4846 MD->setBody(Body);
Craig Topper8ae12032014-05-07 06:21:57 +00004847 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004848 if (PropParentMap) {
4849 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004850 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004851 }
4852 InsertBlockLiteralsWithinMethod(MD);
Craig Topper8ae12032014-05-07 06:21:57 +00004853 CurMethodDef = nullptr;
Steve Naroff1042ff32008-12-08 16:43:47 +00004854 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004855 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004856 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004857 case Decl::ObjCImplementation: {
4858 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4859 ClassImplementation.push_back(CI);
4860 break;
4861 }
4862 case Decl::ObjCCategoryImpl: {
4863 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4864 CategoryImplementation.push_back(CI);
4865 break;
4866 }
4867 case Decl::Var: {
4868 VarDecl *VD = cast<VarDecl>(D);
4869 RewriteObjCQualifiedInterfaceTypes(VD);
4870 if (isTopLevelBlockPointerType(VD->getType()))
4871 RewriteBlockPointerDecl(VD);
4872 else if (VD->getType()->isFunctionPointerType()) {
4873 CheckFunctionPointerDecl(VD->getType(), VD);
4874 if (VD->getInit()) {
4875 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4876 RewriteCastExpr(CE);
4877 }
4878 }
4879 } else if (VD->getType()->isRecordType()) {
4880 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4881 if (RD->isCompleteDefinition())
4882 RewriteRecordBody(RD);
4883 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004884 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004885 GlobalVarDecl = VD;
4886 CurrentBody = VD->getInit();
4887 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Craig Topper8ae12032014-05-07 06:21:57 +00004888 CurrentBody = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004889 if (PropParentMap) {
4890 delete PropParentMap;
Craig Topper8ae12032014-05-07 06:21:57 +00004891 PropParentMap = nullptr;
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004892 }
4893 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Craig Topper8ae12032014-05-07 06:21:57 +00004894 GlobalVarDecl = nullptr;
4895
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004896 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004897 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004898 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004899 }
4900 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004901 break;
4902 }
4903 case Decl::TypeAlias:
4904 case Decl::Typedef: {
4905 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4906 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4907 RewriteBlockPointerDecl(TD);
4908 else if (TD->getUnderlyingType()->isFunctionPointerType())
4909 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4910 }
4911 break;
4912 }
4913 case Decl::CXXRecord:
4914 case Decl::Record: {
4915 RecordDecl *RD = cast<RecordDecl>(D);
4916 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004917 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004918 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004919 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004920 default:
4921 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 }
4923 // Nothing yet.
4924}
4925
Chris Lattnercf169832009-03-28 04:11:33 +00004926void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004927 if (Diags.hasErrorOccurred())
4928 return;
Mike Stump11289f42009-09-09 15:08:12 +00004929
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004931
Steve Naroffd9803712009-04-29 16:37:50 +00004932 // Here's a great place to add any extra declarations that may be needed.
4933 // Write out meta data for each @protocol(<expr>).
Craig Topperc6914d02014-08-25 04:15:02 +00004934 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4935 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
Steve Naroffd9803712009-04-29 16:37:50 +00004936
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004937 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004938 if (ClassImplementation.size() || CategoryImplementation.size())
4939 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004940
Steve Narofff4b992a2008-10-28 20:29:00 +00004941 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4942 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004943 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 Rewrite.getRewriteBufferFor(MainFileID)) {
4945 //printf("Changed:\n");
4946 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4947 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004948 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00004949 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004950
Steve Naroffd9803712009-04-29 16:37:50 +00004951 if (ClassImplementation.size() || CategoryImplementation.size() ||
4952 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004953 // Rewrite Objective-c meta data*
4954 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00004955 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004956 // Emit metadata.
4957 *OutFile << ResultStr;
4958 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004959 OutFile->flush();
4960}
Fariborz Jahanian83077422011-12-08 18:25:15 +00004961
4962void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4963 InitializeCommon(context);
4964
4965 // declaring objc_selector outside the parameter list removes a silly
4966 // scope related warning...
4967 if (IsHeader)
4968 Preamble = "#pragma once\n";
4969 Preamble += "struct objc_selector; struct objc_class;\n";
4970 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4971 Preamble += "struct objc_object *superClass; ";
4972 if (LangOpts.MicrosoftExt) {
4973 // Add a constructor for creating temporary objects.
4974 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4975 ": ";
4976 Preamble += "object(o), superClass(s) {} ";
4977 }
4978 Preamble += "};\n";
4979 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4980 Preamble += "typedef struct objc_object Protocol;\n";
4981 Preamble += "#define _REWRITER_typedef_Protocol\n";
4982 Preamble += "#endif\n";
4983 if (LangOpts.MicrosoftExt) {
4984 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4985 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4986 } else
4987 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4988 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4989 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4990 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4991 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4992 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4993 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4994 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4995 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4996 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4997 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4998 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4999 Preamble += "(const char *);\n";
5000 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5001 Preamble += "(struct objc_class *);\n";
5002 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5003 Preamble += "(const char *);\n";
5004 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5005 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5006 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5007 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5008 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5009 Preamble += "(struct objc_class *, struct objc_object *);\n";
5010 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005011 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5012 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005013 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5014 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5015 Preamble += "struct __objcFastEnumerationState {\n\t";
5016 Preamble += "unsigned long state;\n\t";
5017 Preamble += "void **itemsPtr;\n\t";
5018 Preamble += "unsigned long *mutationsPtr;\n\t";
5019 Preamble += "unsigned long extra[5];\n};\n";
5020 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5021 Preamble += "#define __FASTENUMERATIONSTATE\n";
5022 Preamble += "#endif\n";
5023 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5024 Preamble += "struct __NSConstantStringImpl {\n";
5025 Preamble += " int *isa;\n";
5026 Preamble += " int flags;\n";
5027 Preamble += " char *str;\n";
5028 Preamble += " long length;\n";
5029 Preamble += "};\n";
5030 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5031 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5032 Preamble += "#else\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5034 Preamble += "#endif\n";
5035 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5036 Preamble += "#endif\n";
5037 // Blocks preamble.
5038 Preamble += "#ifndef BLOCK_IMPL\n";
5039 Preamble += "#define BLOCK_IMPL\n";
5040 Preamble += "struct __block_impl {\n";
5041 Preamble += " void *isa;\n";
5042 Preamble += " int Flags;\n";
5043 Preamble += " int Reserved;\n";
5044 Preamble += " void *FuncPtr;\n";
5045 Preamble += "};\n";
5046 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5047 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5048 Preamble += "extern \"C\" __declspec(dllexport) "
5049 "void _Block_object_assign(void *, const void *, const int);\n";
5050 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5051 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5052 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5053 Preamble += "#else\n";
5054 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5055 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5056 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5057 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5058 Preamble += "#endif\n";
5059 Preamble += "#endif\n";
5060 if (LangOpts.MicrosoftExt) {
5061 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5062 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5063 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5064 Preamble += "#define __attribute__(X)\n";
5065 Preamble += "#endif\n";
5066 Preamble += "#define __weak\n";
5067 }
5068 else {
5069 Preamble += "#define __block\n";
5070 Preamble += "#define __weak\n";
5071 }
5072 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5073 // as this avoids warning in any 64bit/32bit compilation model.
5074 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5075}
5076
5077/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5078/// ivar offset.
5079void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5080 std::string &Result) {
5081 if (ivar->isBitField()) {
5082 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5083 // place all bitfields at offset 0.
5084 Result += "0";
5085 } else {
5086 Result += "__OFFSETOFIVAR__(struct ";
5087 Result += ivar->getContainingInterface()->getNameAsString();
5088 if (LangOpts.MicrosoftExt)
5089 Result += "_IMPL";
5090 Result += ", ";
5091 Result += ivar->getNameAsString();
5092 Result += ")";
5093 }
5094}
5095
5096/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5097void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5098 ObjCProtocolDecl *PDecl, StringRef prefix,
5099 StringRef ClassName, std::string &Result) {
5100 static bool objc_protocol_methods = false;
5101
5102 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005103 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005104 /* struct protocol_methods {
5105 SEL _cmd;
5106 char *method_types;
5107 }
5108 */
5109 Result += "\nstruct _protocol_methods {\n";
5110 Result += "\tstruct objc_selector *_cmd;\n";
5111 Result += "\tchar *method_types;\n";
5112 Result += "};\n";
5113
5114 objc_protocol_methods = true;
5115 }
5116 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005117 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005118 return;
5119
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005120 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5121 PDecl = Def;
5122
Fariborz Jahanian83077422011-12-08 18:25:15 +00005123 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5124 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5125 PDecl->instmeth_end());
5126 /* struct _objc_protocol_method_list {
5127 int protocol_method_count;
5128 struct protocol_methods protocols[];
5129 }
5130 */
5131 Result += "\nstatic struct {\n";
5132 Result += "\tint protocol_method_count;\n";
5133 Result += "\tstruct _protocol_methods protocol_methods[";
5134 Result += utostr(NumMethods);
5135 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5136 Result += PDecl->getNameAsString();
5137 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5138 "{\n\t" + utostr(NumMethods) + "\n";
5139
5140 // Output instance methods declared in this protocol.
5141 for (ObjCProtocolDecl::instmeth_iterator
5142 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5143 I != E; ++I) {
5144 if (I == PDecl->instmeth_begin())
5145 Result += "\t ,{{(struct objc_selector *)\"";
5146 else
5147 Result += "\t ,{(struct objc_selector *)\"";
5148 Result += (*I)->getSelector().getAsString();
5149 std::string MethodTypeString;
5150 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5151 Result += "\", \"";
5152 Result += MethodTypeString;
5153 Result += "\"}\n";
5154 }
5155 Result += "\t }\n};\n";
5156 }
5157
5158 // Output class methods declared in this protocol.
5159 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5160 PDecl->classmeth_end());
5161 if (NumMethods > 0) {
5162 /* struct _objc_protocol_method_list {
5163 int protocol_method_count;
5164 struct protocol_methods protocols[];
5165 }
5166 */
5167 Result += "\nstatic struct {\n";
5168 Result += "\tint protocol_method_count;\n";
5169 Result += "\tstruct _protocol_methods protocol_methods[";
5170 Result += utostr(NumMethods);
5171 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5172 Result += PDecl->getNameAsString();
5173 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5174 "{\n\t";
5175 Result += utostr(NumMethods);
5176 Result += "\n";
5177
5178 // Output instance methods declared in this protocol.
5179 for (ObjCProtocolDecl::classmeth_iterator
5180 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5181 I != E; ++I) {
5182 if (I == PDecl->classmeth_begin())
5183 Result += "\t ,{{(struct objc_selector *)\"";
5184 else
5185 Result += "\t ,{(struct objc_selector *)\"";
5186 Result += (*I)->getSelector().getAsString();
5187 std::string MethodTypeString;
5188 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5189 Result += "\", \"";
5190 Result += MethodTypeString;
5191 Result += "\"}\n";
5192 }
5193 Result += "\t }\n};\n";
5194 }
5195
5196 // Output:
5197 /* struct _objc_protocol {
5198 // Objective-C 1.0 extensions
5199 struct _objc_protocol_extension *isa;
5200 char *protocol_name;
5201 struct _objc_protocol **protocol_list;
5202 struct _objc_protocol_method_list *instance_methods;
5203 struct _objc_protocol_method_list *class_methods;
5204 };
5205 */
5206 static bool objc_protocol = false;
5207 if (!objc_protocol) {
5208 Result += "\nstruct _objc_protocol {\n";
5209 Result += "\tstruct _objc_protocol_extension *isa;\n";
5210 Result += "\tchar *protocol_name;\n";
5211 Result += "\tstruct _objc_protocol **protocol_list;\n";
5212 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5213 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5214 Result += "};\n";
5215
5216 objc_protocol = true;
5217 }
5218
5219 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5220 Result += PDecl->getNameAsString();
5221 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5222 "{\n\t0, \"";
5223 Result += PDecl->getNameAsString();
5224 Result += "\", 0, ";
5225 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5226 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5227 Result += PDecl->getNameAsString();
5228 Result += ", ";
5229 }
5230 else
5231 Result += "0, ";
5232 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5233 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5234 Result += PDecl->getNameAsString();
5235 Result += "\n";
5236 }
5237 else
5238 Result += "0\n";
5239 Result += "};\n";
5240
5241 // Mark this protocol as having been generated.
David Blaikie82e95a32014-11-19 07:49:47 +00005242 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005243 llvm_unreachable("protocol already synthesized");
5244
5245}
5246
5247void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5248 const ObjCList<ObjCProtocolDecl> &Protocols,
5249 StringRef prefix, StringRef ClassName,
5250 std::string &Result) {
5251 if (Protocols.empty()) return;
5252
5253 for (unsigned i = 0; i != Protocols.size(); i++)
5254 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5255
5256 // Output the top lovel protocol meta-data for the class.
5257 /* struct _objc_protocol_list {
5258 struct _objc_protocol_list *next;
5259 int protocol_count;
5260 struct _objc_protocol *class_protocols[];
5261 }
5262 */
5263 Result += "\nstatic struct {\n";
5264 Result += "\tstruct _objc_protocol_list *next;\n";
5265 Result += "\tint protocol_count;\n";
5266 Result += "\tstruct _objc_protocol *class_protocols[";
5267 Result += utostr(Protocols.size());
5268 Result += "];\n} _OBJC_";
5269 Result += prefix;
5270 Result += "_PROTOCOLS_";
5271 Result += ClassName;
5272 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5273 "{\n\t0, ";
5274 Result += utostr(Protocols.size());
5275 Result += "\n";
5276
5277 Result += "\t,{&_OBJC_PROTOCOL_";
5278 Result += Protocols[0]->getNameAsString();
5279 Result += " \n";
5280
5281 for (unsigned i = 1; i != Protocols.size(); i++) {
5282 Result += "\t ,&_OBJC_PROTOCOL_";
5283 Result += Protocols[i]->getNameAsString();
5284 Result += "\n";
5285 }
5286 Result += "\t }\n};\n";
5287}
5288
5289void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5290 std::string &Result) {
5291 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5292
5293 // Explicitly declared @interface's are already synthesized.
5294 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005295 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005296 // produce correct synthesis as yet.
5297 RewriteObjCInternalStruct(CDecl, Result);
5298 }
5299
5300 // Build _objc_ivar_list metadata for classes ivars if needed
5301 unsigned NumIvars = !IDecl->ivar_empty()
5302 ? IDecl->ivar_size()
5303 : (CDecl ? CDecl->ivar_size() : 0);
5304 if (NumIvars > 0) {
5305 static bool objc_ivar = false;
5306 if (!objc_ivar) {
5307 /* struct _objc_ivar {
5308 char *ivar_name;
5309 char *ivar_type;
5310 int ivar_offset;
5311 };
5312 */
5313 Result += "\nstruct _objc_ivar {\n";
5314 Result += "\tchar *ivar_name;\n";
5315 Result += "\tchar *ivar_type;\n";
5316 Result += "\tint ivar_offset;\n";
5317 Result += "};\n";
5318
5319 objc_ivar = true;
5320 }
5321
5322 /* struct {
5323 int ivar_count;
5324 struct _objc_ivar ivar_list[nIvars];
5325 };
5326 */
5327 Result += "\nstatic struct {\n";
5328 Result += "\tint ivar_count;\n";
5329 Result += "\tstruct _objc_ivar ivar_list[";
5330 Result += utostr(NumIvars);
5331 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5332 Result += IDecl->getNameAsString();
5333 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5334 "{\n\t";
5335 Result += utostr(NumIvars);
5336 Result += "\n";
5337
5338 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5339 SmallVector<ObjCIvarDecl *, 8> IVars;
5340 if (!IDecl->ivar_empty()) {
Aaron Ballmand6d25de2014-03-14 15:16:45 +00005341 for (auto *IV : IDecl->ivars())
5342 IVars.push_back(IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005343 IVI = IDecl->ivar_begin();
5344 IVE = IDecl->ivar_end();
5345 } else {
5346 IVI = CDecl->ivar_begin();
5347 IVE = CDecl->ivar_end();
5348 }
5349 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005350 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005351 Result += "\", \"";
5352 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005353 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005354 QuoteDoublequotes(TmpString, StrEncoding);
5355 Result += StrEncoding;
5356 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005357 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005358 Result += "}\n";
5359 for (++IVI; IVI != IVE; ++IVI) {
5360 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005361 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005362 Result += "\", \"";
5363 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005364 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005365 QuoteDoublequotes(TmpString, StrEncoding);
5366 Result += StrEncoding;
5367 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005368 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005369 Result += "}\n";
5370 }
5371
5372 Result += "\t }\n};\n";
5373 }
5374
5375 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005376 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005377
5378 // If any of our property implementations have associated getters or
5379 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005380 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005381 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005382 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005383 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005384 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005385 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005386 if (!PD)
5387 continue;
5388 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5389 if (!Getter->isDefined())
5390 InstanceMethods.push_back(Getter);
5391 if (PD->isReadOnly())
5392 continue;
5393 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5394 if (!Setter->isDefined())
5395 InstanceMethods.push_back(Setter);
5396 }
5397 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5398 true, "", IDecl->getName(), Result);
5399
5400 // Build _objc_method_list for class's class methods if needed
5401 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5402 false, "", IDecl->getName(), Result);
5403
5404 // Protocols referenced in class declaration?
5405 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5406 "CLASS", CDecl->getName(), Result);
5407
5408 // Declaration of class/meta-class metadata
5409 /* struct _objc_class {
5410 struct _objc_class *isa; // or const char *root_class_name when metadata
5411 const char *super_class_name;
5412 char *name;
5413 long version;
5414 long info;
5415 long instance_size;
5416 struct _objc_ivar_list *ivars;
5417 struct _objc_method_list *methods;
5418 struct objc_cache *cache;
5419 struct objc_protocol_list *protocols;
5420 const char *ivar_layout;
5421 struct _objc_class_ext *ext;
5422 };
5423 */
5424 static bool objc_class = false;
5425 if (!objc_class) {
5426 Result += "\nstruct _objc_class {\n";
5427 Result += "\tstruct _objc_class *isa;\n";
5428 Result += "\tconst char *super_class_name;\n";
5429 Result += "\tchar *name;\n";
5430 Result += "\tlong version;\n";
5431 Result += "\tlong info;\n";
5432 Result += "\tlong instance_size;\n";
5433 Result += "\tstruct _objc_ivar_list *ivars;\n";
5434 Result += "\tstruct _objc_method_list *methods;\n";
5435 Result += "\tstruct objc_cache *cache;\n";
5436 Result += "\tstruct _objc_protocol_list *protocols;\n";
5437 Result += "\tconst char *ivar_layout;\n";
5438 Result += "\tstruct _objc_class_ext *ext;\n";
5439 Result += "};\n";
5440 objc_class = true;
5441 }
5442
5443 // Meta-class metadata generation.
Craig Topper8ae12032014-05-07 06:21:57 +00005444 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005445 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5446 while (SuperClass) {
5447 RootClass = SuperClass;
5448 SuperClass = SuperClass->getSuperClass();
5449 }
5450 SuperClass = CDecl->getSuperClass();
5451
5452 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5453 Result += CDecl->getNameAsString();
5454 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5455 "{\n\t(struct _objc_class *)\"";
5456 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5457 Result += "\"";
5458
5459 if (SuperClass) {
5460 Result += ", \"";
5461 Result += SuperClass->getNameAsString();
5462 Result += "\", \"";
5463 Result += CDecl->getNameAsString();
5464 Result += "\"";
5465 }
5466 else {
5467 Result += ", 0, \"";
5468 Result += CDecl->getNameAsString();
5469 Result += "\"";
5470 }
5471 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5472 // 'info' field is initialized to CLS_META(2) for metaclass
5473 Result += ", 0,2, sizeof(struct _objc_class), 0";
5474 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5475 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5476 Result += IDecl->getNameAsString();
5477 Result += "\n";
5478 }
5479 else
5480 Result += ", 0\n";
5481 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5482 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5483 Result += CDecl->getNameAsString();
5484 Result += ",0,0\n";
5485 }
5486 else
5487 Result += "\t,0,0,0,0\n";
5488 Result += "};\n";
5489
5490 // class metadata generation.
5491 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5492 Result += CDecl->getNameAsString();
5493 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5494 "{\n\t&_OBJC_METACLASS_";
5495 Result += CDecl->getNameAsString();
5496 if (SuperClass) {
5497 Result += ", \"";
5498 Result += SuperClass->getNameAsString();
5499 Result += "\", \"";
5500 Result += CDecl->getNameAsString();
5501 Result += "\"";
5502 }
5503 else {
5504 Result += ", 0, \"";
5505 Result += CDecl->getNameAsString();
5506 Result += "\"";
5507 }
5508 // 'info' field is initialized to CLS_CLASS(1) for class
5509 Result += ", 0,1";
5510 if (!ObjCSynthesizedStructs.count(CDecl))
5511 Result += ",0";
5512 else {
5513 // class has size. Must synthesize its size.
5514 Result += ",sizeof(struct ";
5515 Result += CDecl->getNameAsString();
5516 if (LangOpts.MicrosoftExt)
5517 Result += "_IMPL";
5518 Result += ")";
5519 }
5520 if (NumIvars > 0) {
5521 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5522 Result += CDecl->getNameAsString();
5523 Result += "\n\t";
5524 }
5525 else
5526 Result += ",0";
5527 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5528 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5529 Result += CDecl->getNameAsString();
5530 Result += ", 0\n\t";
5531 }
5532 else
5533 Result += ",0,0";
5534 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5535 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5536 Result += CDecl->getNameAsString();
5537 Result += ", 0,0\n";
5538 }
5539 else
5540 Result += ",0,0,0\n";
5541 Result += "};\n";
5542}
5543
5544void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5545 int ClsDefCount = ClassImplementation.size();
5546 int CatDefCount = CategoryImplementation.size();
5547
5548 // For each implemented class, write out all its meta data.
5549 for (int i = 0; i < ClsDefCount; i++)
5550 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5551
5552 // For each implemented category, write out all its meta data.
5553 for (int i = 0; i < CatDefCount; i++)
5554 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5555
5556 // Write objc_symtab metadata
5557 /*
5558 struct _objc_symtab
5559 {
5560 long sel_ref_cnt;
5561 SEL *refs;
5562 short cls_def_cnt;
5563 short cat_def_cnt;
5564 void *defs[cls_def_cnt + cat_def_cnt];
5565 };
5566 */
5567
5568 Result += "\nstruct _objc_symtab {\n";
5569 Result += "\tlong sel_ref_cnt;\n";
5570 Result += "\tSEL *refs;\n";
5571 Result += "\tshort cls_def_cnt;\n";
5572 Result += "\tshort cat_def_cnt;\n";
5573 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5574 Result += "};\n\n";
5575
5576 Result += "static struct _objc_symtab "
5577 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5578 Result += "\t0, 0, " + utostr(ClsDefCount)
5579 + ", " + utostr(CatDefCount) + "\n";
5580 for (int i = 0; i < ClsDefCount; i++) {
5581 Result += "\t,&_OBJC_CLASS_";
5582 Result += ClassImplementation[i]->getNameAsString();
5583 Result += "\n";
5584 }
5585
5586 for (int i = 0; i < CatDefCount; i++) {
5587 Result += "\t,&_OBJC_CATEGORY_";
5588 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5589 Result += "_";
5590 Result += CategoryImplementation[i]->getNameAsString();
5591 Result += "\n";
5592 }
5593
5594 Result += "};\n\n";
5595
5596 // Write objc_module metadata
5597
5598 /*
5599 struct _objc_module {
5600 long version;
5601 long size;
5602 const char *name;
5603 struct _objc_symtab *symtab;
5604 }
5605 */
5606
5607 Result += "\nstruct _objc_module {\n";
5608 Result += "\tlong version;\n";
5609 Result += "\tlong size;\n";
5610 Result += "\tconst char *name;\n";
5611 Result += "\tstruct _objc_symtab *symtab;\n";
5612 Result += "};\n\n";
5613 Result += "static struct _objc_module "
5614 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5615 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5616 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5617 Result += "};\n\n";
5618
5619 if (LangOpts.MicrosoftExt) {
5620 if (ProtocolExprDecls.size()) {
5621 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5622 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Craig Topperc6914d02014-08-25 04:15:02 +00005623 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005624 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005625 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005626 Result += " = &_OBJC_PROTOCOL_";
Craig Topperc6914d02014-08-25 04:15:02 +00005627 Result += ProtDecl->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005628 Result += ";\n";
5629 }
5630 Result += "#pragma data_seg(pop)\n\n";
5631 }
5632 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5633 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5634 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5635 Result += "&_OBJC_MODULES;\n";
5636 Result += "#pragma data_seg(pop)\n\n";
5637 }
5638}
5639
5640/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5641/// implementation.
5642void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5643 std::string &Result) {
5644 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5645 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005646 ObjCCategoryDecl *CDecl
5647 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005648
5649 std::string FullCategoryName = ClassDecl->getNameAsString();
5650 FullCategoryName += '_';
5651 FullCategoryName += IDecl->getNameAsString();
5652
5653 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005654 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005655
5656 // If any of our property implementations have associated getters or
5657 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00005658 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005659 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005660 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005661 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005662 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005663 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005664 if (!PD)
5665 continue;
5666 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5667 InstanceMethods.push_back(Getter);
5668 if (PD->isReadOnly())
5669 continue;
5670 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5671 InstanceMethods.push_back(Setter);
5672 }
5673 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5674 true, "CATEGORY_", FullCategoryName.c_str(),
5675 Result);
5676
5677 // Build _objc_method_list for class's class methods if needed
5678 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5679 false, "CATEGORY_", FullCategoryName.c_str(),
5680 Result);
5681
5682 // Protocols referenced in class declaration?
5683 // Null CDecl is case of a category implementation with no category interface
5684 if (CDecl)
5685 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5686 FullCategoryName, Result);
5687 /* struct _objc_category {
5688 char *category_name;
5689 char *class_name;
5690 struct _objc_method_list *instance_methods;
5691 struct _objc_method_list *class_methods;
5692 struct _objc_protocol_list *protocols;
5693 // Objective-C 1.0 extensions
5694 uint32_t size; // sizeof (struct _objc_category)
5695 struct _objc_property_list *instance_properties; // category's own
5696 // @property decl.
5697 };
5698 */
5699
5700 static bool objc_category = false;
5701 if (!objc_category) {
5702 Result += "\nstruct _objc_category {\n";
5703 Result += "\tchar *category_name;\n";
5704 Result += "\tchar *class_name;\n";
5705 Result += "\tstruct _objc_method_list *instance_methods;\n";
5706 Result += "\tstruct _objc_method_list *class_methods;\n";
5707 Result += "\tstruct _objc_protocol_list *protocols;\n";
5708 Result += "\tunsigned int size;\n";
5709 Result += "\tstruct _objc_property_list *instance_properties;\n";
5710 Result += "};\n";
5711 objc_category = true;
5712 }
5713 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5714 Result += FullCategoryName;
5715 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5716 Result += IDecl->getNameAsString();
5717 Result += "\"\n\t, \"";
5718 Result += ClassDecl->getNameAsString();
5719 Result += "\"\n";
5720
5721 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5722 Result += "\t, (struct _objc_method_list *)"
5723 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5724 Result += FullCategoryName;
5725 Result += "\n";
5726 }
5727 else
5728 Result += "\t, 0\n";
5729 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5730 Result += "\t, (struct _objc_method_list *)"
5731 "&_OBJC_CATEGORY_CLASS_METHODS_";
5732 Result += FullCategoryName;
5733 Result += "\n";
5734 }
5735 else
5736 Result += "\t, 0\n";
5737
5738 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5739 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5740 Result += FullCategoryName;
5741 Result += "\n";
5742 }
5743 else
5744 Result += "\t, 0\n";
5745 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5746}
5747
5748// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5749/// class methods.
5750template<typename MethodIterator>
5751void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5752 MethodIterator MethodEnd,
5753 bool IsInstanceMethod,
5754 StringRef prefix,
5755 StringRef ClassName,
5756 std::string &Result) {
5757 if (MethodBegin == MethodEnd) return;
5758
5759 if (!objc_impl_method) {
5760 /* struct _objc_method {
5761 SEL _cmd;
5762 char *method_types;
5763 void *_imp;
5764 }
5765 */
5766 Result += "\nstruct _objc_method {\n";
5767 Result += "\tSEL _cmd;\n";
5768 Result += "\tchar *method_types;\n";
5769 Result += "\tvoid *_imp;\n";
5770 Result += "};\n";
5771
5772 objc_impl_method = true;
5773 }
5774
5775 // Build _objc_method_list for class's methods if needed
5776
5777 /* struct {
5778 struct _objc_method_list *next_method;
5779 int method_count;
5780 struct _objc_method method_list[];
5781 }
5782 */
5783 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5784 Result += "\nstatic struct {\n";
5785 Result += "\tstruct _objc_method_list *next_method;\n";
5786 Result += "\tint method_count;\n";
5787 Result += "\tstruct _objc_method method_list[";
5788 Result += utostr(NumMethods);
5789 Result += "];\n} _OBJC_";
5790 Result += prefix;
5791 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5792 Result += "_METHODS_";
5793 Result += ClassName;
5794 Result += " __attribute__ ((used, section (\"__OBJC, __";
5795 Result += IsInstanceMethod ? "inst" : "cls";
5796 Result += "_meth\")))= ";
5797 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5798
5799 Result += "\t,{{(SEL)\"";
5800 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5801 std::string MethodTypeString;
5802 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5803 Result += "\", \"";
5804 Result += MethodTypeString;
5805 Result += "\", (void *)";
5806 Result += MethodInternalNames[*MethodBegin];
5807 Result += "}\n";
5808 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5809 Result += "\t ,{(SEL)\"";
5810 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5811 std::string MethodTypeString;
5812 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5813 Result += "\", \"";
5814 Result += MethodTypeString;
5815 Result += "\", (void *)";
5816 Result += MethodInternalNames[*MethodBegin];
5817 Result += "}\n";
5818 }
5819 Result += "\t }\n};\n";
5820}
5821
5822Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5823 SourceRange OldRange = IV->getSourceRange();
5824 Expr *BaseExpr = IV->getBase();
5825
5826 // Rewrite the base, but without actually doing replaces.
5827 {
5828 DisableReplaceStmtScope S(*this);
5829 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5830 IV->setBase(BaseExpr);
5831 }
5832
5833 ObjCIvarDecl *D = IV->getDecl();
5834
5835 Expr *Replacement = IV;
5836 if (CurMethodDef) {
5837 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5838 const ObjCInterfaceType *iFaceDecl =
5839 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5840 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5841 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005842 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005843 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5844 clsDeclared);
5845 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5846
5847 // Synthesize an explicit cast to gain access to the ivar.
5848 std::string RecName = clsDeclared->getIdentifier()->getName();
5849 RecName += "_IMPL";
5850 IdentifierInfo *II = &Context->Idents.get(RecName);
5851 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5852 SourceLocation(), SourceLocation(),
5853 II);
5854 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5855 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5856 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5857 CK_BitCast,
5858 IV->getBase());
5859 // Don't forget the parens to enforce the proper binding.
5860 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5861 OldRange.getEnd(),
Yunzhong Gaoeba323a2015-05-01 02:04:32 +00005862 castExpr);
5863 if (IV->isFreeIvar() &&
5864 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5865 MemberExpr *ME = new (Context)
5866 MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(),
5867 D->getType(), VK_LValue, OK_Ordinary);
5868 Replacement = ME;
5869 } else {
5870 IV->setBase(PE);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005871 }
5872 }
5873 } else { // we are outside a method.
5874 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5875
5876 // Explicit ivar refs need to have a cast inserted.
5877 // FIXME: consider sharing some of this code with the code above.
5878 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5879 const ObjCInterfaceType *iFaceDecl =
5880 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5881 // lookup which class implements the instance variable.
Craig Topper8ae12032014-05-07 06:21:57 +00005882 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahanian83077422011-12-08 18:25:15 +00005883 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5884 clsDeclared);
5885 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5886
5887 // Synthesize an explicit cast to gain access to the ivar.
5888 std::string RecName = clsDeclared->getIdentifier()->getName();
5889 RecName += "_IMPL";
5890 IdentifierInfo *II = &Context->Idents.get(RecName);
5891 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5892 SourceLocation(), SourceLocation(),
5893 II);
5894 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5895 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5896 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5897 CK_BitCast,
5898 IV->getBase());
5899 // Don't forget the parens to enforce the proper binding.
5900 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5901 IV->getBase()->getLocEnd(), castExpr);
5902 // Cannot delete IV->getBase(), since PE points to it.
5903 // Replace the old base with the cast. This is important when doing
5904 // embedded rewrites. For example, [newInv->_container addObject:0].
5905 IV->setBase(PE);
5906 }
5907 }
5908
5909 ReplaceStmtWithRange(IV, Replacement, OldRange);
5910 return Replacement;
5911}
Alp Toker0621cb22014-07-16 16:48:33 +00005912
5913#endif