blob: 339b7d16404a6416f4f3281120f3d4ab632e623a [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
Daniel Dunbarc1b17292010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 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 Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000250 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000251 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
252 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000253 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
254 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
256 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
257 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
258 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000259 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000260 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000261 void RewriteBlockPointerType(std::string& Str, QualType Type);
262 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000263 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000264 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000265 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000268 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000269 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000270 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner3c799d72007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Steve Naroff1042ff32008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattner69534692007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
282 bool &replaced);
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000284 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
285 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000286 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000301 Expr **args, unsigned nargs,
302 SourceLocation StartLoc=SourceLocation(),
303 SourceLocation EndLoc=SourceLocation());
304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
305 SourceLocation StartLoc=SourceLocation(),
306 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000309 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000310
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000311 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000312 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000313 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000314 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000315 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000316 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000317 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000318 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000319 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000320 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner3c799d72007-10-24 17:06:59 +0000322 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000323 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000326 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000327 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000329 template<typename MethodIterator>
330 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
331 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000332 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000333 llvm::StringRef prefix,
334 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +0000335 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Steve Naroffd9803712009-04-29 16:37:50 +0000337 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000338 llvm::StringRef prefix,
339 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000340 std::string &Result);
341 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000342 llvm::StringRef prefix,
343 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000344 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000345 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000346 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000347 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000348 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000356
Steve Naroff677ab3a2008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000388
Steve Naroff677ab3a2008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Steve Naroff677ab3a2008-10-27 17:20:55 +0000407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
410 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Steve Naroff677ab3a2008-10-27 17:20:55 +0000412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000413
Steve Naroff677ab3a2008-10-27 17:20:55 +0000414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
416 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000420 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000421 return true;
422 }
423 return false;
424 }
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000426 void GetExtentOfArgList(const char *Name, const char *&LParen,
427 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000428 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Daniel Dunbar56df9772010-08-17 22:39:59 +0000430 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
432 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000433
Steve Naroffd9803712009-04-29 16:37:50 +0000434 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000435 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000436 if (From[i] == '"')
437 To += "\\\"";
438 else
439 To += From[i];
440 }
441 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000442 };
John McCall97513962010-01-15 18:39:57 +0000443
444 // Helper function: create a CStyleCastExpr with trivial type source info.
445 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000446 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000447 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallcf142162010-08-07 06:22:56 +0000448 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
449 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000450 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
454 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000455 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000457 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000458 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000459 // All the args are checked/rewritten. Don't call twice!
460 RewriteBlockPointerDecl(D);
461 break;
462 }
463 }
464}
465
466void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000467 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000468 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000469 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000470}
471
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000472static bool IsHeaderFile(const std::string &Filename) {
473 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000474
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000475 if (DotPos == std::string::npos) {
476 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000477 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000478 }
Mike Stump11289f42009-09-09 15:08:12 +0000479
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000480 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
481 // C header: .h
482 // C++ header: .hh or .H;
483 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000484}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000485
Eli Friedman94cf21e2009-05-18 22:20:00 +0000486RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000487 Diagnostic &D, const LangOptions &LOpts,
488 bool silenceMacroWarn)
489 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
490 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000491 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000492 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000493 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000494 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000495 "rewriter doesn't support user-specified control flow semantics "
496 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000497}
498
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000499ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
500 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000501 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000502 const LangOptions &LOpts,
503 bool SilenceRewriteMacroWarning) {
504 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000505}
Chris Lattnere99c8322007-10-11 00:43:27 +0000506
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000507void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000508 Context = &context;
509 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000510 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000511 MsgSendFunctionDecl = 0;
512 MsgSendSuperFunctionDecl = 0;
513 MsgSendStretFunctionDecl = 0;
514 MsgSendSuperStretFunctionDecl = 0;
515 MsgSendFpretFunctionDecl = 0;
516 GetClassFunctionDecl = 0;
517 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000518 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000519 SelGetUidFunctionDecl = 0;
520 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000521 ConstantStringClassReference = 0;
522 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000523 CurMethodDef = 0;
524 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000525 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000526 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000527 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000528 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000529 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000530 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000531 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000532 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000533 PropParentMap = 0;
534 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000535 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000536 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Chris Lattner187f6262008-01-31 19:38:44 +0000538 // Get the ID and start/end of the main file.
539 MainFileID = SM->getMainFileID();
540 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
541 MainFileStart = MainBuf->getBufferStart();
542 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000543
Chris Lattner184e65d2009-04-14 23:22:57 +0000544 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner187f6262008-01-31 19:38:44 +0000546 // declaring objc_selector outside the parameter list removes a silly
547 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000548 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000549 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000550 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000551 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000552 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000553 if (LangOpts.Microsoft) {
554 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000555 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
556 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000557 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000558 }
Steve Naroff00a31762008-03-27 22:29:16 +0000559 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
561 Preamble += "typedef struct objc_object Protocol;\n";
562 Preamble += "#define _REWRITER_typedef_Protocol\n";
563 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000564 if (LangOpts.Microsoft) {
565 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
566 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
567 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000568 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000570 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000573 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000576 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000578 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000580 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
582 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000584 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000590 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000591 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
596 Preamble += "struct __objcFastEnumerationState {\n\t";
597 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000598 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000599 Preamble += "unsigned long *mutationsPtr;\n\t";
600 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000602 Preamble += "#define __FASTENUMERATIONSTATE\n";
603 Preamble += "#endif\n";
604 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
605 Preamble += "struct __NSConstantStringImpl {\n";
606 Preamble += " int *isa;\n";
607 Preamble += " int flags;\n";
608 Preamble += " char *str;\n";
609 Preamble += " long length;\n";
610 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000611 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
612 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
613 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000615 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000616 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000618 // Blocks preamble.
619 Preamble += "#ifndef BLOCK_IMPL\n";
620 Preamble += "#define BLOCK_IMPL\n";
621 Preamble += "struct __block_impl {\n";
622 Preamble += " void *isa;\n";
623 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000624 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000625 Preamble += " void *FuncPtr;\n";
626 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000627 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000628 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000629 Preamble += "extern \"C\" __declspec(dllexport) "
630 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000631 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
634 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
639 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000640 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000641 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000642 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
643 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000644 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000645 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000646 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000647 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000648 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000649 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000650 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000651 Preamble += "#define __weak\n";
652 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000653 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
654 // as this avoids warning in any 64bit/32bit compilation model.
655 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000656}
657
658
Chris Lattner3c799d72007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Top Level Driver Code
661//===----------------------------------------------------------------------===//
662
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000663void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000664 if (Diags.hasErrorOccurred())
665 return;
666
Chris Lattner0bd1c972007-10-16 21:07:07 +0000667 // Two cases: either the decl could be in the main file, or it could be in a
668 // #included file. If the former, rewrite it now. If the later, check to see
669 // if we rewrote the #include/#import.
670 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000671 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattner0bd1c972007-10-16 21:07:07 +0000673 // If this is for a builtin, ignore it.
674 if (Loc.isInvalid()) return;
675
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000676 // Look for built-in declarations that we need to refer during the rewrite.
677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000678 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000679 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000680 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000681 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000682 ConstantStringClassReference = FVD;
683 return;
684 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000685 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000686 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000687 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000688 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000689 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000690 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000691 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000692 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000693 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000694 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
695 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000696 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
697 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000698 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000699 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000700 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000701 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000702 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000703 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000704}
705
Chris Lattner3c799d72007-10-24 17:06:59 +0000706//===----------------------------------------------------------------------===//
707// Syntactic (non-AST) Rewriting Code
708//===----------------------------------------------------------------------===//
709
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000710void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000711 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000712 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.begin();
714 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000715 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000716
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000717 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000718 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
719 if (*BufPtr == '#') {
720 if (++BufPtr == MainBufEnd)
721 return;
722 while (*BufPtr == ' ' || *BufPtr == '\t')
723 if (++BufPtr == MainBufEnd)
724 return;
725 if (!strncmp(BufPtr, "import", ImportLen)) {
726 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000727 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000728 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000729 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000730 BufPtr += ImportLen;
731 }
732 }
733 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000734}
735
Steve Naroff9af94912008-12-02 15:48:25 +0000736static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
737 ObjCIvarDecl *OID) {
738 std::string S;
739 S = "((struct ";
740 S += ClassDecl->getIdentifier()->getName();
741 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000742 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000743 return S;
744}
745
Steve Naroffc038b3a2008-12-02 17:36:43 +0000746void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
747 ObjCImplementationDecl *IMD,
748 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000749 static bool objcGetPropertyDefined = false;
750 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000751 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000752 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000753 const char *startBuf = SM->getCharacterData(startLoc);
754 assert((*startBuf == '@') && "bogus @synthesize location");
755 const char *semiBuf = strchr(startBuf, ';');
756 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000757 SourceLocation onePastSemiLoc =
758 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000759
760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
761 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000762
Steve Naroff9af94912008-12-02 15:48:25 +0000763 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000764 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000765 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000766 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000767
Steve Naroff003d00e2008-12-02 16:05:55 +0000768 if (!OID)
769 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000770 unsigned Attributes = PD->getPropertyAttributes();
771 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
772 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
773 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000775 if (GenGetProperty && !objcGetPropertyDefined) {
776 objcGetPropertyDefined = true;
777 // FIXME. Is this attribute correct in all cases?
778 Getr = "\nextern \"C\" __declspec(dllimport) "
779 "id objc_getProperty(id, SEL, long, bool);\n";
780 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000781 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
782 Getr += "{ ";
783 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000784 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000785 if (GenGetProperty) {
786 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
787 Getr += "typedef ";
788 const FunctionType *FPRetType = 0;
789 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
790 FPRetType);
791 Getr += " _TYPE";
792 if (FPRetType) {
793 Getr += ")"; // close the precedence "scope" for "*".
794
795 // Now, emit the argument types (if any).
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000796 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000797 Getr += "(";
798 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
799 if (i) Getr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000800 std::string ParamStr = FT->getArgType(i).getAsString(
801 Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000802 Getr += ParamStr;
803 }
804 if (FT->isVariadic()) {
805 if (FT->getNumArgs()) Getr += ", ";
806 Getr += "...";
807 }
808 Getr += ")";
809 } else
810 Getr += "()";
811 }
812 Getr += ";\n";
813 Getr += "return (_TYPE)";
814 Getr += "objc_getProperty(self, _cmd, ";
815 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
816 Getr += ", 1)";
817 }
818 else
819 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000820 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000821 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000822 if (PD->isReadOnly())
823 return;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Steve Naroff9af94912008-12-02 15:48:25 +0000825 // Generate the 'setter' function.
826 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000827 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy);
829 if (GenSetProperty && !objcSetPropertyDefined) {
830 objcSetPropertyDefined = true;
831 // FIXME. Is this attribute correct in all cases?
832 Setr = "\nextern \"C\" __declspec(dllimport) "
833 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
834 }
835
Steve Naroff9af94912008-12-02 15:48:25 +0000836 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000837 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000838 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000839 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000840 if (GenSetProperty) {
841 Setr += "objc_setProperty (self, _cmd, ";
842 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
843 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000844 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000845 Setr += ", ";
846 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
847 Setr += "0, ";
848 else
849 Setr += "1, ";
850 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
851 Setr += "1)";
852 else
853 Setr += "0)";
854 }
855 else {
856 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000857 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000858 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000859 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000860 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000861}
Chris Lattner16a0de42007-10-11 18:38:32 +0000862
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000863void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000864 // Get the start location and compute the semi location.
865 SourceLocation startLoc = ClassDecl->getLocation();
866 const char *startBuf = SM->getCharacterData(startLoc);
867 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner3c799d72007-10-24 17:06:59 +0000869 // Translate to typedef's that forward reference structs with the same name
870 // as the class. As a convenience, we include the original declaration
871 // as a comment.
872 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000873 typedefString += "// @class ";
874 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
875 I != E; ++I) {
876 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
877 typedefString += ForwardDecl->getNameAsString();
878 if (I+1 != E)
879 typedefString += ", ";
880 else
881 typedefString += ";\n";
882 }
883
Chris Lattner9ee23b72009-02-20 18:04:31 +0000884 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
885 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000886 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000887 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000888 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000889 typedefString += "\n";
890 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000891 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000892 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000893 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000894 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000895 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000896 }
Mike Stump11289f42009-09-09 15:08:12 +0000897
Steve Naroff574440f2007-10-24 22:48:43 +0000898 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000899 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000900}
901
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000902void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000903 // When method is a synthesized one, such as a getter/setter there is
904 // nothing to rewrite.
905 if (Method->isSynthesized())
906 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000907 SourceLocation LocStart = Method->getLocStart();
908 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattner88ea93e2009-02-04 01:06:56 +0000910 if (SM->getInstantiationLineNumber(LocEnd) >
911 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000912 InsertText(LocStart, "#if 0\n");
913 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000914 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000915 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000916 }
917}
918
Mike Stump11289f42009-09-09 15:08:12 +0000919void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000920 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000921
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000922 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000923 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000924}
925
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000926void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000927 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000928
Steve Naroff5448cf62007-10-30 13:30:57 +0000929 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000930 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000931
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000932 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
933 E = CatDecl->prop_end(); I != E; ++I)
934 RewriteProperty(*I);
935
Mike Stump11289f42009-09-09 15:08:12 +0000936 for (ObjCCategoryDecl::instmeth_iterator
937 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000938 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000939 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000940 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000941 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000942 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000943 RewriteMethodDeclaration(*I);
944
Steve Naroff5448cf62007-10-30 13:30:57 +0000945 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000946 ReplaceText(CatDecl->getAtEndRange().getBegin(),
947 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000948}
949
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000950void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000951 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000952
Steve Narofff921385f2007-10-30 16:42:30 +0000953 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000954 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000955
956 for (ObjCProtocolDecl::instmeth_iterator
957 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000958 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000959 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000960 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000961 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000962 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000963 RewriteMethodDeclaration(*I);
964
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000965 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
966 E = PDecl->prop_end(); I != E; ++I)
967 RewriteProperty(*I);
968
Steve Narofff921385f2007-10-30 16:42:30 +0000969 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000970 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000971 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000972
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000973 // Must comment out @optional/@required
974 const char *startBuf = SM->getCharacterData(LocStart);
975 const char *endBuf = SM->getCharacterData(LocEnd);
976 for (const char *p = startBuf; p < endBuf; p++) {
977 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000978 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000979 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000981 }
982 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000983 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000984 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +0000985
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000986 }
987 }
Steve Narofff921385f2007-10-30 16:42:30 +0000988}
989
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000990void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000991 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000992 if (LocStart.isInvalid())
993 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000994 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000995 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000996}
997
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000998void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
999 const FunctionType *&FPRetType) {
1000 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001001 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001002 else if (T->isFunctionPointerType() ||
1003 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001004 // needs special handling, since pointer-to-functions have special
1005 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001006 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001007 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001008 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001009 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001010 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001011 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001012 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001013 ResultStr += FPRetType->getResultType().getAsString(
1014 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001015 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001016 }
1017 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001018 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001019}
1020
1021void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1022 std::string &ResultStr) {
1023 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1024 const FunctionType *FPRetType = 0;
1025 ResultStr += "\nstatic ";
1026 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001027 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001028
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001029 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001030 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregorffca3a22009-01-09 17:18:27 +00001032 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001033 NameStr += "_I_";
1034 else
1035 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001037 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001038 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001039
1040 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001041 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001042 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001043 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001046 {
1047 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001048 int len = selString.size();
1049 for (int i = 0; i < len; i++)
1050 if (selString[i] == ':')
1051 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001052 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001053 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001054 // Remember this name for metadata emission
1055 MethodInternalNames[OMD] = NameStr;
1056 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001057
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058 // Rewrite arguments
1059 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001060
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001061 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001062 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001063 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001064 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001065 if (!LangOpts.Microsoft) {
1066 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1067 ResultStr += "struct ";
1068 }
1069 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001070 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001071 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 }
1073 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001074 ResultStr += Context->getObjCClassType().getAsString(
1075 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001076
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001078 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001079 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001080
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001082 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1083 E = OMD->param_end(); PI != E; ++PI) {
1084 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001086 if (PDecl->getType()->isObjCQualifiedIdType()) {
1087 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001088 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001089 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001090 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001091 QualType QT = PDecl->getType();
1092 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1093 if (convertBlockPointerToFunctionPointer(QT))
1094 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1095 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001096 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001097 ResultStr += Name;
1098 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001099 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001100 if (OMD->isVariadic())
1101 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001102 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001103
Steve Naroffb067bbd2008-07-16 14:40:40 +00001104 if (FPRetType) {
1105 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001106
Steve Naroffb067bbd2008-07-16 14:40:40 +00001107 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001108 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001109 ResultStr += "(";
1110 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1111 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001112 std::string ParamStr = FT->getArgType(i).getAsString(
1113 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001114 ResultStr += ParamStr;
1115 }
1116 if (FT->isVariadic()) {
1117 if (FT->getNumArgs()) ResultStr += ", ";
1118 ResultStr += "...";
1119 }
1120 ResultStr += ")";
1121 } else {
1122 ResultStr += "()";
1123 }
1124 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001125}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001126void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001127 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1128 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001129
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001130 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001131
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001132 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001133 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1134 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001135 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001136 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001137 ObjCMethodDecl *OMD = *I;
1138 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001139 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001140 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001141
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001142 const char *startBuf = SM->getCharacterData(LocStart);
1143 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001144 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001147 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001148 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1149 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001150 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001151 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001152 ObjCMethodDecl *OMD = *I;
1153 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001154 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001155 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001156
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001157 const char *startBuf = SM->getCharacterData(LocStart);
1158 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001159 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001160 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001161 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001162 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001163 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001164 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001165 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001166 }
1167
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001168 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001169}
1170
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001171void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001172 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001173 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001174 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001175 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001176 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001177 ResultStr += "\n";
1178 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001179 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001180 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001181 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001182 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001183 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001184 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001185 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001186 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001188
1189 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001190 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001191 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001192 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001193 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001194 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001195 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001196 for (ObjCInterfaceDecl::classmeth_iterator
1197 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001198 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001199 RewriteMethodDeclaration(*I);
1200
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001201 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001202 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1203 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001204}
1205
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001206Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001207 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001208 ObjCMethodDecl *OMD = 0;
1209 QualType Ty;
1210 Selector Sel;
1211 Stmt *Receiver;
1212 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001213 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001214 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1215 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1216 OMD = PDecl->getSetterMethodDecl();
1217 Ty = PDecl->getType();
1218 Sel = PDecl->getSetterName();
1219 Receiver = PropRefExpr->getBase();
1220 }
1221 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1222 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1223 OMD = ImplicitRefExpr->getSetterMethod();
1224 Sel = OMD->getSelector();
1225 Ty = ImplicitRefExpr->getType();
1226 Receiver = ImplicitRefExpr->getBase();
1227 }
1228
1229 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001230 llvm::SmallVector<Expr *, 1> ExprVec;
1231 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001233 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1234 if (PropGetters[Exp])
1235 // This allows us to handle chain/nested property/implicit getters.
1236 Receiver = PropGetters[Exp];
1237
1238 ObjCMessageExpr *MsgExpr;
Douglas Gregor9a129192010-04-21 00:45:42 +00001239 if (isa<ObjCSuperExpr>(Receiver))
1240 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001241 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001242 /*FIXME?*/SourceLocation(),
1243 Receiver->getLocStart(),
1244 /*IsInstanceSuper=*/true,
1245 cast<Expr>(Receiver)->getType(),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001246 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001247 &ExprVec[0], 1,
1248 /*FIXME:*/SourceLocation());
1249 else
1250 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001251 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001252 /*FIXME: */SourceLocation(),
1253 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001254 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001255 &ExprVec[0], 1,
1256 /*FIXME:*/SourceLocation());
Steve Naroff4588d0f2008-12-04 16:24:46 +00001257 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001258
Steve Naroff4588d0f2008-12-04 16:24:46 +00001259 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001260 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001261 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001262 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1263 // to things that stay around.
1264 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001265 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001266}
1267
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001268Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1269 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001270 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001271 Stmt *Receiver;
1272 ObjCMethodDecl *OMD = 0;
1273 QualType Ty;
1274 Selector Sel;
1275 if (ObjCPropertyRefExpr *PropRefExpr =
1276 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1277 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1278 OMD = PDecl->getGetterMethodDecl();
1279 Receiver = PropRefExpr->getBase();
1280 Ty = PDecl->getType();
1281 Sel = PDecl->getGetterName();
Steve Naroff1042ff32008-12-08 16:43:47 +00001282 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001283 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1284 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1285 OMD = ImplicitRefExpr->getGetterMethod();
1286 Receiver = ImplicitRefExpr->getBase();
1287 Sel = OMD->getSelector();
1288 Ty = ImplicitRefExpr->getType();
1289 }
1290
1291 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1292
1293 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1294 if (PropGetters[Exp])
1295 // This allows us to handle chain/nested property/implicit getters.
1296 Receiver = PropGetters[Exp];
1297
1298 ObjCMessageExpr *MsgExpr;
Douglas Gregor9a129192010-04-21 00:45:42 +00001299 if (isa<ObjCSuperExpr>(Receiver))
1300 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001301 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001302 /*FIXME:*/SourceLocation(),
1303 Receiver->getLocStart(),
1304 /*IsInstanceSuper=*/true,
1305 cast<Expr>(Receiver)->getType(),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001306 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001307 0, 0,
1308 /*FIXME:*/SourceLocation());
1309 else
1310 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001311 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001312 /*FIXME:*/SourceLocation(),
1313 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001314 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001315 0, 0,
1316 /*FIXME:*/SourceLocation());
Steve Narofff326f402008-12-03 00:56:33 +00001317
Steve Naroff22216db2008-12-04 23:50:32 +00001318 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001319
1320 if (!PropParentMap)
1321 PropParentMap = new ParentMap(CurrentBody);
1322
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001323 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1324 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1325 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001326 // We stash away the ReplacingStmt since actually doing the
1327 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001328 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001329 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1330 // to things that stay around.
1331 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001332 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001333 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001334 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001335 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001336 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1337 // to things that stay around.
1338 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001339 return ReplacingStmt;
1340 }
Steve Narofff326f402008-12-03 00:56:33 +00001341}
1342
Mike Stump11289f42009-09-09 15:08:12 +00001343Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001344 SourceLocation OrigStart,
1345 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001346 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001347 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001348 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001349 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001350 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001351 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001352 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001353 // lookup which class implements the instance variable.
1354 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001355 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001356 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001357 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001358
Steve Naroffb1c02372008-05-08 17:52:16 +00001359 // Synthesize an explicit cast to gain access to the ivar.
1360 std::string RecName = clsDeclared->getIdentifier()->getName();
1361 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001362 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001363 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001364 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001365 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1366 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001367 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001368 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001369 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001370 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001371 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1372 IV->getBase()->getLocEnd(),
1373 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001374 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001375 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001376 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001377 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1378 IV->getLocation(),
1379 D->getType());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001380 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001381 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001382 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001383 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001384 // Cannot delete IV->getBase(), since PE points to it.
1385 // Replace the old base with the cast. This is important when doing
1386 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001387 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001388 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001389 }
Steve Naroff24840f62008-04-18 21:55:08 +00001390 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001391 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001392
Steve Naroff29ce4e52008-05-06 23:20:07 +00001393 // Explicit ivar refs need to have a cast inserted.
1394 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001395 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001396 ObjCInterfaceType *iFaceDecl =
1397 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001398 // lookup which class implements the instance variable.
1399 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001400 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001401 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001402 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001403
Steve Naroff29ce4e52008-05-06 23:20:07 +00001404 // Synthesize an explicit cast to gain access to the ivar.
1405 std::string RecName = clsDeclared->getIdentifier()->getName();
1406 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001407 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001408 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001409 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001410 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1411 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001412 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001413 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001414 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001415 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001416 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001417 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001418 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001419 // Cannot delete IV->getBase(), since PE points to it.
1420 // Replace the old base with the cast. This is important when doing
1421 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001422 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001423 return IV;
1424 }
Steve Naroff05caa482007-11-15 11:33:00 +00001425 }
Steve Naroff24840f62008-04-18 21:55:08 +00001426 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001427}
1428
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001429Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1430 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1431 CI != E; ++CI) {
1432 if (*CI) {
1433 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1434 if (newStmt)
1435 *CI = newStmt;
1436 }
1437 }
1438 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1439 SourceRange OrigStmtRange = S->getSourceRange();
1440 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1441 replaced);
1442 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001443 }
1444 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1445 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1446 return newStmt;
1447 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001448 return S;
1449}
1450
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001451/// SynthCountByEnumWithState - To print:
1452/// ((unsigned int (*)
1453/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001454/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001455/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001456/// "countByEnumeratingWithState:objects:count:"),
1457/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458/// (id *)items, (unsigned int)16)
1459///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001460void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001461 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1462 "id *, unsigned int))(void *)objc_msgSend)";
1463 buf += "\n\t\t";
1464 buf += "((id)l_collection,\n\t\t";
1465 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1466 buf += "\n\t\t";
1467 buf += "&enumState, "
1468 "(id *)items, (unsigned int)16)";
1469}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001470
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001471/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1472/// statement to exit to its outer synthesized loop.
1473///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001474Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001475 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1476 return S;
1477 // replace break with goto __break_label
1478 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001479
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001480 SourceLocation startLoc = S->getLocStart();
1481 buf = "goto __break_label_";
1482 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001483 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484
1485 return 0;
1486}
1487
1488/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1489/// statement to continue with its inner synthesized loop.
1490///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001491Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001492 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1493 return S;
1494 // replace continue with goto __continue_label
1495 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001496
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001497 SourceLocation startLoc = S->getLocStart();
1498 buf = "goto __continue_label_";
1499 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001500 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001502 return 0;
1503}
1504
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001505/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001506/// It rewrites:
1507/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001508
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001509/// Into:
1510/// {
Mike Stump11289f42009-09-09 15:08:12 +00001511/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001513/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001515/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001516/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001517/// if (limit) {
1518/// unsigned long startMutations = *enumState.mutationsPtr;
1519/// do {
1520/// unsigned long counter = 0;
1521/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001522/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001523/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001524/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001525/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001526/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001527/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001528/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001529/// objects:items count:16]);
1530/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001531/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001532/// }
1533/// else
1534/// elem = nil;
1535/// }
1536///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001537Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001538 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001539 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001540 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001541 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001542 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001543 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001544
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001545 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001546 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001547 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001548 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001549 std::string buf;
1550 buf = "\n{\n\t";
1551 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1552 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001553 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001554 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001555 if (ElementType->isObjCQualifiedIdType() ||
1556 ElementType->isObjCQualifiedInterfaceType())
1557 // Simply use 'id' for all qualified types.
1558 elementTypeAsString = "id";
1559 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001560 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001561 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001562 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001563 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001564 buf += elementName;
1565 buf += ";\n\t";
1566 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001567 else {
1568 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001569 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001570 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1571 if (VD->getType()->isObjCQualifiedIdType() ||
1572 VD->getType()->isObjCQualifiedInterfaceType())
1573 // Simply use 'id' for all qualified types.
1574 elementTypeAsString = "id";
1575 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001576 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 // struct __objcFastEnumerationState enumState = { 0 };
1580 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1581 // id items[16];
1582 buf += "id items[16];\n\t";
1583 // id l_collection = (id)
1584 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001585 // Find start location of 'collection' the hard way!
1586 const char *startCollectionBuf = startBuf;
1587 startCollectionBuf += 3; // skip 'for'
1588 startCollectionBuf = strchr(startCollectionBuf, '(');
1589 startCollectionBuf++; // skip '('
1590 // find 'in' and skip it.
1591 while (*startCollectionBuf != ' ' ||
1592 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1593 (*(startCollectionBuf+3) != ' ' &&
1594 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1595 startCollectionBuf++;
1596 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001597
1598 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001599 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001600 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001601 SourceLocation rightParenLoc = S->getRParenLoc();
1602 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1603 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001604 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001605
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001606 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1607 // objects:items count:16];
1608 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001609 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 // ((unsigned int (*)
1611 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001612 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001614 // "countByEnumeratingWithState:objects:count:"),
1615 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001616 // (id *)items, (unsigned int)16);
1617 buf += "unsigned long limit =\n\t\t";
1618 SynthCountByEnumWithState(buf);
1619 buf += ";\n\t";
1620 /// if (limit) {
1621 /// unsigned long startMutations = *enumState.mutationsPtr;
1622 /// do {
1623 /// unsigned long counter = 0;
1624 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001625 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001626 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001627 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001628 buf += "if (limit) {\n\t";
1629 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1630 buf += "do {\n\t\t";
1631 buf += "unsigned long counter = 0;\n\t\t";
1632 buf += "do {\n\t\t\t";
1633 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1634 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1635 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001636 buf += " = (";
1637 buf += elementTypeAsString;
1638 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001639 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001640 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001641
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001642 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001643 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001644 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001645 /// objects:items count:16]);
1646 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001647 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 /// }
1649 /// else
1650 /// elem = nil;
1651 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001652 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001653 buf = ";\n\t";
1654 buf += "__continue_label_";
1655 buf += utostr(ObjCBcLabelNo.back());
1656 buf += ": ;";
1657 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001658 buf += "} while (counter < limit);\n\t";
1659 buf += "} while (limit = ";
1660 SynthCountByEnumWithState(buf);
1661 buf += ");\n\t";
1662 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001663 buf += " = ((";
1664 buf += elementTypeAsString;
1665 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001666 buf += "__break_label_";
1667 buf += utostr(ObjCBcLabelNo.back());
1668 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001669 buf += "}\n\t";
1670 buf += "else\n\t\t";
1671 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001672 buf += " = ((";
1673 buf += elementTypeAsString;
1674 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001675 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001676
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001677 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001678 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001679 if (isa<CompoundStmt>(S->getBody())) {
1680 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001681 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001682 } else {
1683 /* Need to treat single statements specially. For example:
1684 *
1685 * for (A *a in b) if (stuff()) break;
1686 * for (A *a in b) xxxyy;
1687 *
1688 * The following code simply scans ahead to the semi to find the actual end.
1689 */
1690 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1691 const char *semiBuf = strchr(stmtBuf, ';');
1692 assert(semiBuf && "Can't find ';'");
1693 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001694 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001695 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001696 Stmts.pop_back();
1697 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001698 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001699}
1700
Mike Stump11289f42009-09-09 15:08:12 +00001701/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001702/// This routine rewrites @synchronized(expr) stmt;
1703/// into:
1704/// objc_sync_enter(expr);
1705/// @try stmt @finally { objc_sync_exit(expr); }
1706///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001707Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001708 // Get the start location and compute the semi location.
1709 SourceLocation startLoc = S->getLocStart();
1710 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001711
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001712 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001713
1714 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001715 buf = "objc_sync_enter((id)";
1716 const char *lparenBuf = startBuf;
1717 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001718 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001719 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1720 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001721 // been rewritten! (which implies the SourceLocation's are invalid).
1722 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001723 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001724 while (*endBuf != ')') endBuf--;
1725 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001726 buf = ");\n";
1727 // declare a new scope with two variables, _stack and _rethrow.
1728 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1729 buf += "int buf[18/*32-bit i386*/];\n";
1730 buf += "char *pointers[4];} _stack;\n";
1731 buf += "id volatile _rethrow = 0;\n";
1732 buf += "objc_exception_try_enter(&_stack);\n";
1733 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001734 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001735 startLoc = S->getSynchBody()->getLocEnd();
1736 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001737
Steve Naroffad7013b2008-08-19 13:04:19 +00001738 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001739 SourceLocation lastCurlyLoc = startLoc;
1740 buf = "}\nelse {\n";
1741 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001742 buf += "}\n";
1743 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001744 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001745
1746 std::string syncBuf;
1747 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001748 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00001749 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001750 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001751 std::string syncExprBufS;
1752 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001753 syncExpr->printPretty(syncExprBuf, *Context, 0,
1754 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001755 syncBuf += syncExprBuf.str();
1756 syncBuf += ");";
1757
1758 buf += syncBuf;
1759 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001760 buf += "}\n";
1761 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001762
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001763 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001764
1765 bool hasReturns = false;
1766 HasReturnStmts(S->getSynchBody(), hasReturns);
1767 if (hasReturns)
1768 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1769
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001770 return 0;
1771}
1772
Steve Naroffec60b432009-12-05 21:43:12 +00001773void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1774{
Steve Naroff6d6da252008-12-05 17:03:39 +00001775 // Perform a bottom up traversal of all children.
1776 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1777 CI != E; ++CI)
1778 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001779 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001780
Steve Naroffec60b432009-12-05 21:43:12 +00001781 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001782 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001783 TryFinallyContainsReturnDiag);
1784 }
1785 return;
1786}
1787
Steve Naroffec60b432009-12-05 21:43:12 +00001788void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1789{
1790 // Perform a bottom up traversal of all children.
1791 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1792 CI != E; ++CI)
1793 if (*CI)
1794 HasReturnStmts(*CI, hasReturns);
1795
1796 if (isa<ReturnStmt>(S))
1797 hasReturns = true;
1798 return;
1799}
1800
1801void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1802 // Perform a bottom up traversal of all children.
1803 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1804 CI != E; ++CI)
1805 if (*CI) {
1806 RewriteTryReturnStmts(*CI);
1807 }
1808 if (isa<ReturnStmt>(S)) {
1809 SourceLocation startLoc = S->getLocStart();
1810 const char *startBuf = SM->getCharacterData(startLoc);
1811
1812 const char *semiBuf = strchr(startBuf, ';');
1813 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1814 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1815
1816 std::string buf;
1817 buf = "{ objc_exception_try_exit(&_stack); return";
1818
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001819 ReplaceText(startLoc, 6, buf);
1820 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001821 }
1822 return;
1823}
1824
1825void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1826 // Perform a bottom up traversal of all children.
1827 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1828 CI != E; ++CI)
1829 if (*CI) {
1830 RewriteSyncReturnStmts(*CI, syncExitBuf);
1831 }
1832 if (isa<ReturnStmt>(S)) {
1833 SourceLocation startLoc = S->getLocStart();
1834 const char *startBuf = SM->getCharacterData(startLoc);
1835
1836 const char *semiBuf = strchr(startBuf, ';');
1837 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1838 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1839
1840 std::string buf;
1841 buf = "{ objc_exception_try_exit(&_stack);";
1842 buf += syncExitBuf;
1843 buf += " return";
1844
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001845 ReplaceText(startLoc, 6, buf);
1846 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001847 }
1848 return;
1849}
1850
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001851Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001852 // Get the start location and compute the semi location.
1853 SourceLocation startLoc = S->getLocStart();
1854 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001855
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856 assert((*startBuf == '@') && "bogus @try location");
1857
1858 std::string buf;
1859 // declare a new scope with two variables, _stack and _rethrow.
1860 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1861 buf += "int buf[18/*32-bit i386*/];\n";
1862 buf += "char *pointers[4];} _stack;\n";
1863 buf += "id volatile _rethrow = 0;\n";
1864 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001865 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001866
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001867 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroffbf478ec2007-11-07 04:08:17 +00001869 startLoc = S->getTryBody()->getLocEnd();
1870 startBuf = SM->getCharacterData(startLoc);
1871
1872 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001873
Steve Naroffbf478ec2007-11-07 04:08:17 +00001874 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001875 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001876 startLoc = startLoc.getFileLocWithOffset(1);
1877 buf = " /* @catch begin */ else {\n";
1878 buf += " id _caught = objc_exception_extract(&_stack);\n";
1879 buf += " objc_exception_try_enter (&_stack);\n";
1880 buf += " if (_setjmp(_stack.buf))\n";
1881 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1882 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001883
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001884 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001885 } else { /* no catch list */
1886 buf = "}\nelse {\n";
1887 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1888 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001889 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001890 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001891 bool sawIdTypedCatch = false;
1892 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001893 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1894 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001895 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001896
Douglas Gregor96c79492010-04-23 22:50:49 +00001897 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898 buf = "if ("; // we are generating code for the first catch clause
1899 else
1900 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001901 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001902 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001903
Steve Naroffbf478ec2007-11-07 04:08:17 +00001904 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001905
Steve Naroffbf478ec2007-11-07 04:08:17 +00001906 const char *lParenLoc = strchr(startBuf, '(');
1907
Douglas Gregor96c79492010-04-23 22:50:49 +00001908 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001909 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001910 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001911 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1912 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001913 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001914 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001915 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001916
Steve Naroffedb5bc62008-02-01 20:02:07 +00001917 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001918 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001919 } else if (catchDecl) {
1920 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001921 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001922 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001923 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001924 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001925 } else if (const ObjCObjectPointerType *Ptr =
1926 t->getAs<ObjCObjectPointerType>()) {
1927 // Should be a pointer to a class.
1928 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1929 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001930 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001931 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001932 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001933 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001934 }
1935 }
1936 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001937 lastCatchBody = Catch->getCatchBody();
1938 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001939 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1940 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1941 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1942 assert((*rParenBuf == ')') && "bogus @catch paren location");
1943 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001944
Mike Stump11289f42009-09-09 15:08:12 +00001945 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001946 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001947 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001948 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001949 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001950 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001951 }
1952 // Complete the catch list...
1953 if (lastCatchBody) {
1954 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001955 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1956 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001957
Steve Naroff4adbe312008-09-11 15:29:03 +00001958 // Insert the last (implicit) else clause *before* the right curly brace.
1959 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1960 buf = "} /* last catch end */\n";
1961 buf += "else {\n";
1962 buf += " _rethrow = _caught;\n";
1963 buf += " objc_exception_try_exit(&_stack);\n";
1964 buf += "} } /* @catch end */\n";
1965 if (!S->getFinallyStmt())
1966 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001967 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001968
Steve Naroffbf478ec2007-11-07 04:08:17 +00001969 // Set lastCurlyLoc
1970 lastCurlyLoc = lastCatchBody->getLocEnd();
1971 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001972 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001973 startLoc = finalStmt->getLocStart();
1974 startBuf = SM->getCharacterData(startLoc);
1975 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001976
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001977 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001978
Steve Naroffbf478ec2007-11-07 04:08:17 +00001979 Stmt *body = finalStmt->getFinallyBody();
1980 SourceLocation startLoc = body->getLocStart();
1981 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001982 assert(*SM->getCharacterData(startLoc) == '{' &&
1983 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001984 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001985 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001986
Steve Naroffbf478ec2007-11-07 04:08:17 +00001987 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001988 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001989 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001990 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001991
Steve Naroffbf478ec2007-11-07 04:08:17 +00001992 // Set lastCurlyLoc
1993 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001994
Steve Naroff6d6da252008-12-05 17:03:39 +00001995 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001996 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001997 } else { /* no finally clause - make sure we synthesize an implicit one */
1998 buf = "{ /* implicit finally clause */\n";
1999 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2000 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2001 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002002 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002003
2004 // Now check for any return/continue/go statements within the @try.
2005 // The implicit finally clause won't called if the @try contains any
2006 // jump statements.
2007 bool hasReturns = false;
2008 HasReturnStmts(S->getTryBody(), hasReturns);
2009 if (hasReturns)
2010 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002011 }
2012 // Now emit the final closing curly brace...
2013 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002014 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002015 return 0;
2016}
2017
Mike Stump11289f42009-09-09 15:08:12 +00002018// This can't be done with ReplaceStmt(S, ThrowExpr), since
2019// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002020// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002021Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002022 // Get the start location and compute the semi location.
2023 SourceLocation startLoc = S->getLocStart();
2024 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Steve Naroffa733c7f2007-11-07 15:32:26 +00002026 assert((*startBuf == '@') && "bogus @throw location");
2027
2028 std::string buf;
2029 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002030 if (S->getThrowExpr())
2031 buf = "objc_exception_throw(";
2032 else // add an implicit argument
2033 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002034
Steve Naroff29788342008-07-25 15:41:30 +00002035 // handle "@ throw" correctly.
2036 const char *wBuf = strchr(startBuf, 'w');
2037 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002038 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Steve Naroffa733c7f2007-11-07 15:32:26 +00002040 const char *semiBuf = strchr(startBuf, ';');
2041 assert((*semiBuf == ';') && "@throw: can't find ';'");
2042 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002043 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002044 return 0;
2045}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002046
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002047Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002048 // Create a new string expression.
2049 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002050 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002051 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002052 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2053 StrEncoding.length(), false,StrType,
2054 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002055 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Chris Lattner4431a1b2007-11-30 22:53:43 +00002057 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002058 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002059 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002060}
2061
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002062Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002063 if (!SelGetUidFunctionDecl)
2064 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002065 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2066 // Create a call to sel_registerName("selName").
2067 llvm::SmallVector<Expr*, 8> SelExprs;
2068 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002069 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002070 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002071 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002072 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002073 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2074 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002075 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002076 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002077 return SelExp;
2078}
2079
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002080CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002081 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2082 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002083 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002084 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002085
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002086 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002087 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002088
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002089 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002090 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002091 ImplicitCastExpr *ICE =
John McCalle3027922010-08-25 11:45:40 +00002092 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall2536c6d2010-08-25 10:28:54 +00002093 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002094
John McCall9dd450b2009-09-21 23:43:11 +00002095 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002096
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002097 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002098 new (Context) CallExpr(*Context, ICE, args, nargs,
2099 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002100 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002101}
2102
Steve Naroff50d42052007-11-01 13:24:47 +00002103static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2104 const char *&startRef, const char *&endRef) {
2105 while (startBuf < endBuf) {
2106 if (*startBuf == '<')
2107 startRef = startBuf; // mark the start.
2108 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002109 if (startRef && *startRef == '<') {
2110 endRef = startBuf; // mark the end.
2111 return true;
2112 }
2113 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002114 }
2115 startBuf++;
2116 }
2117 return false;
2118}
2119
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002120static void scanToNextArgument(const char *&argRef) {
2121 int angle = 0;
2122 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2123 if (*argRef == '<')
2124 angle++;
2125 else if (*argRef == '>')
2126 angle--;
2127 argRef++;
2128 }
2129 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2130}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002131
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002132bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002133 if (T->isObjCQualifiedIdType())
2134 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002135 if (const PointerType *PT = T->getAs<PointerType>()) {
2136 if (PT->getPointeeType()->isObjCQualifiedIdType())
2137 return true;
2138 }
2139 if (T->isObjCObjectPointerType()) {
2140 T = T->getPointeeType();
2141 return T->isObjCQualifiedInterfaceType();
2142 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002143 if (T->isArrayType()) {
2144 QualType ElemTy = Context->getBaseElementType(T);
2145 return needToScanForQualifiers(ElemTy);
2146 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002147 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002148}
2149
Steve Naroff873bd842008-07-29 18:15:38 +00002150void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2151 QualType Type = E->getType();
2152 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002153 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Steve Naroffdbfc6932008-11-19 21:15:47 +00002155 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2156 Loc = ECE->getLParenLoc();
2157 EndLoc = ECE->getRParenLoc();
2158 } else {
2159 Loc = E->getLocStart();
2160 EndLoc = E->getLocEnd();
2161 }
2162 // This will defend against trying to rewrite synthesized expressions.
2163 if (Loc.isInvalid() || EndLoc.isInvalid())
2164 return;
2165
Steve Naroff873bd842008-07-29 18:15:38 +00002166 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002167 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002168 const char *startRef = 0, *endRef = 0;
2169 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2170 // Get the locations of the startRef, endRef.
2171 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2172 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2173 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002174 InsertText(LessLoc, "/*");
2175 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002176 }
2177 }
2178}
2179
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002180void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002181 SourceLocation Loc;
2182 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002183 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002184 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2185 Loc = VD->getLocation();
2186 Type = VD->getType();
2187 }
2188 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2189 Loc = FD->getLocation();
2190 // Check for ObjC 'id' and class types that have been adorned with protocol
2191 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002192 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002193 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002194 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002195 if (!proto)
2196 return;
2197 Type = proto->getResultType();
2198 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002199 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2200 Loc = FD->getLocation();
2201 Type = FD->getType();
2202 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002203 else
2204 return;
Mike Stump11289f42009-09-09 15:08:12 +00002205
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002206 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002207 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002208
Steve Naroff50d42052007-11-01 13:24:47 +00002209 const char *endBuf = SM->getCharacterData(Loc);
2210 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002211 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002212 startBuf--; // scan backward (from the decl location) for return type.
2213 const char *startRef = 0, *endRef = 0;
2214 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2215 // Get the locations of the startRef, endRef.
2216 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2217 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2218 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002219 InsertText(LessLoc, "/*");
2220 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002221 }
2222 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002223 if (!proto)
2224 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002225 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002226 const char *startBuf = SM->getCharacterData(Loc);
2227 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002228 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2229 if (needToScanForQualifiers(proto->getArgType(i))) {
2230 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002231
Steve Naroff50d42052007-11-01 13:24:47 +00002232 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002233 // scan forward (from the decl location) for argument types.
2234 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002235 const char *startRef = 0, *endRef = 0;
2236 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2237 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002238 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002239 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002240 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002241 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002242 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002243 InsertText(LessLoc, "/*");
2244 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002245 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002246 startBuf = ++endBuf;
2247 }
2248 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002249 // If the function name is derived from a macro expansion, then the
2250 // argument buffer will not follow the name. Need to speak with Chris.
2251 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002252 startBuf++; // scan forward (from the decl location) for argument types.
2253 startBuf++;
2254 }
Steve Naroff50d42052007-11-01 13:24:47 +00002255 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002256}
2257
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002258void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2259 QualType QT = ND->getType();
2260 const Type* TypePtr = QT->getAs<Type>();
2261 if (!isa<TypeOfExprType>(TypePtr))
2262 return;
2263 while (isa<TypeOfExprType>(TypePtr)) {
2264 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2265 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2266 TypePtr = QT->getAs<Type>();
2267 }
2268 // FIXME. This will not work for multiple declarators; as in:
2269 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002270 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002271 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2272 const char *startBuf = SM->getCharacterData(DeclLoc);
2273 if (ND->getInit()) {
2274 std::string Name(ND->getNameAsString());
2275 TypeAsString += " " + Name + " = ";
2276 Expr *E = ND->getInit();
2277 SourceLocation startLoc;
2278 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2279 startLoc = ECE->getLParenLoc();
2280 else
2281 startLoc = E->getLocStart();
2282 startLoc = SM->getInstantiationLoc(startLoc);
2283 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002284 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002285 }
2286 else {
2287 SourceLocation X = ND->getLocEnd();
2288 X = SM->getInstantiationLoc(X);
2289 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002290 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002291 }
2292}
2293
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002294// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002295void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002296 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2297 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002298 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002299 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002300 &ArgTys[0], ArgTys.size(),
2301 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002302 false, false, 0, 0,
2303 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002304 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002305 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002306 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002307 SC_Extern,
2308 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002309}
2310
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002311void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002312 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002313 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002314 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002315 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002316 return;
2317 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002318 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002319}
2320
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002321void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2322 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002323 const char *argPtr = TypeString.c_str();
2324 if (!strchr(argPtr, '^')) {
2325 Str += TypeString;
2326 return;
2327 }
2328 while (*argPtr) {
2329 Str += (*argPtr == '^' ? '*' : *argPtr);
2330 argPtr++;
2331 }
2332}
2333
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002334// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002335void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2336 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002337 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002338 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002339 const char *argPtr = TypeString.c_str();
2340 int paren = 0;
2341 while (*argPtr) {
2342 switch (*argPtr) {
2343 case '(':
2344 Str += *argPtr;
2345 paren++;
2346 break;
2347 case ')':
2348 Str += *argPtr;
2349 paren--;
2350 break;
2351 case '^':
2352 Str += '*';
2353 if (paren == 1)
2354 Str += VD->getNameAsString();
2355 break;
2356 default:
2357 Str += *argPtr;
2358 break;
2359 }
2360 argPtr++;
2361 }
2362}
2363
2364
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002365void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2366 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2367 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2368 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2369 if (!proto)
2370 return;
2371 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002372 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002373 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002374 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002375 FdStr += "(";
2376 unsigned numArgs = proto->getNumArgs();
2377 for (unsigned i = 0; i < numArgs; i++) {
2378 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002379 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002380 if (i+1 < numArgs)
2381 FdStr += ", ";
2382 }
2383 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002384 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002385 CurFunctionDeclToDeclareForBlock = 0;
2386}
2387
Steve Naroff17978c42008-03-11 17:37:02 +00002388// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002389void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002390 if (SuperContructorFunctionDecl)
2391 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002392 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002393 llvm::SmallVector<QualType, 16> ArgTys;
2394 QualType argT = Context->getObjCIdType();
2395 assert(!argT.isNull() && "Can't find 'id' type");
2396 ArgTys.push_back(argT);
2397 ArgTys.push_back(argT);
2398 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2399 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002400 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002401 false, false, 0, 0,
2402 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002403 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002404 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002405 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002406 SC_Extern,
2407 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002408}
2409
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002410// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002411void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002412 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2413 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002414 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002415 assert(!argT.isNull() && "Can't find 'id' type");
2416 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002417 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002418 assert(!argT.isNull() && "Can't find 'SEL' type");
2419 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002420 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002421 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002422 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002423 false, false, 0, 0,
2424 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002425 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002426 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002427 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002428 SC_Extern,
2429 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002430}
2431
Steve Naroff7fa2f042007-11-15 10:28:18 +00002432// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002433void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002434 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2435 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002436 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002437 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002438 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002439 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2440 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2441 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002442 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002443 assert(!argT.isNull() && "Can't find 'SEL' type");
2444 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002445 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002446 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002447 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002448 false, false, 0, 0,
2449 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002450 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002451 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002452 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002453 SC_Extern,
2454 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002455}
2456
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002457// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002458void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2460 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002461 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002464 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002467 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002468 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002469 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002470 false, false, 0, 0,
2471 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002472 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002473 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002474 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002475 SC_Extern,
2476 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002477}
2478
Mike Stump11289f42009-09-09 15:08:12 +00002479// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002480// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002481void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002482 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002483 &Context->Idents.get("objc_msgSendSuper_stret");
2484 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002485 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002486 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002487 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002488 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2489 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2490 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002491 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002492 assert(!argT.isNull() && "Can't find 'SEL' type");
2493 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002494 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002495 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002496 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002497 false, false, 0, 0,
2498 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002499 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002500 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002501 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002502 SC_Extern,
2503 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002504}
2505
Steve Naroff2e4e3852008-05-08 22:02:18 +00002506// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002507void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002508 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2509 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002510 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002511 assert(!argT.isNull() && "Can't find 'id' type");
2512 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002513 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002514 assert(!argT.isNull() && "Can't find 'SEL' type");
2515 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002516 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002517 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002518 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002519 false, false, 0, 0,
2520 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002521 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002522 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002523 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002524 SC_Extern,
2525 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002526}
2527
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002528// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002529void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002530 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2531 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002532 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002533 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002534 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002535 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002536 false, false, 0, 0,
2537 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002538 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002539 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002540 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002541 SC_Extern,
2542 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002543}
2544
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002545// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2546void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2547 IdentifierInfo *getSuperClassIdent =
2548 &Context->Idents.get("class_getSuperclass");
2549 llvm::SmallVector<QualType, 16> ArgTys;
2550 ArgTys.push_back(Context->getObjCClassType());
2551 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2552 &ArgTys[0], ArgTys.size(),
2553 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002554 false, false, 0, 0,
2555 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002556 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002557 SourceLocation(),
2558 getSuperClassIdent,
2559 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002560 SC_Extern,
2561 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002562 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002563}
2564
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002565// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002566void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002567 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2568 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002569 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002570 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002571 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002572 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002573 false, false, 0, 0,
2574 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002575 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002576 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002577 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002578 SC_Extern,
2579 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002580}
2581
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002582Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002583 QualType strType = getConstantStringStructType();
2584
2585 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002586
2587 std::string tmpName = InFileName;
2588 unsigned i;
2589 for (i=0; i < tmpName.length(); i++) {
2590 char c = tmpName.at(i);
2591 // replace any non alphanumeric characters with '_'.
2592 if (!isalpha(c) && (c < '0' || c > '9'))
2593 tmpName[i] = '_';
2594 }
2595 S += tmpName;
2596 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002597 S += utostr(NumObjCStringLiterals++);
2598
Steve Naroff00a31762008-03-27 22:29:16 +00002599 Preamble += "static __NSConstantStringImpl " + S;
2600 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2601 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002602 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002603 std::string prettyBufS;
2604 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002605 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2606 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002607 Preamble += prettyBuf.str();
2608 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002609 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002610
2611 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002612 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002613 SC_Static, SC_None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002614 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002615 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002616 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002617 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002618 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002619 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalle3027922010-08-25 11:45:40 +00002620 CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002621 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002622 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002623 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002624}
2625
Steve Naroff7fa2f042007-11-15 10:28:18 +00002626// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002627QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002628 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002629 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002630 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002631 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002632 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002633
Steve Naroff7fa2f042007-11-15 10:28:18 +00002634 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002635 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002636 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002637 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002638
Steve Naroff7fa2f042007-11-15 10:28:18 +00002639 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002640 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002641 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2642 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002643 FieldTypes[i], 0,
2644 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002645 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002646 }
Mike Stump11289f42009-09-09 15:08:12 +00002647
Douglas Gregord5058122010-02-11 01:19:42 +00002648 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002649 }
2650 return Context->getTagDeclType(SuperStructDecl);
2651}
2652
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002653QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002654 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002655 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002656 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002657 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002658 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002659
Steve Naroffce8e8862008-03-15 00:55:56 +00002660 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002661 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002662 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002663 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002664 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002665 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002666 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002667 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002668
Steve Naroffce8e8862008-03-15 00:55:56 +00002669 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002670 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002671 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2672 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002673 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002674 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002675 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002676 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002677 }
2678
Douglas Gregord5058122010-02-11 01:19:42 +00002679 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002680 }
2681 return Context->getTagDeclType(ConstantStringDecl);
2682}
2683
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002684Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2685 SourceLocation StartLoc,
2686 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002687 if (!SelGetUidFunctionDecl)
2688 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002689 if (!MsgSendFunctionDecl)
2690 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002691 if (!MsgSendSuperFunctionDecl)
2692 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 if (!MsgSendStretFunctionDecl)
2694 SynthMsgSendStretFunctionDecl();
2695 if (!MsgSendSuperStretFunctionDecl)
2696 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002697 if (!MsgSendFpretFunctionDecl)
2698 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002699 if (!GetClassFunctionDecl)
2700 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002701 if (!GetSuperClassFunctionDecl)
2702 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002703 if (!GetMetaClassFunctionDecl)
2704 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Naroff7fa2f042007-11-15 10:28:18 +00002706 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002707 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2708 // May need to use objc_msgSend_stret() as well.
2709 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002710 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2711 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002712 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002713 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002714 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002715 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Steve Naroff574440f2007-10-24 22:48:43 +00002718 // Synthesize a call to objc_msgSend().
2719 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002720 switch (Exp->getReceiverKind()) {
2721 case ObjCMessageExpr::SuperClass: {
2722 MsgSendFlavor = MsgSendSuperFunctionDecl;
2723 if (MsgSendStretFlavor)
2724 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2725 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002726
Douglas Gregor9a129192010-04-21 00:45:42 +00002727 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregor9a129192010-04-21 00:45:42 +00002729 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002730
Douglas Gregor9a129192010-04-21 00:45:42 +00002731 // set the receiver to self, the first argument to all methods.
2732 InitExprs.push_back(
2733 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002734 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002735 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2736 Context->getObjCIdType(),
2737 SourceLocation()))
2738 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregor9a129192010-04-21 00:45:42 +00002740 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2741 llvm::SmallVector<Expr*, 8> ClsExprs;
2742 QualType argType = Context->getPointerType(Context->CharTy);
2743 ClsExprs.push_back(StringLiteral::Create(*Context,
2744 ClassDecl->getIdentifier()->getNameStart(),
2745 ClassDecl->getIdentifier()->getLength(),
2746 false, argType, SourceLocation()));
2747 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2748 &ClsExprs[0],
2749 ClsExprs.size(),
2750 StartLoc,
2751 EndLoc);
2752 // (Class)objc_getClass("CurrentClass")
2753 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2754 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002755 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002756 ClsExprs.clear();
2757 ClsExprs.push_back(ArgExpr);
2758 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2759 &ClsExprs[0], ClsExprs.size(),
2760 StartLoc, EndLoc);
2761
2762 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2763 // To turn off a warning, type-cast to 'id'
2764 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2765 NoTypeInfoCStyleCastExpr(Context,
2766 Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002767 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002768 // struct objc_super
2769 QualType superType = getSuperStructType();
2770 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002771
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 if (LangOpts.Microsoft) {
2773 SynthSuperContructorFunctionDecl();
2774 // Simulate a contructor call...
2775 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2776 superType, SourceLocation());
2777 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2778 InitExprs.size(),
2779 superType, SourceLocation());
2780 // The code for super is a little tricky to prevent collision with
2781 // the structure definition in the header. The rewriter has it's own
2782 // internal definition (__rw_objc_super) that is uses. This is why
2783 // we need the cast below. For example:
2784 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2785 //
John McCalle3027922010-08-25 11:45:40 +00002786 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 Context->getPointerType(SuperRep->getType()),
2788 SourceLocation());
2789 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2790 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002791 CK_Unknown, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002792 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002793 // (struct objc_super) { <exprs from above> }
2794 InitListExpr *ILE =
2795 new (Context) InitListExpr(*Context, SourceLocation(),
2796 &InitExprs[0], InitExprs.size(),
2797 SourceLocation());
2798 TypeSourceInfo *superTInfo
2799 = Context->getTrivialTypeSourceInfo(superType);
2800 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2801 superType, ILE, false);
2802 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002803 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002804 Context->getPointerType(SuperRep->getType()),
2805 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002806 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002807 MsgExprs.push_back(SuperRep);
2808 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002809 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002810
2811 case ObjCMessageExpr::Class: {
2812 llvm::SmallVector<Expr*, 8> ClsExprs;
2813 QualType argType = Context->getPointerType(Context->CharTy);
2814 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002815 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002816 IdentifierInfo *clsName = Class->getIdentifier();
2817 ClsExprs.push_back(StringLiteral::Create(*Context,
2818 clsName->getNameStart(),
2819 clsName->getLength(),
2820 false, argType,
2821 SourceLocation()));
2822 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2823 &ClsExprs[0],
2824 ClsExprs.size(),
2825 StartLoc, EndLoc);
2826 MsgExprs.push_back(Cls);
2827 break;
2828 }
2829
2830 case ObjCMessageExpr::SuperInstance:{
2831 MsgSendFlavor = MsgSendSuperFunctionDecl;
2832 if (MsgSendStretFlavor)
2833 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2834 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2835 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2836 llvm::SmallVector<Expr*, 4> InitExprs;
2837
2838 InitExprs.push_back(
2839 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002840 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002841 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2842 Context->getObjCIdType(),
2843 SourceLocation()))
2844 ); // set the 'receiver'.
2845
2846 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2847 llvm::SmallVector<Expr*, 8> ClsExprs;
2848 QualType argType = Context->getPointerType(Context->CharTy);
2849 ClsExprs.push_back(StringLiteral::Create(*Context,
2850 ClassDecl->getIdentifier()->getNameStart(),
2851 ClassDecl->getIdentifier()->getLength(),
2852 false, argType, SourceLocation()));
2853 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2854 &ClsExprs[0],
2855 ClsExprs.size(),
2856 StartLoc, EndLoc);
2857 // (Class)objc_getClass("CurrentClass")
2858 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2859 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002860 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002861 ClsExprs.clear();
2862 ClsExprs.push_back(ArgExpr);
2863 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2864 &ClsExprs[0], ClsExprs.size(),
2865 StartLoc, EndLoc);
2866
2867 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2868 // To turn off a warning, type-cast to 'id'
2869 InitExprs.push_back(
2870 // set 'super class', using class_getSuperclass().
2871 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002872 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002873 // struct objc_super
2874 QualType superType = getSuperStructType();
2875 Expr *SuperRep;
2876
2877 if (LangOpts.Microsoft) {
2878 SynthSuperContructorFunctionDecl();
2879 // Simulate a contructor call...
2880 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2881 superType, SourceLocation());
2882 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2883 InitExprs.size(),
2884 superType, SourceLocation());
2885 // The code for super is a little tricky to prevent collision with
2886 // the structure definition in the header. The rewriter has it's own
2887 // internal definition (__rw_objc_super) that is uses. This is why
2888 // we need the cast below. For example:
2889 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2890 //
John McCalle3027922010-08-25 11:45:40 +00002891 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002892 Context->getPointerType(SuperRep->getType()),
2893 SourceLocation());
2894 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2895 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002896 CK_Unknown, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002897 } else {
2898 // (struct objc_super) { <exprs from above> }
2899 InitListExpr *ILE =
2900 new (Context) InitListExpr(*Context, SourceLocation(),
2901 &InitExprs[0], InitExprs.size(),
2902 SourceLocation());
2903 TypeSourceInfo *superTInfo
2904 = Context->getTrivialTypeSourceInfo(superType);
2905 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2906 superType, ILE, false);
2907 }
2908 MsgExprs.push_back(SuperRep);
2909 break;
2910 }
2911
2912 case ObjCMessageExpr::Instance: {
2913 // Remove all type-casts because it may contain objc-style types; e.g.
2914 // Foo<Proto> *.
2915 Expr *recExpr = Exp->getInstanceReceiver();
2916 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2917 recExpr = CE->getSubExpr();
2918 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002919 CK_Unknown, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002920 MsgExprs.push_back(recExpr);
2921 break;
2922 }
2923 }
2924
Steve Naroffa397efd2007-11-03 11:27:19 +00002925 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002926 llvm::SmallVector<Expr*, 8> SelExprs;
2927 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002928 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002929 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002930 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002931 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002932 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002933 &SelExprs[0], SelExprs.size(),
2934 StartLoc,
2935 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002936 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002937
Steve Naroff574440f2007-10-24 22:48:43 +00002938 // Now push any user supplied arguments.
2939 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002940 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002941 // Make all implicit casts explicit...ICE comes in handy:-)
2942 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2943 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002944 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002945 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002946 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002947 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002948 (void)convertBlockPointerToFunctionPointer(type);
John McCalle3027922010-08-25 11:45:40 +00002949 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00002950 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002951 }
2952 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002953 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002954 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002955 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002956 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002957 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002958 CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002959 }
Mike Stump11289f42009-09-09 15:08:12 +00002960 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002961 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002962 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2963 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002964 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002965 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002966 }
Steve Narofff36987c2007-11-04 22:37:50 +00002967 // Generate the funky cast.
2968 CastExpr *cast;
2969 llvm::SmallVector<QualType, 8> ArgTypes;
2970 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Steve Narofff36987c2007-11-04 22:37:50 +00002972 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002973 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2974 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2975 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002976 ArgTypes.push_back(Context->getObjCIdType());
2977 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002978 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002979 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002980 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2981 E = OMD->param_end(); PI != E; ++PI) {
2982 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002983 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002984 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002985 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002986 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002987 ArgTypes.push_back(t);
2988 }
Chris Lattnera4997152009-02-20 18:43:26 +00002989 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2990 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002991 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002992 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002993 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002994 }
2995 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002996 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002997
Steve Narofff36987c2007-11-04 22:37:50 +00002998 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002999 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003000 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003001
Mike Stump11289f42009-09-09 15:08:12 +00003002 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003003 // If we don't do this cast, we get the following bizarre warning/note:
3004 // xx.m:13: warning: function called through a non-compatible type
3005 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003006 cast = NoTypeInfoCStyleCastExpr(Context,
3007 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00003008 CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003009
Steve Narofff36987c2007-11-04 22:37:50 +00003010 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003011 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003012 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003013 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003014 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003015 false, false, 0, 0,
3016 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003017 castType = Context->getPointerType(castType);
John McCalle3027922010-08-25 11:45:40 +00003018 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003019 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003020
3021 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003022 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003023
John McCall9dd450b2009-09-21 23:43:11 +00003024 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003025 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003026 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003027 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003028 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003029 if (MsgSendStretFlavor) {
3030 // We have the method which returns a struct/union. Must also generate
3031 // call to objc_msgSend_stret and hang both varieties on a conditional
3032 // expression which dictate which one to envoke depending on size of
3033 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003034
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003035 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003036 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003037 SourceLocation());
3038 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003039 cast = NoTypeInfoCStyleCastExpr(Context,
3040 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00003041 CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003042 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003043 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003044 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003045 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003046 false, false, 0, 0,
3047 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003048 castType = Context->getPointerType(castType);
John McCalle3027922010-08-25 11:45:40 +00003049 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003050 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003051
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003052 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003053 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003054
John McCall9dd450b2009-09-21 23:43:11 +00003055 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003056 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003057 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003058 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003059
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003060 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003061 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003062 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003063 Context->getSizeType(),
3064 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003065 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3066 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3067 // For X86 it is more complicated and some kind of target specific routine
3068 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003069 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003070 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003071 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3072 llvm::APInt(IntSize, 8),
3073 Context->IntTy,
3074 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003075 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCalle3027922010-08-25 11:45:40 +00003076 BO_LE,
Mike Stump11289f42009-09-09 15:08:12 +00003077 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003078 SourceLocation());
3079 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003080 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003081 new (Context) ConditionalOperator(lessThanExpr,
3082 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003083 SourceLocation(), STCE, (Expr*)0,
3084 returnType);
3085 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3086 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003087 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003088 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003089 return ReplacingStmt;
3090}
3091
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003092Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003093 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3094 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003095
Steve Naroff574440f2007-10-24 22:48:43 +00003096 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003097 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003098
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003099 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003100 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003101}
3102
Steve Naroffd9803712009-04-29 16:37:50 +00003103// typedef struct objc_object Protocol;
3104QualType RewriteObjC::getProtocolType() {
3105 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003106 TypeSourceInfo *TInfo
3107 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003108 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003109 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003110 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003111 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003112 }
3113 return Context->getTypeDeclType(ProtocolTypeDecl);
3114}
3115
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003116/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003117/// a synthesized/forward data reference (to the protocol's metadata).
3118/// The forward references (and metadata) are generated in
3119/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003120Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003121 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3122 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003123 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003124 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003125 SC_Extern, SC_None);
Steve Naroffd9803712009-04-29 16:37:50 +00003126 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003127 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003128 Context->getPointerType(DRE->getType()),
3129 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003130 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalle3027922010-08-25 11:45:40 +00003131 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003132 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003133 ReplaceStmt(Exp, castExpr);
3134 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003135 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003136 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003137
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003138}
3139
Mike Stump11289f42009-09-09 15:08:12 +00003140bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003141 const char *endBuf) {
3142 while (startBuf < endBuf) {
3143 if (*startBuf == '#') {
3144 // Skip whitespace.
3145 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3146 ;
3147 if (!strncmp(startBuf, "if", strlen("if")) ||
3148 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3149 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3150 !strncmp(startBuf, "define", strlen("define")) ||
3151 !strncmp(startBuf, "undef", strlen("undef")) ||
3152 !strncmp(startBuf, "else", strlen("else")) ||
3153 !strncmp(startBuf, "elif", strlen("elif")) ||
3154 !strncmp(startBuf, "endif", strlen("endif")) ||
3155 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3156 !strncmp(startBuf, "include", strlen("include")) ||
3157 !strncmp(startBuf, "import", strlen("import")) ||
3158 !strncmp(startBuf, "include_next", strlen("include_next")))
3159 return true;
3160 }
3161 startBuf++;
3162 }
3163 return false;
3164}
3165
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003166/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003167/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003168void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003169 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003170 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003171 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003172 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003173 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003174 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003175 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003176 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003177 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003178 SourceLocation LocStart = CDecl->getLocStart();
3179 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003180
Steve Naroffdde78982007-11-14 19:25:57 +00003181 const char *startBuf = SM->getCharacterData(LocStart);
3182 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003183
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003184 // If no ivars and no root or if its root, directly or indirectly,
3185 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003186 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3187 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003188 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003189 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003190 return;
3191 }
Mike Stump11289f42009-09-09 15:08:12 +00003192
3193 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003194 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003195 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003196 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003197 if (LangOpts.Microsoft)
3198 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003199
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003200 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003201 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003202 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003203 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003204 // If the buffer contains preprocessor directives, we do more fine-grained
3205 // rewrites. This is intended to fix code that looks like (which occurs in
3206 // NSURL.h, for example):
3207 //
3208 // #ifdef XYZ
3209 // @interface Foo : NSObject
3210 // #else
3211 // @interface FooBar : NSObject
3212 // #endif
3213 // {
3214 // int i;
3215 // }
3216 // @end
3217 //
3218 // This clause is segregated to avoid breaking the common case.
3219 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003220 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003221 CDecl->getClassLoc();
3222 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003223 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003224
Chris Lattnerf5b77512009-02-20 18:18:36 +00003225 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003226 // advance to the end of the referenced protocols.
3227 while (endHeader < cursor && *endHeader != '>') endHeader++;
3228 endHeader++;
3229 }
3230 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003231 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003232 } else {
3233 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003234 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003235 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003236 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003237 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003238 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003239 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003240 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003241 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003242
Steve Naroffdde78982007-11-14 19:25:57 +00003243 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003244 SourceLocation OnePastCurly =
3245 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003246 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003247 }
3248 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003249
Steve Naroffdde78982007-11-14 19:25:57 +00003250 // Now comment out any visibility specifiers.
3251 while (cursor < endBuf) {
3252 if (*cursor == '@') {
3253 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003254 // Skip whitespace.
3255 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3256 /*scan*/;
3257
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003258 // FIXME: presence of @public, etc. inside comment results in
3259 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003260 if (!strncmp(cursor, "public", strlen("public")) ||
3261 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003262 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003263 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003264 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003265 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003266 // FIXME: If there are cases where '<' is used in ivar declaration part
3267 // of user code, then scan the ivar list and use needToScanForQualifiers
3268 // for type checking.
3269 else if (*cursor == '<') {
3270 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003271 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003272 cursor = strchr(cursor, '>');
3273 cursor++;
3274 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003275 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003276 } else if (*cursor == '^') { // rewrite block specifier.
3277 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003278 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003279 }
Steve Naroffdde78982007-11-14 19:25:57 +00003280 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003281 }
Steve Naroffdde78982007-11-14 19:25:57 +00003282 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003283 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003284 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003285 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003286 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003287 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003288 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003289 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003290 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003291 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003292 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003293 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003294 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003295 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003296}
3297
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003298// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003299/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003300template<typename MethodIterator>
3301void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3302 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003303 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003304 llvm::StringRef prefix,
3305 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003306 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003307 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003308
Chris Lattner31bc07e2007-12-12 07:46:12 +00003309 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003310 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003311 SEL _cmd;
3312 char *method_types;
3313 void *_imp;
3314 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003315 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003316 Result += "\nstruct _objc_method {\n";
3317 Result += "\tSEL _cmd;\n";
3318 Result += "\tchar *method_types;\n";
3319 Result += "\tvoid *_imp;\n";
3320 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003321
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003325 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003326
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003327 /* struct {
3328 struct _objc_method_list *next_method;
3329 int method_count;
3330 struct _objc_method method_list[];
3331 }
3332 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003333 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003334 Result += "\nstatic struct {\n";
3335 Result += "\tstruct _objc_method_list *next_method;\n";
3336 Result += "\tint method_count;\n";
3337 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003338 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003339 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003340 Result += prefix;
3341 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3342 Result += "_METHODS_";
3343 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003344 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003345 Result += IsInstanceMethod ? "inst" : "cls";
3346 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003347 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003348
Chris Lattner31bc07e2007-12-12 07:46:12 +00003349 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003350 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003351 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003352 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003353 Result += "\", \"";
3354 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003355 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003356 Result += MethodInternalNames[*MethodBegin];
3357 Result += "}\n";
3358 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3359 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003360 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003361 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003362 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003363 Result += "\", \"";
3364 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003365 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003366 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003367 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003368 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003369 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003370}
3371
Steve Naroffd9803712009-04-29 16:37:50 +00003372/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003373void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003374RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3375 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003376 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003377
3378 // Output struct protocol_methods holder of method selector and type.
3379 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3380 /* struct protocol_methods {
3381 SEL _cmd;
3382 char *method_types;
3383 }
3384 */
3385 Result += "\nstruct _protocol_methods {\n";
3386 Result += "\tstruct objc_selector *_cmd;\n";
3387 Result += "\tchar *method_types;\n";
3388 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003389
Steve Naroffd9803712009-04-29 16:37:50 +00003390 objc_protocol_methods = true;
3391 }
3392 // Do not synthesize the protocol more than once.
3393 if (ObjCSynthesizedProtocols.count(PDecl))
3394 return;
Mike Stump11289f42009-09-09 15:08:12 +00003395
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003396 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3397 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3398 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003399 /* struct _objc_protocol_method_list {
3400 int protocol_method_count;
3401 struct protocol_methods protocols[];
3402 }
Steve Naroff251084d2008-03-12 01:06:30 +00003403 */
Steve Naroffd9803712009-04-29 16:37:50 +00003404 Result += "\nstatic struct {\n";
3405 Result += "\tint protocol_method_count;\n";
3406 Result += "\tstruct _protocol_methods protocol_methods[";
3407 Result += utostr(NumMethods);
3408 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3409 Result += PDecl->getNameAsString();
3410 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3411 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003412
Steve Naroffd9803712009-04-29 16:37:50 +00003413 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003414 for (ObjCProtocolDecl::instmeth_iterator
3415 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003416 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003417 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003418 Result += "\t ,{{(struct objc_selector *)\"";
3419 else
3420 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003421 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003422 std::string MethodTypeString;
3423 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3424 Result += "\", \"";
3425 Result += MethodTypeString;
3426 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003427 }
Steve Naroffd9803712009-04-29 16:37:50 +00003428 Result += "\t }\n};\n";
3429 }
Mike Stump11289f42009-09-09 15:08:12 +00003430
Steve Naroffd9803712009-04-29 16:37:50 +00003431 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003432 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3433 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003434 if (NumMethods > 0) {
3435 /* struct _objc_protocol_method_list {
3436 int protocol_method_count;
3437 struct protocol_methods protocols[];
3438 }
3439 */
3440 Result += "\nstatic struct {\n";
3441 Result += "\tint protocol_method_count;\n";
3442 Result += "\tstruct _protocol_methods protocol_methods[";
3443 Result += utostr(NumMethods);
3444 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3445 Result += PDecl->getNameAsString();
3446 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3447 "{\n\t";
3448 Result += utostr(NumMethods);
3449 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003450
Steve Naroffd9803712009-04-29 16:37:50 +00003451 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003452 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003453 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003454 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003455 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003456 Result += "\t ,{{(struct objc_selector *)\"";
3457 else
3458 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003459 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003460 std::string MethodTypeString;
3461 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3462 Result += "\", \"";
3463 Result += MethodTypeString;
3464 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003465 }
Steve Naroffd9803712009-04-29 16:37:50 +00003466 Result += "\t }\n};\n";
3467 }
3468
3469 // Output:
3470 /* struct _objc_protocol {
3471 // Objective-C 1.0 extensions
3472 struct _objc_protocol_extension *isa;
3473 char *protocol_name;
3474 struct _objc_protocol **protocol_list;
3475 struct _objc_protocol_method_list *instance_methods;
3476 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003477 };
Steve Naroffd9803712009-04-29 16:37:50 +00003478 */
3479 static bool objc_protocol = false;
3480 if (!objc_protocol) {
3481 Result += "\nstruct _objc_protocol {\n";
3482 Result += "\tstruct _objc_protocol_extension *isa;\n";
3483 Result += "\tchar *protocol_name;\n";
3484 Result += "\tstruct _objc_protocol **protocol_list;\n";
3485 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3486 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003487 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003488
Steve Naroffd9803712009-04-29 16:37:50 +00003489 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003490 }
Mike Stump11289f42009-09-09 15:08:12 +00003491
Steve Naroffd9803712009-04-29 16:37:50 +00003492 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3493 Result += PDecl->getNameAsString();
3494 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3495 "{\n\t0, \"";
3496 Result += PDecl->getNameAsString();
3497 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003498 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003499 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3500 Result += PDecl->getNameAsString();
3501 Result += ", ";
3502 }
3503 else
3504 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003505 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003506 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3507 Result += PDecl->getNameAsString();
3508 Result += "\n";
3509 }
3510 else
3511 Result += "0\n";
3512 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003513
Steve Naroffd9803712009-04-29 16:37:50 +00003514 // Mark this protocol as having been generated.
3515 if (!ObjCSynthesizedProtocols.insert(PDecl))
3516 assert(false && "protocol already synthesized");
3517
3518}
3519
3520void RewriteObjC::
3521RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003522 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003523 std::string &Result) {
3524 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003525
Steve Naroffd9803712009-04-29 16:37:50 +00003526 for (unsigned i = 0; i != Protocols.size(); i++)
3527 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3528
Chris Lattner388f6e92008-07-21 21:33:21 +00003529 // Output the top lovel protocol meta-data for the class.
3530 /* struct _objc_protocol_list {
3531 struct _objc_protocol_list *next;
3532 int protocol_count;
3533 struct _objc_protocol *class_protocols[];
3534 }
3535 */
3536 Result += "\nstatic struct {\n";
3537 Result += "\tstruct _objc_protocol_list *next;\n";
3538 Result += "\tint protocol_count;\n";
3539 Result += "\tstruct _objc_protocol *class_protocols[";
3540 Result += utostr(Protocols.size());
3541 Result += "];\n} _OBJC_";
3542 Result += prefix;
3543 Result += "_PROTOCOLS_";
3544 Result += ClassName;
3545 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3546 "{\n\t0, ";
3547 Result += utostr(Protocols.size());
3548 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003549
Chris Lattner388f6e92008-07-21 21:33:21 +00003550 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003551 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003552 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003553
Chris Lattner388f6e92008-07-21 21:33:21 +00003554 for (unsigned i = 1; i != Protocols.size(); i++) {
3555 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003556 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003557 Result += "\n";
3558 }
3559 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003560}
3561
Steve Naroffd9803712009-04-29 16:37:50 +00003562
Mike Stump11289f42009-09-09 15:08:12 +00003563/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003564/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003565void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003566 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003567 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003568 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003569 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003570 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003571 CDecl = CDecl->getNextClassCategory())
3572 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3573 break;
Mike Stump11289f42009-09-09 15:08:12 +00003574
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003575 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003576 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003577 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003578
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003579 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003580 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003581 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003582
3583 // If any of our property implementations have associated getters or
3584 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003585 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3586 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003587 Prop != PropEnd; ++Prop) {
3588 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3589 continue;
3590 if (!(*Prop)->getPropertyIvarDecl())
3591 continue;
3592 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3593 if (!PD)
3594 continue;
3595 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3596 InstanceMethods.push_back(Getter);
3597 if (PD->isReadOnly())
3598 continue;
3599 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3600 InstanceMethods.push_back(Setter);
3601 }
3602 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003603 true, "CATEGORY_", FullCategoryName.c_str(),
3604 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003605
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003606 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003607 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003608 false, "CATEGORY_", FullCategoryName.c_str(),
3609 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003610
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003611 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003612 // Null CDecl is case of a category implementation with no category interface
3613 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003614 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003615 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003616 /* struct _objc_category {
3617 char *category_name;
3618 char *class_name;
3619 struct _objc_method_list *instance_methods;
3620 struct _objc_method_list *class_methods;
3621 struct _objc_protocol_list *protocols;
3622 // Objective-C 1.0 extensions
3623 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003624 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003625 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003626 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003627 */
Mike Stump11289f42009-09-09 15:08:12 +00003628
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003629 static bool objc_category = false;
3630 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += "\nstruct _objc_category {\n";
3632 Result += "\tchar *category_name;\n";
3633 Result += "\tchar *class_name;\n";
3634 Result += "\tstruct _objc_method_list *instance_methods;\n";
3635 Result += "\tstruct _objc_method_list *class_methods;\n";
3636 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003637 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += "\tstruct _objc_property_list *instance_properties;\n";
3639 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003640 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003641 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3643 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003644 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003645 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003646 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003647 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003648 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003649
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003650 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003651 Result += "\t, (struct _objc_method_list *)"
3652 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3653 Result += FullCategoryName;
3654 Result += "\n";
3655 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003656 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003657 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003658 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003659 Result += "\t, (struct _objc_method_list *)"
3660 "&_OBJC_CATEGORY_CLASS_METHODS_";
3661 Result += FullCategoryName;
3662 Result += "\n";
3663 }
3664 else
3665 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003666
Chris Lattnerf5b77512009-02-20 18:18:36 +00003667 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003668 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003669 Result += FullCategoryName;
3670 Result += "\n";
3671 }
3672 else
3673 Result += "\t, 0\n";
3674 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003675}
3676
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003677/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3678/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003679void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003680 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003681 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003682 if (ivar->isBitField()) {
3683 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3684 // place all bitfields at offset 0.
3685 Result += "0";
3686 } else {
3687 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003688 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003689 if (LangOpts.Microsoft)
3690 Result += "_IMPL";
3691 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003692 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003693 Result += ")";
3694 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003695}
3696
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003697//===----------------------------------------------------------------------===//
3698// Meta Data Emission
3699//===----------------------------------------------------------------------===//
3700
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003701void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003703 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003704
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003705 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003706 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003707 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003708 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003709 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003710 }
Mike Stump11289f42009-09-09 15:08:12 +00003711
Chris Lattner30d23e82007-12-12 07:56:42 +00003712 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003713 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003714 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003715 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003716 if (NumIvars > 0) {
3717 static bool objc_ivar = false;
3718 if (!objc_ivar) {
3719 /* struct _objc_ivar {
3720 char *ivar_name;
3721 char *ivar_type;
3722 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003723 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003724 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003725 Result += "\nstruct _objc_ivar {\n";
3726 Result += "\tchar *ivar_name;\n";
3727 Result += "\tchar *ivar_type;\n";
3728 Result += "\tint ivar_offset;\n";
3729 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003730
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003731 objc_ivar = true;
3732 }
3733
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003734 /* struct {
3735 int ivar_count;
3736 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003737 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003738 */
Mike Stump11289f42009-09-09 15:08:12 +00003739 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003740 Result += "\tint ivar_count;\n";
3741 Result += "\tstruct _objc_ivar ivar_list[";
3742 Result += utostr(NumIvars);
3743 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003744 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003745 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003746 "{\n\t";
3747 Result += utostr(NumIvars);
3748 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003749
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003750 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003751 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003752 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003753 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003754 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003755 IV != IVEnd; ++IV)
3756 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003757 IVI = IDecl->ivar_begin();
3758 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003759 } else {
3760 IVI = CDecl->ivar_begin();
3761 IVE = CDecl->ivar_end();
3762 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003763 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003764 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003765 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003766 std::string TmpString, StrEncoding;
3767 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3768 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003769 Result += StrEncoding;
3770 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003771 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003772 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003773 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003774 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003775 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003776 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003777 std::string TmpString, StrEncoding;
3778 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3779 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003780 Result += StrEncoding;
3781 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003782 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003783 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003784 }
Mike Stump11289f42009-09-09 15:08:12 +00003785
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003786 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003787 }
Mike Stump11289f42009-09-09 15:08:12 +00003788
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003789 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003790 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003791 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003792
3793 // If any of our property implementations have associated getters or
3794 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003795 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3796 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003797 Prop != PropEnd; ++Prop) {
3798 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3799 continue;
3800 if (!(*Prop)->getPropertyIvarDecl())
3801 continue;
3802 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3803 if (!PD)
3804 continue;
3805 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3806 InstanceMethods.push_back(Getter);
3807 if (PD->isReadOnly())
3808 continue;
3809 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3810 InstanceMethods.push_back(Setter);
3811 }
3812 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003813 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003814
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003815 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003816 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003817 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003818
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003819 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003820 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003821 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003822
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003823 // Declaration of class/meta-class metadata
3824 /* struct _objc_class {
3825 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003826 const char *super_class_name;
3827 char *name;
3828 long version;
3829 long info;
3830 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003831 struct _objc_ivar_list *ivars;
3832 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003833 struct objc_cache *cache;
3834 struct objc_protocol_list *protocols;
3835 const char *ivar_layout;
3836 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003837 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003838 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003839 static bool objc_class = false;
3840 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003841 Result += "\nstruct _objc_class {\n";
3842 Result += "\tstruct _objc_class *isa;\n";
3843 Result += "\tconst char *super_class_name;\n";
3844 Result += "\tchar *name;\n";
3845 Result += "\tlong version;\n";
3846 Result += "\tlong info;\n";
3847 Result += "\tlong instance_size;\n";
3848 Result += "\tstruct _objc_ivar_list *ivars;\n";
3849 Result += "\tstruct _objc_method_list *methods;\n";
3850 Result += "\tstruct objc_cache *cache;\n";
3851 Result += "\tstruct _objc_protocol_list *protocols;\n";
3852 Result += "\tconst char *ivar_layout;\n";
3853 Result += "\tstruct _objc_class_ext *ext;\n";
3854 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003855 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003858 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003859 ObjCInterfaceDecl *RootClass = 0;
3860 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003861 while (SuperClass) {
3862 RootClass = SuperClass;
3863 SuperClass = SuperClass->getSuperClass();
3864 }
3865 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003866
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003867 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003868 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003869 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003870 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003871 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003872 Result += "\"";
3873
3874 if (SuperClass) {
3875 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003876 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003877 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003878 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003879 Result += "\"";
3880 }
3881 else {
3882 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003883 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003884 Result += "\"";
3885 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003886 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003887 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003888 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003889 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003890 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003892 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003893 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003894 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003895 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003896 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003897 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003898 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003899 Result += ",0,0\n";
3900 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003901 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003902 Result += "\t,0,0,0,0\n";
3903 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003904
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003905 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003906 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003907 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003908 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003909 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003910 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003911 if (SuperClass) {
3912 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003913 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003914 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003915 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003916 Result += "\"";
3917 }
3918 else {
3919 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003921 Result += "\"";
3922 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003923 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003924 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003925 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003926 Result += ",0";
3927 else {
3928 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003929 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003930 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003931 if (LangOpts.Microsoft)
3932 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003933 Result += ")";
3934 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003935 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003936 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003937 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003938 Result += "\n\t";
3939 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003940 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003941 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003942 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003943 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003944 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003945 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003946 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003947 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003948 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003949 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003950 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003952 Result += ", 0,0\n";
3953 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003954 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003955 Result += ",0,0,0\n";
3956 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003957}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003958
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003959/// RewriteImplementations - This routine rewrites all method implementations
3960/// and emits meta-data.
3961
Steve Narofff8cfd162008-11-13 20:07:04 +00003962void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003963 int ClsDefCount = ClassImplementation.size();
3964 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003965
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003966 // Rewrite implemented methods
3967 for (int i = 0; i < ClsDefCount; i++)
3968 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003969
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003970 for (int i = 0; i < CatDefCount; i++)
3971 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003972}
Mike Stump11289f42009-09-09 15:08:12 +00003973
Steve Narofff8cfd162008-11-13 20:07:04 +00003974void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3975 int ClsDefCount = ClassImplementation.size();
3976 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003977
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003978 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003979 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003980 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003981
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003982 // For each implemented category, write out all its meta data.
3983 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003984 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003985
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003986 // Write objc_symtab metadata
3987 /*
3988 struct _objc_symtab
3989 {
3990 long sel_ref_cnt;
3991 SEL *refs;
3992 short cls_def_cnt;
3993 short cat_def_cnt;
3994 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003995 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003996 */
Mike Stump11289f42009-09-09 15:08:12 +00003997
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003998 Result += "\nstruct _objc_symtab {\n";
3999 Result += "\tlong sel_ref_cnt;\n";
4000 Result += "\tSEL *refs;\n";
4001 Result += "\tshort cls_def_cnt;\n";
4002 Result += "\tshort cat_def_cnt;\n";
4003 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4004 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004005
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004006 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004007 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004008 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004009 + ", " + utostr(CatDefCount) + "\n";
4010 for (int i = 0; i < ClsDefCount; i++) {
4011 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004012 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004013 Result += "\n";
4014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004016 for (int i = 0; i < CatDefCount; i++) {
4017 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004018 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004019 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004020 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004021 Result += "\n";
4022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004024 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004025
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004026 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004027
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004028 /*
4029 struct _objc_module {
4030 long version;
4031 long size;
4032 const char *name;
4033 struct _objc_symtab *symtab;
4034 }
4035 */
Mike Stump11289f42009-09-09 15:08:12 +00004036
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004037 Result += "\nstruct _objc_module {\n";
4038 Result += "\tlong version;\n";
4039 Result += "\tlong size;\n";
4040 Result += "\tconst char *name;\n";
4041 Result += "\tstruct _objc_symtab *symtab;\n";
4042 Result += "};\n\n";
4043 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004044 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004045 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004046 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004047 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004048
4049 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004050 if (ProtocolExprDecls.size()) {
4051 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4052 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004053 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004054 E = ProtocolExprDecls.end(); I != E; ++I) {
4055 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4056 Result += (*I)->getNameAsString();
4057 Result += " = &_OBJC_PROTOCOL_";
4058 Result += (*I)->getNameAsString();
4059 Result += ";\n";
4060 }
4061 Result += "#pragma data_seg(pop)\n\n";
4062 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004063 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004064 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004065 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4066 Result += "&_OBJC_MODULES;\n";
4067 Result += "#pragma data_seg(pop)\n\n";
4068 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004069}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004070
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004071void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4072 const std::string &Name,
4073 ValueDecl *VD) {
4074 assert(BlockByRefDeclNo.count(VD) &&
4075 "RewriteByRefString: ByRef decl missing");
4076 ResultStr += "struct __Block_byref_" + Name +
4077 "_" + utostr(BlockByRefDeclNo[VD]) ;
4078}
4079
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004080static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4081 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4082 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4083 return false;
4084}
4085
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004087 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 std::string Tag) {
4089 const FunctionType *AFT = CE->getFunctionType();
4090 QualType RT = AFT->getResultType();
4091 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004092 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004093 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004094
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004096
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004097 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004098 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004099 // block (to reference imported block decl refs).
4100 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101 } else if (BD->param_empty()) {
4102 S += "(" + StructRef + " *__cself)";
4103 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004104 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004105 assert(FT && "SynthesizeBlockFunc: No function proto");
4106 S += '(';
4107 // first add the implicit argument.
4108 S += StructRef + " *__cself, ";
4109 std::string ParamStr;
4110 for (BlockDecl::param_iterator AI = BD->param_begin(),
4111 E = BD->param_end(); AI != E; ++AI) {
4112 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004113 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004114 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004115 if (convertBlockPointerToFunctionPointer(QT))
4116 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004117 else
4118 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 S += ParamStr;
4120 }
4121 if (FT->isVariadic()) {
4122 if (!BD->param_empty()) S += ", ";
4123 S += "...";
4124 }
4125 S += ')';
4126 }
4127 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004128
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129 // Create local declarations to avoid rewriting all closure decl ref exprs.
4130 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004131 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 E = BlockByRefDecls.end(); I != E; ++I) {
4133 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004134 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004135 std::string TypeString;
4136 RewriteByRefString(TypeString, Name, (*I));
4137 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004138 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004139 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004140 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004142 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143 E = BlockByCopyDecls.end(); I != E; ++I) {
4144 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004145 // Handle nested closure invocation. For example:
4146 //
4147 // void (^myImportedClosure)(void);
4148 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004149 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004150 // void (^anotherClosure)(void);
4151 // anotherClosure = ^(void) {
4152 // myImportedClosure(); // import and invoke the closure
4153 // };
4154 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004155 if (isTopLevelBlockPointerType((*I)->getType())) {
4156 RewriteBlockPointerTypeVariable(S, (*I));
4157 S += " = (";
4158 RewriteBlockPointerType(S, (*I)->getType());
4159 S += ")";
4160 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4161 }
4162 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004163 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004164 QualType QT = (*I)->getType();
4165 if (HasLocalVariableExternalStorage(*I))
4166 QT = Context->getPointerType(QT);
4167 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004168 S += Name + " = __cself->" +
4169 (*I)->getNameAsString() + "; // bound by copy\n";
4170 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 }
4172 std::string RewrittenStr = RewrittenBlockExprs[CE];
4173 const char *cstr = RewrittenStr.c_str();
4174 while (*cstr++ != '{') ;
4175 S += cstr;
4176 S += "\n";
4177 return S;
4178}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004179
Steve Naroff677ab3a2008-10-27 17:20:55 +00004180std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004181 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004182 std::string Tag) {
4183 std::string StructRef = "struct " + Tag;
4184 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004185
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186 S += funcName;
4187 S += "_block_copy_" + utostr(i);
4188 S += "(" + StructRef;
4189 S += "*dst, " + StructRef;
4190 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004191 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004192 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004193 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004194 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004195 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004196 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004197 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004198 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004199 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004200 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004201 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004202 S += "}\n";
4203
Steve Naroff677ab3a2008-10-27 17:20:55 +00004204 S += "\nstatic void __";
4205 S += funcName;
4206 S += "_block_dispose_" + utostr(i);
4207 S += "(" + StructRef;
4208 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004209 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004210 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004211 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004212 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004213 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004214 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004215 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004216 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004219 return S;
4220}
4221
Steve Naroff30484702009-12-06 21:14:13 +00004222std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4223 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004224 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004225 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004226
Steve Naroff677ab3a2008-10-27 17:20:55 +00004227 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004228 S += " struct " + Desc;
4229 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004230
Steve Naroff30484702009-12-06 21:14:13 +00004231 Constructor += "(void *fp, "; // Invoke function pointer.
4232 Constructor += "struct " + Desc; // Descriptor pointer.
4233 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004234
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 if (BlockDeclRefs.size()) {
4236 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004237 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004238 E = BlockByCopyDecls.end(); I != E; ++I) {
4239 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004240 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 std::string ArgName = "_" + FieldName;
4242 // Handle nested closure invocation. For example:
4243 //
4244 // void (^myImportedBlock)(void);
4245 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004246 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 // void (^anotherBlock)(void);
4248 // anotherBlock = ^(void) {
4249 // myImportedBlock(); // import and invoke the closure
4250 // };
4251 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004252 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004253 S += "struct __block_impl *";
4254 Constructor += ", void *" + ArgName;
4255 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004256 QualType QT = (*I)->getType();
4257 if (HasLocalVariableExternalStorage(*I))
4258 QT = Context->getPointerType(QT);
4259 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4260 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004261 Constructor += ", " + ArgName;
4262 }
4263 S += FieldName + ";\n";
4264 }
4265 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004266 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 E = BlockByRefDecls.end(); I != E; ++I) {
4268 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004269 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004270 std::string ArgName = "_" + FieldName;
4271 // Handle nested closure invocation. For example:
4272 //
4273 // void (^myImportedBlock)(void);
4274 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004275 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004276 // void (^anotherBlock)(void);
4277 // anotherBlock = ^(void) {
4278 // myImportedBlock(); // import and invoke the closure
4279 // };
4280 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004281 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 S += "struct __block_impl *";
4283 Constructor += ", void *" + ArgName;
4284 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004285 std::string TypeString;
4286 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004287 TypeString += " *";
4288 FieldName = TypeString + FieldName;
4289 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004290 Constructor += ", " + ArgName;
4291 }
4292 S += FieldName + "; // by ref\n";
4293 }
4294 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004295 Constructor += ", int flags=0)";
4296 // Initialize all "by copy" arguments.
4297 bool firsTime = true;
4298 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4299 E = BlockByCopyDecls.end(); I != E; ++I) {
4300 std::string Name = (*I)->getNameAsString();
4301 if (firsTime) {
4302 Constructor += " : ";
4303 firsTime = false;
4304 }
4305 else
4306 Constructor += ", ";
4307 if (isTopLevelBlockPointerType((*I)->getType()))
4308 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4309 else
4310 Constructor += Name + "(_" + Name + ")";
4311 }
4312 // Initialize all "by ref" arguments.
4313 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4314 E = BlockByRefDecls.end(); I != E; ++I) {
4315 std::string Name = (*I)->getNameAsString();
4316 if (firsTime) {
4317 Constructor += " : ";
4318 firsTime = false;
4319 }
4320 else
4321 Constructor += ", ";
4322 if (isTopLevelBlockPointerType((*I)->getType()))
4323 Constructor += Name + "((struct __block_impl *)_"
4324 + Name + "->__forwarding)";
4325 else
4326 Constructor += Name + "(_" + Name + "->__forwarding)";
4327 }
4328
4329 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004330 if (GlobalVarDecl)
4331 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4332 else
4333 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004334 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004335
Steve Naroff30484702009-12-06 21:14:13 +00004336 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 } else {
4338 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004339 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004340 if (GlobalVarDecl)
4341 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4342 else
4343 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004344 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4345 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004346 }
4347 Constructor += " ";
4348 Constructor += "}\n";
4349 S += Constructor;
4350 S += "};\n";
4351 return S;
4352}
4353
Steve Naroff30484702009-12-06 21:14:13 +00004354std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4355 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004356 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004357 unsigned hasCopy) {
4358 std::string S = "\nstatic struct " + DescTag;
4359
4360 S += " {\n unsigned long reserved;\n";
4361 S += " unsigned long Block_size;\n";
4362 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004363 S += " void (*copy)(struct ";
4364 S += ImplTag; S += "*, struct ";
4365 S += ImplTag; S += "*);\n";
4366
4367 S += " void (*dispose)(struct ";
4368 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004369 }
4370 S += "} ";
4371
4372 S += DescTag + "_DATA = { 0, sizeof(struct ";
4373 S += ImplTag + ")";
4374 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004375 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4376 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004377 }
4378 S += "};\n";
4379 return S;
4380}
4381
Steve Naroff677ab3a2008-10-27 17:20:55 +00004382void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004383 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004384 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004385 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004386 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004387 bool RewriteSC = (GlobalVarDecl &&
4388 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004389 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004390 GlobalVarDecl->getType().getCVRQualifiers());
4391 if (RewriteSC) {
4392 std::string SC(" void __");
4393 SC += GlobalVarDecl->getNameAsString();
4394 SC += "() {}";
4395 InsertText(FunLocStart, SC);
4396 }
4397
Steve Naroff677ab3a2008-10-27 17:20:55 +00004398 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004399 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4400 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004401 // Need to copy-in the inner copied-in variables not actually used in this
4402 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004403 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4404 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4405 ValueDecl *VD = Exp->getDecl();
4406 BlockDeclRefs.push_back(Exp);
4407 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4408 BlockByCopyDeclsPtrSet.insert(VD);
4409 BlockByCopyDecls.push_back(VD);
4410 }
4411 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4412 BlockByRefDeclsPtrSet.insert(VD);
4413 BlockByRefDecls.push_back(VD);
4414 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004415 // imported objects in the inner blocks not used in the outer
4416 // blocks must be copied/disposed in the outer block as well.
4417 if (Exp->isByRef() ||
4418 VD->getType()->isObjCObjectPointerType() ||
4419 VD->getType()->isBlockPointerType())
4420 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004421 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004422
Daniel Dunbar56df9772010-08-17 22:39:59 +00004423 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4424 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004425
Steve Naroff30484702009-12-06 21:14:13 +00004426 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004427
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004428 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004429
Steve Naroff30484702009-12-06 21:14:13 +00004430 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004431
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004432 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004433
4434 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004435 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004436 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004437 }
Steve Naroff30484702009-12-06 21:14:13 +00004438 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4439 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004440 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004441
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442 BlockDeclRefs.clear();
4443 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004444 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004445 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004446 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004447 ImportedBlockDecls.clear();
4448 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004449 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004450 // Must insert any 'const/volatile/static here. Since it has been
4451 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004452 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004453 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004454 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004455 if (GlobalVarDecl->getType().isConstQualified())
4456 SC += "const ";
4457 if (GlobalVarDecl->getType().isVolatileQualified())
4458 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004459 if (GlobalVarDecl->getType().isRestrictQualified())
4460 SC += "restrict ";
4461 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004462 }
4463
Steve Naroff677ab3a2008-10-27 17:20:55 +00004464 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004465 InnerDeclRefsCount.clear();
4466 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004467 RewrittenBlockExprs.clear();
4468}
4469
4470void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4471 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004472 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004473
Steve Naroff677ab3a2008-10-27 17:20:55 +00004474 SynthesizeBlockLiterals(FunLocStart, FuncName);
4475}
4476
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004477static void BuildUniqueMethodName(std::string &Name,
4478 ObjCMethodDecl *MD) {
4479 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004480 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004481 Name += "__" + MD->getSelector().getAsString();
4482 // Convert colons to underscores.
4483 std::string::size_type loc = 0;
4484 while ((loc = Name.find(":", loc)) != std::string::npos)
4485 Name.replace(loc, 1, "_");
4486}
4487
Steve Naroff677ab3a2008-10-27 17:20:55 +00004488void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004489 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4490 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004491 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004492 std::string FuncName;
4493 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004494 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004495}
4496
4497void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4498 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4499 CI != E; ++CI)
4500 if (*CI) {
4501 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4502 GetBlockDeclRefExprs(CBE->getBody());
4503 else
4504 GetBlockDeclRefExprs(*CI);
4505 }
4506 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004507 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004508 // FIXME: Handle enums.
4509 if (!isa<FunctionDecl>(CDRE->getDecl()))
4510 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004511 }
4512 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4513 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4514 BlockDeclRefExpr *BDRE =
4515 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4516 DRE->getLocation(), false);
4517 BlockDeclRefs.push_back(BDRE);
4518 }
4519
Steve Naroff677ab3a2008-10-27 17:20:55 +00004520 return;
4521}
4522
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004523void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4524 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004525 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004526 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4527 CI != E; ++CI)
4528 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004529 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4530 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004531 GetInnerBlockDeclRefExprs(CBE->getBody(),
4532 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004533 InnerContexts);
4534 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004535 else
4536 GetInnerBlockDeclRefExprs(*CI,
4537 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004538 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004539
4540 }
4541 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004542 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004543 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004544 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004545 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004546 }
4547 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4548 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4549 if (Var->isFunctionOrMethodVarDecl())
4550 ImportedLocalExternalDecls.insert(Var);
4551 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004552
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004553 return;
4554}
4555
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004556/// convertFunctionTypeOfBlocks - This routine converts a function type
4557/// whose result type may be a block pointer or whose argument type(s)
4558/// might be block pointers to an equivalent funtion type replacing
4559/// all block pointers to function pointers.
4560QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4561 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4562 // FTP will be null for closures that don't take arguments.
4563 // Generate a funky cast.
4564 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004565 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004566 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004567
4568 if (FTP) {
4569 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4570 E = FTP->arg_type_end(); I && (I != E); ++I) {
4571 QualType t = *I;
4572 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004573 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004574 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004575 ArgTypes.push_back(t);
4576 }
4577 }
4578 QualType FuncType;
4579 // FIXME. Does this work if block takes no argument but has a return type
4580 // which is of block type?
4581 if (HasBlockType)
4582 FuncType = Context->getFunctionType(Res,
4583 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4584 false, false, 0, 0, FunctionType::ExtInfo());
4585 else FuncType = QualType(FT, 0);
4586 return FuncType;
4587}
4588
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004589Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004590 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004591 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004592
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004593 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004594 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004595 } else if (const BlockDeclRefExpr *CDRE =
4596 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004597 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004598 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004599 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004600 }
4601 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4602 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4603 }
4604 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4605 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4606 else if (const ConditionalOperator *CEXPR =
4607 dyn_cast<ConditionalOperator>(BlockExp)) {
4608 Expr *LHSExp = CEXPR->getLHS();
4609 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4610 Expr *RHSExp = CEXPR->getRHS();
4611 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4612 Expr *CONDExp = CEXPR->getCond();
4613 ConditionalOperator *CondExpr =
4614 new (Context) ConditionalOperator(CONDExp,
4615 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004616 SourceLocation(), cast<Expr>(RHSStmt),
4617 (Expr*)0,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004618 Exp->getType());
4619 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004620 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4621 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004622 } else {
4623 assert(1 && "RewriteBlockClass: Bad type");
4624 }
4625 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004626 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004627 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004628 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004629 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004630
Abramo Bagnara6150c882010-05-11 21:36:43 +00004631 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004632 SourceLocation(),
4633 &Context->Idents.get("__block_impl"));
4634 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004635
Steve Naroff350b6652008-10-30 10:07:53 +00004636 // Generate a funky cast.
4637 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004638
Steve Naroff350b6652008-10-30 10:07:53 +00004639 // Push the block argument type.
4640 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004641 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004642 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004643 E = FTP->arg_type_end(); I && (I != E); ++I) {
4644 QualType t = *I;
4645 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004646 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004647 ArgTypes.push_back(t);
4648 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004649 }
Steve Naroff350b6652008-10-30 10:07:53 +00004650 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004651 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004652 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4653 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004654 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004655
Steve Naroff350b6652008-10-30 10:07:53 +00004656 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004657
John McCall97513962010-01-15 18:39:57 +00004658 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalle3027922010-08-25 11:45:40 +00004659 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00004660 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004661 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004662 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4663 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004664 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004665
Douglas Gregor91f84212008-12-11 16:49:14 +00004666 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004667 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004668 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004669 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4670 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004671
John McCall97513962010-01-15 18:39:57 +00004672 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalle3027922010-08-25 11:45:40 +00004673 CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004674 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004675
Steve Naroff350b6652008-10-30 10:07:53 +00004676 llvm::SmallVector<Expr*, 8> BlkExprs;
4677 // Add the implicit argument.
4678 BlkExprs.push_back(BlkCast);
4679 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004680 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004681 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004682 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004683 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004684 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4685 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004686 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004687 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004688}
4689
Steve Naroffd9803712009-04-29 16:37:50 +00004690// We need to return the rewritten expression to handle cases where the
4691// BlockDeclRefExpr is embedded in another expression being rewritten.
4692// For example:
4693//
4694// int main() {
4695// __block Foo *f;
4696// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004697//
Steve Naroffd9803712009-04-29 16:37:50 +00004698// void (^myblock)() = ^() {
4699// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4700// i = 77;
4701// };
4702//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004703Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004704 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004705 // for each DeclRefExp where BYREFVAR is name of the variable.
4706 ValueDecl *VD;
4707 bool isArrow = true;
4708 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4709 VD = BDRE->getDecl();
4710 else {
4711 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4712 isArrow = false;
4713 }
4714
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004715 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4716 &Context->Idents.get("__forwarding"),
4717 Context->VoidPtrTy, 0,
4718 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004719 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4720 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004721 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004722
Daniel Dunbar56df9772010-08-17 22:39:59 +00004723 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004724 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4725 &Context->Idents.get(Name),
4726 Context->VoidPtrTy, 0,
4727 /*BitWidth=*/0, /*Mutable=*/true);
4728 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004729 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004730
4731
4732
Steve Narofff26a1d42009-02-02 17:19:26 +00004733 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004734 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4735 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004736 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004737 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004738}
4739
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004740// Rewrites the imported local variable V with external storage
4741// (static, extern, etc.) as *V
4742//
4743Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4744 ValueDecl *VD = DRE->getDecl();
4745 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4746 if (!ImportedLocalExternalDecls.count(Var))
4747 return DRE;
John McCalle3027922010-08-25 11:45:40 +00004748 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004749 DRE->getType(), DRE->getLocation());
4750 // Need parens to enforce precedence.
4751 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4752 Exp);
4753 ReplaceStmt(DRE, PE);
4754 return PE;
4755}
4756
Steve Naroffc989a7b2008-11-03 23:29:32 +00004757void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4758 SourceLocation LocStart = CE->getLParenLoc();
4759 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004760
4761 // Need to avoid trying to rewrite synthesized casts.
4762 if (LocStart.isInvalid())
4763 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004764 // Need to avoid trying to rewrite casts contained in macros.
4765 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4766 return;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Steve Naroff677ab3a2008-10-27 17:20:55 +00004768 const char *startBuf = SM->getCharacterData(LocStart);
4769 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004770 QualType QT = CE->getType();
4771 const Type* TypePtr = QT->getAs<Type>();
4772 if (isa<TypeOfExprType>(TypePtr)) {
4773 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4774 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4775 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004776 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004777 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004778 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004779 return;
4780 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004781 // advance the location to startArgList.
4782 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004783
Steve Naroff677ab3a2008-10-27 17:20:55 +00004784 while (*argPtr++ && (argPtr < endBuf)) {
4785 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004786 case '^':
4787 // Replace the '^' with '*'.
4788 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004789 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004790 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004791 }
4792 }
4793 return;
4794}
4795
4796void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4797 SourceLocation DeclLoc = FD->getLocation();
4798 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Steve Naroff677ab3a2008-10-27 17:20:55 +00004800 // We have 1 or more arguments that have closure pointers.
4801 const char *startBuf = SM->getCharacterData(DeclLoc);
4802 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004803
Steve Naroff677ab3a2008-10-27 17:20:55 +00004804 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004805
Steve Naroff677ab3a2008-10-27 17:20:55 +00004806 parenCount++;
4807 // advance the location to startArgList.
4808 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4809 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004810
Steve Naroff677ab3a2008-10-27 17:20:55 +00004811 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004812
Steve Naroff677ab3a2008-10-27 17:20:55 +00004813 while (*argPtr++ && parenCount) {
4814 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004815 case '^':
4816 // Replace the '^' with '*'.
4817 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004818 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004819 break;
4820 case '(':
4821 parenCount++;
4822 break;
4823 case ')':
4824 parenCount--;
4825 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004826 }
4827 }
4828 return;
4829}
4830
4831bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004832 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004833 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004834 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004835 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004836 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004837 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004838 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004839 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004840 }
4841 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004842 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004843 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004844 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004845 return true;
4846 }
4847 return false;
4848}
4849
Ted Kremenek5a201952009-02-07 01:47:29 +00004850void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4851 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004852 const char *argPtr = strchr(Name, '(');
4853 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004854
Steve Naroff677ab3a2008-10-27 17:20:55 +00004855 LParen = argPtr; // output the start.
4856 argPtr++; // skip past the left paren.
4857 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004858
Steve Naroff677ab3a2008-10-27 17:20:55 +00004859 while (*argPtr && parenCount) {
4860 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004861 case '(': parenCount++; break;
4862 case ')': parenCount--; break;
4863 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004864 }
4865 if (parenCount) argPtr++;
4866 }
4867 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4868 RParen = argPtr; // output the end
4869}
4870
4871void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4872 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4873 RewriteBlockPointerFunctionArgs(FD);
4874 return;
Mike Stump11289f42009-09-09 15:08:12 +00004875 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004876 // Handle Variables and Typedefs.
4877 SourceLocation DeclLoc = ND->getLocation();
4878 QualType DeclT;
4879 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4880 DeclT = VD->getType();
4881 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4882 DeclT = TDD->getUnderlyingType();
4883 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4884 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004885 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004886 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004887
Steve Naroff677ab3a2008-10-27 17:20:55 +00004888 const char *startBuf = SM->getCharacterData(DeclLoc);
4889 const char *endBuf = startBuf;
4890 // scan backward (from the decl location) for the end of the previous decl.
4891 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4892 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004893
Steve Naroff677ab3a2008-10-27 17:20:55 +00004894 // *startBuf != '^' if we are dealing with a pointer to function that
4895 // may take block argument types (which will be handled below).
4896 if (*startBuf == '^') {
4897 // Replace the '^' with '*', computing a negative offset.
4898 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004899 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004900 }
4901 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4902 // Replace the '^' with '*' for arguments.
4903 DeclLoc = ND->getLocation();
4904 startBuf = SM->getCharacterData(DeclLoc);
4905 const char *argListBegin, *argListEnd;
4906 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4907 while (argListBegin < argListEnd) {
4908 if (*argListBegin == '^') {
4909 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004910 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004911 }
4912 argListBegin++;
4913 }
4914 }
4915 return;
4916}
4917
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004918
4919/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4920/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4921/// struct Block_byref_id_object *src) {
4922/// _Block_object_assign (&_dest->object, _src->object,
4923/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4924/// [|BLOCK_FIELD_IS_WEAK]) // object
4925/// _Block_object_assign(&_dest->object, _src->object,
4926/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4927/// [|BLOCK_FIELD_IS_WEAK]) // block
4928/// }
4929/// And:
4930/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4931/// _Block_object_dispose(_src->object,
4932/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4933/// [|BLOCK_FIELD_IS_WEAK]) // object
4934/// _Block_object_dispose(_src->object,
4935/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4936/// [|BLOCK_FIELD_IS_WEAK]) // block
4937/// }
4938
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004939std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4940 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004941 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004942 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004943 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004944 CopyDestroyCache.insert(flag);
4945 S = "static void __Block_byref_id_object_copy_";
4946 S += utostr(flag);
4947 S += "(void *dst, void *src) {\n";
4948
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004949 // offset into the object pointer is computed as:
4950 // void * + void* + int + int + void* + void *
4951 unsigned IntSize =
4952 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4953 unsigned VoidPtrSize =
4954 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4955
4956 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4957 S += " _Block_object_assign((char*)dst + ";
4958 S += utostr(offset);
4959 S += ", *(void * *) ((char*)src + ";
4960 S += utostr(offset);
4961 S += "), ";
4962 S += utostr(flag);
4963 S += ");\n}\n";
4964
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004965 S += "static void __Block_byref_id_object_dispose_";
4966 S += utostr(flag);
4967 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004968 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4969 S += utostr(offset);
4970 S += "), ";
4971 S += utostr(flag);
4972 S += ");\n}\n";
4973 return S;
4974}
4975
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004976/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4977/// the declaration into:
4978/// struct __Block_byref_ND {
4979/// void *__isa; // NULL for everything except __weak pointers
4980/// struct __Block_byref_ND *__forwarding;
4981/// int32_t __flags;
4982/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004983/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4984/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004985/// typex ND;
4986/// };
4987///
4988/// It then replaces declaration of ND variable with:
4989/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4990/// __size=sizeof(struct __Block_byref_ND),
4991/// ND=initializer-if-any};
4992///
4993///
4994void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004995 // Insert declaration for the function in which block literal is
4996 // used.
4997 if (CurFunctionDeclToDeclareForBlock)
4998 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004999 int flag = 0;
5000 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005001 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005002 if (DeclLoc.isInvalid())
5003 // If type location is missing, it is because of missing type (a warning).
5004 // Use variable's location which is good for this case.
5005 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005006 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005007 SourceLocation X = ND->getLocEnd();
5008 X = SM->getInstantiationLoc(X);
5009 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005010 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005011 std::string ByrefType;
5012 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005013 ByrefType += " {\n";
5014 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005015 RewriteByRefString(ByrefType, Name, ND);
5016 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005017 ByrefType += " int __flags;\n";
5018 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005019 // Add void *__Block_byref_id_object_copy;
5020 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005021 QualType Ty = ND->getType();
5022 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5023 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005024 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5025 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005026 }
5027
5028 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005029 ByrefType += " " + Name + ";\n";
5030 ByrefType += "};\n";
5031 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005032 SourceLocation FunLocStart;
5033 if (CurFunctionDef)
5034 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5035 else {
5036 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5037 FunLocStart = CurMethodDef->getLocStart();
5038 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005039 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005040 if (Ty.isObjCGCWeak()) {
5041 flag |= BLOCK_FIELD_IS_WEAK;
5042 isa = 1;
5043 }
5044
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005045 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005046 flag = BLOCK_BYREF_CALLER;
5047 QualType Ty = ND->getType();
5048 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5049 if (Ty->isBlockPointerType())
5050 flag |= BLOCK_FIELD_IS_BLOCK;
5051 else
5052 flag |= BLOCK_FIELD_IS_OBJECT;
5053 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005054 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005055 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005056 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005057
5058 // struct __Block_byref_ND ND =
5059 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5060 // initializer-if-any};
5061 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005062 unsigned flags = 0;
5063 if (HasCopyAndDispose)
5064 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005065 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005066 ByrefType.clear();
5067 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005068 std::string ForwardingCastType("(");
5069 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005070 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005071 ByrefType += " " + Name + " = {(void*)";
5072 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005073 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005074 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005075 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005076 ByrefType += "sizeof(";
5077 RewriteByRefString(ByrefType, Name, ND);
5078 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005079 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005080 ByrefType += ", __Block_byref_id_object_copy_";
5081 ByrefType += utostr(flag);
5082 ByrefType += ", __Block_byref_id_object_dispose_";
5083 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005084 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005085 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005086 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005087 }
5088 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005089 SourceLocation startLoc;
5090 Expr *E = ND->getInit();
5091 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5092 startLoc = ECE->getLParenLoc();
5093 else
5094 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005095 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005096 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005097 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005098 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005099 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005100 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005101 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005102 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005103 ByrefType += "sizeof(";
5104 RewriteByRefString(ByrefType, Name, ND);
5105 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005106 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005107 ByrefType += "__Block_byref_id_object_copy_";
5108 ByrefType += utostr(flag);
5109 ByrefType += ", __Block_byref_id_object_dispose_";
5110 ByrefType += utostr(flag);
5111 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005112 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005113 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005114
5115 // Complete the newly synthesized compound expression by inserting a right
5116 // curly brace before the end of the declaration.
5117 // FIXME: This approach avoids rewriting the initializer expression. It
5118 // also assumes there is only one declarator. For example, the following
5119 // isn't currently supported by this routine (in general):
5120 //
5121 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5122 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005123 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5124 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005125 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5126 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005127 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005128
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005129 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005130 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005131 return;
5132}
5133
Mike Stump11289f42009-09-09 15:08:12 +00005134void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005135 // Add initializers for any closure decl refs.
5136 GetBlockDeclRefExprs(Exp->getBody());
5137 if (BlockDeclRefs.size()) {
5138 // Unique all "by copy" declarations.
5139 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005140 if (!BlockDeclRefs[i]->isByRef()) {
5141 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5142 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5143 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5144 }
5145 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005146 // Unique all "by ref" declarations.
5147 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5148 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005149 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5150 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5151 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5152 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005153 }
5154 // Find any imported blocks...they will need special attention.
5155 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005156 if (BlockDeclRefs[i]->isByRef() ||
5157 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005158 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005159 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005160 }
5161}
5162
Daniel Dunbar56df9772010-08-17 22:39:59 +00005163FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005164 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005165 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005166 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005167 ID, FType, 0, SC_Extern,
5168 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005169}
5170
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005171Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5172 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 Blocks.push_back(Exp);
5174
5175 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005176
5177 // Add inner imported variables now used in current block.
5178 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005179 if (!InnerBlockDeclRefs.empty()) {
5180 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5181 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5182 ValueDecl *VD = Exp->getDecl();
5183 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005184 // We need to save the copied-in variables in nested
5185 // blocks because it is needed at the end for some of the API generations.
5186 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005187 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5188 BlockDeclRefs.push_back(Exp);
5189 BlockByCopyDeclsPtrSet.insert(VD);
5190 BlockByCopyDecls.push_back(VD);
5191 }
5192 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5193 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5194 BlockDeclRefs.push_back(Exp);
5195 BlockByRefDeclsPtrSet.insert(VD);
5196 BlockByRefDecls.push_back(VD);
5197 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005198 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005199 // Find any imported blocks...they will need special attention.
5200 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5201 if (InnerBlockDeclRefs[i]->isByRef() ||
5202 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5203 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5204 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005205 }
5206 InnerDeclRefsCount.push_back(countOfInnerDecls);
5207
Steve Narofff4b992a2008-10-28 20:29:00 +00005208 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005209
Steve Narofff4b992a2008-10-28 20:29:00 +00005210 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005211 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005212 else if (CurMethodDef)
5213 BuildUniqueMethodName(FuncName, CurMethodDef);
5214 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005215 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005216
Steve Narofff4b992a2008-10-28 20:29:00 +00005217 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005218
Steve Narofff4b992a2008-10-28 20:29:00 +00005219 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5220 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005221
Steve Narofff4b992a2008-10-28 20:29:00 +00005222 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005223 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5224 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005225
5226 FunctionDecl *FD;
5227 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005228
Steve Narofff4b992a2008-10-28 20:29:00 +00005229 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005230 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek5a201952009-02-07 01:47:29 +00005231 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005232
Steve Narofff4b992a2008-10-28 20:29:00 +00005233 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005234
Steve Naroffe2514232008-10-29 21:23:59 +00005235 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005236 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek5a201952009-02-07 01:47:29 +00005237 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5238 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005239 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005240 CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005241 InitExprs.push_back(castExpr);
5242
Steve Naroff30484702009-12-06 21:14:13 +00005243 // Initialize the block descriptor.
5244 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005245
Steve Naroff30484702009-12-06 21:14:13 +00005246 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5247 &Context->Idents.get(DescData.c_str()),
5248 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005249 SC_Static, SC_None);
Steve Naroff30484702009-12-06 21:14:13 +00005250 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5251 new (Context) DeclRefExpr(NewVD,
5252 Context->VoidPtrTy, SourceLocation()),
John McCalle3027922010-08-25 11:45:40 +00005253 UO_AddrOf,
Steve Naroff30484702009-12-06 21:14:13 +00005254 Context->getPointerType(Context->VoidPtrTy),
5255 SourceLocation());
5256 InitExprs.push_back(DescRefExpr);
5257
Steve Narofff4b992a2008-10-28 20:29:00 +00005258 // Add initializers for any closure decl refs.
5259 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005260 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005261 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005262 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005263 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005264 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005265 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005266 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005267 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005268 if (HasLocalVariableExternalStorage(*I)) {
5269 QualType QT = (*I)->getType();
5270 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005271 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005272 SourceLocation());
5273 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005274 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005275 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005276 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005277 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005278 CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005279 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005280 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005281 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005282 if (HasLocalVariableExternalStorage(*I)) {
5283 QualType QT = (*I)->getType();
5284 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005285 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005286 SourceLocation());
5287 }
5288
Steve Narofff4b992a2008-10-28 20:29:00 +00005289 }
Mike Stump11289f42009-09-09 15:08:12 +00005290 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005291 }
5292 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005293 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005295 ValueDecl *ND = (*I);
5296 std::string Name(ND->getNameAsString());
5297 std::string RecName;
5298 RewriteByRefString(RecName, Name, ND);
5299 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5300 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005301 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005302 SourceLocation(), II);
5303 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5304 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5305
Daniel Dunbar56df9772010-08-17 22:39:59 +00005306 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005307 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005308 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005309 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005310 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005311 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005312 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005313 }
5314 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005315 if (ImportedBlockDecls.size()) {
5316 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5317 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005318 unsigned IntSize =
5319 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005320 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5321 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005322 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005323 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005324 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5325 FType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005326 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005327 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005328 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005329 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00005330 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005331 BlockDeclRefs.clear();
5332 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005333 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005334 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005335 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005336 ImportedBlockDecls.clear();
5337 return NewRep;
5338}
5339
5340//===----------------------------------------------------------------------===//
5341// Function Body / Expression rewriting
5342//===----------------------------------------------------------------------===//
5343
Steve Naroff4588d0f2008-12-04 16:24:46 +00005344// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5345// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5346// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5347// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5348// Since the rewriter isn't capable of rewriting rewritten code, it's important
5349// we get this right.
5350void RewriteObjC::CollectPropertySetters(Stmt *S) {
5351 // Perform a bottom up traversal of all children.
5352 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5353 CI != E; ++CI)
5354 if (*CI)
5355 CollectPropertySetters(*CI);
5356
5357 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5358 if (BinOp->isAssignmentOp()) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005359 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5360 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5361 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005362 }
5363 }
5364}
5365
Steve Narofff4b992a2008-10-28 20:29:00 +00005366Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005367 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005368 isa<DoStmt>(S) || isa<ForStmt>(S))
5369 Stmts.push_back(S);
5370 else if (isa<ObjCForCollectionStmt>(S)) {
5371 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005372 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Steve Narofff4b992a2008-10-28 20:29:00 +00005375 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005376
Steve Narofff4b992a2008-10-28 20:29:00 +00005377 // Perform a bottom up rewrite of all children.
5378 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5379 CI != E; ++CI)
5380 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005381 Stmt *newStmt;
5382 Stmt *S = (*CI);
5383 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5384 Expr *OldBase = IvarRefExpr->getBase();
5385 bool replaced = false;
5386 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5387 if (replaced) {
5388 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5389 ReplaceStmt(OldBase, IRE->getBase());
5390 else
5391 ReplaceStmt(S, newStmt);
5392 }
5393 }
5394 else
5395 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005396 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005397 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005398 // If dealing with an assignment with LHS being a property reference
5399 // expression, the entire assignment tree is rewritten into a property
5400 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5401 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005402 if (Expr *Exp = dyn_cast<Expr>(S))
5403 if (isa<ObjCPropertyRefExpr>(Exp) ||
5404 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5405 if (PropSetters[Exp]) {
5406 ++CI;
5407 continue;
5408 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005409 }
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005410 }
Mike Stump11289f42009-09-09 15:08:12 +00005411
Steve Narofff4b992a2008-10-28 20:29:00 +00005412 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005413 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005414 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5415 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005416 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005417 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005418 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005419 // Rewrite the block body in place.
5420 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005421 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005422 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005423 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005424 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005425
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005426 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5427
Steve Narofff4b992a2008-10-28 20:29:00 +00005428 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005429 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005430 return blockTranscribed;
5431 }
5432 // Handle specific things.
5433 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5434 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005435
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005436 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5437 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5438 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5439
5440 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005441 if (BinOp) {
5442 // Because the rewriter doesn't allow us to rewrite rewritten code,
5443 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005444 DisableReplaceStmt = true;
5445 // Save the source range. Even if we disable the replacement, the
5446 // rewritten node will have been inserted into the tree. If the synthesized
5447 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005448 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005449 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5450 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005451 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005452 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005453 //
5454 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5455 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5456 // to see the original expression). Consider this example:
5457 //
5458 // Foo *obj1, *obj2;
5459 //
5460 // obj1.i = [obj2 rrrr];
5461 //
5462 // 'BinOp' for the previous expression looks like:
5463 //
5464 // (BinaryOperator 0x231ccf0 'int' '='
5465 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5466 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5467 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5468 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5469 //
5470 // 'newStmt' represents the rewritten message expression. For example:
5471 //
5472 // (CallExpr 0x231d300 'id':'struct objc_object *'
5473 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5474 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5475 // (CStyleCastExpr 0x231d220 'void *'
5476 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5477 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005478 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005479 // can be used as the setter argument. ReplaceStmt() will still 'see'
5480 // the original RHS (since we haven't altered BinOp).
5481 //
Mike Stump11289f42009-09-09 15:08:12 +00005482 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005483 // node. As a result, we now leak the original AST nodes.
5484 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005485 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005486 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005487 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005488 }
5489 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005490
Steve Narofff4b992a2008-10-28 20:29:00 +00005491 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5492 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005493
Steve Narofff4b992a2008-10-28 20:29:00 +00005494 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5495 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005496
Steve Narofff4b992a2008-10-28 20:29:00 +00005497 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005498#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005499 // Before we rewrite it, put the original message expression in a comment.
5500 SourceLocation startLoc = MessExpr->getLocStart();
5501 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005502
Steve Narofff4b992a2008-10-28 20:29:00 +00005503 const char *startBuf = SM->getCharacterData(startLoc);
5504 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005505
Steve Narofff4b992a2008-10-28 20:29:00 +00005506 std::string messString;
5507 messString += "// ";
5508 messString.append(startBuf, endBuf-startBuf+1);
5509 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005510
5511 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005512 // InsertText(clang::SourceLocation, char const*, unsigned int).
5513 // InsertText(startLoc, messString.c_str(), messString.size());
5514 // Tried this, but it didn't work either...
5515 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005516#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005517 return RewriteMessageExpr(MessExpr);
5518 }
Mike Stump11289f42009-09-09 15:08:12 +00005519
Steve Narofff4b992a2008-10-28 20:29:00 +00005520 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5521 return RewriteObjCTryStmt(StmtTry);
5522
5523 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5524 return RewriteObjCSynchronizedStmt(StmtTry);
5525
5526 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5527 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005528
Steve Narofff4b992a2008-10-28 20:29:00 +00005529 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5530 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005531
5532 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005533 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005534 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005535 OrigStmtRange.getEnd());
5536 if (BreakStmt *StmtBreakStmt =
5537 dyn_cast<BreakStmt>(S))
5538 return RewriteBreakStmt(StmtBreakStmt);
5539 if (ContinueStmt *StmtContinueStmt =
5540 dyn_cast<ContinueStmt>(S))
5541 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005542
5543 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005544 // and cast exprs.
5545 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5546 // FIXME: What we're doing here is modifying the type-specifier that
5547 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005548 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005549 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5550 // the context of an ObjCForCollectionStmt. For example:
5551 // NSArray *someArray;
5552 // for (id <FooProtocol> index in someArray) ;
5553 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5554 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005555 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005556 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005557
Steve Narofff4b992a2008-10-28 20:29:00 +00005558 // Blocks rewrite rules.
5559 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5560 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005561 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005562 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005563 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005564 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005565 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005566 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005567 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005568 if (VD->hasAttr<BlocksAttr>()) {
5569 static unsigned uniqueByrefDeclCount = 0;
5570 assert(!BlockByRefDeclNo.count(ND) &&
5571 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5572 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005573 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005574 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005575 else
5576 RewriteTypeOfDecl(VD);
5577 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005578 }
5579 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005580 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005581 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005582 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005583 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5584 }
5585 }
5586 }
Mike Stump11289f42009-09-09 15:08:12 +00005587
Steve Narofff4b992a2008-10-28 20:29:00 +00005588 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5589 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005590
5591 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005592 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5593 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005594 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5595 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005596 && "Statement stack mismatch");
5597 Stmts.pop_back();
5598 }
5599 // Handle blocks rewriting.
5600 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5601 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005602 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005603 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005604 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5605 ValueDecl *VD = DRE->getDecl();
5606 if (VD->hasAttr<BlocksAttr>())
5607 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005608 if (HasLocalVariableExternalStorage(VD))
5609 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005610 }
5611
Steve Narofff4b992a2008-10-28 20:29:00 +00005612 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005613 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005614 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005615 ReplaceStmt(S, BlockCall);
5616 return BlockCall;
5617 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005618 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005619 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005620 RewriteCastExpr(CE);
5621 }
5622#if 0
5623 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005624 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5625 ICE->getSubExpr(),
5626 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005627 // Get the new text.
5628 std::string SStr;
5629 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005630 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005631 const std::string &Str = Buf.str();
5632
5633 printf("CAST = %s\n", &Str[0]);
5634 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5635 delete S;
5636 return Replacement;
5637 }
5638#endif
5639 // Return this stmt unmodified.
5640 return S;
5641}
5642
Steve Naroffe70a52a2009-12-05 15:55:59 +00005643void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5644 for (RecordDecl::field_iterator i = RD->field_begin(),
5645 e = RD->field_end(); i != e; ++i) {
5646 FieldDecl *FD = *i;
5647 if (isTopLevelBlockPointerType(FD->getType()))
5648 RewriteBlockPointerDecl(FD);
5649 if (FD->getType()->isObjCQualifiedIdType() ||
5650 FD->getType()->isObjCQualifiedInterfaceType())
5651 RewriteObjCQualifiedInterfaceTypes(FD);
5652 }
5653}
5654
Steve Narofff4b992a2008-10-28 20:29:00 +00005655/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5656/// main file of the input.
5657void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005659 if (FD->isOverloadedOperator())
5660 return;
Mike Stump11289f42009-09-09 15:08:12 +00005661
Steve Narofff4b992a2008-10-28 20:29:00 +00005662 // Since function prototypes don't have ParmDecl's, we check the function
5663 // prototype. This enables us to rewrite function declarations and
5664 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005665 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005666
Sebastian Redla7b98a72009-04-26 20:35:05 +00005667 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005668 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005669 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005670 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005671 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005672 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005673 Body =
5674 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5675 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005676 CurrentBody = 0;
5677 if (PropParentMap) {
5678 delete PropParentMap;
5679 PropParentMap = 0;
5680 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 // This synthesizes and inserts the block "impl" struct, invoke function,
5682 // and any copy/dispose helper functions.
5683 InsertBlockLiteralsWithinFunction(FD);
5684 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005685 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005686 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005687 return;
5688 }
5689 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005690 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005691 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005692 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005693 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005694 Body =
5695 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5696 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005697 CurrentBody = 0;
5698 if (PropParentMap) {
5699 delete PropParentMap;
5700 PropParentMap = 0;
5701 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005702 InsertBlockLiteralsWithinMethod(MD);
5703 CurMethodDef = 0;
5704 }
5705 }
5706 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5707 ClassImplementation.push_back(CI);
5708 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5709 CategoryImplementation.push_back(CI);
5710 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5711 RewriteForwardClassDecl(CD);
5712 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5713 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005714 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005715 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005716 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005717 CheckFunctionPointerDecl(VD->getType(), VD);
5718 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005719 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005720 RewriteCastExpr(CE);
5721 }
5722 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005723 } else if (VD->getType()->isRecordType()) {
5724 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5725 if (RD->isDefinition())
5726 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005727 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005728 if (VD->getInit()) {
5729 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005730 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005731 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005732 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005733 CurrentBody = 0;
5734 if (PropParentMap) {
5735 delete PropParentMap;
5736 PropParentMap = 0;
5737 }
Mike Stump11289f42009-09-09 15:08:12 +00005738 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005739 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005740 GlobalVarDecl = 0;
5741
5742 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005743 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005744 RewriteCastExpr(CE);
5745 }
5746 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005747 return;
5748 }
5749 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005750 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005751 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005752 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005753 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5754 return;
5755 }
5756 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005757 if (RD->isDefinition())
5758 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005759 return;
5760 }
5761 // Nothing yet.
5762}
5763
Chris Lattnercf169832009-03-28 04:11:33 +00005764void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005765 if (Diags.hasErrorOccurred())
5766 return;
Mike Stump11289f42009-09-09 15:08:12 +00005767
Steve Narofff4b992a2008-10-28 20:29:00 +00005768 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005769
Steve Naroffd9803712009-04-29 16:37:50 +00005770 // Here's a great place to add any extra declarations that may be needed.
5771 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005772 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005773 E = ProtocolExprDecls.end(); I != E; ++I)
5774 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5775
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005776 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005777 if (ClassImplementation.size() || CategoryImplementation.size())
5778 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005779
Steve Narofff4b992a2008-10-28 20:29:00 +00005780 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5781 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005782 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005783 Rewrite.getRewriteBufferFor(MainFileID)) {
5784 //printf("Changed:\n");
5785 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5786 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005787 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005788 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005789
Steve Naroffd9803712009-04-29 16:37:50 +00005790 if (ClassImplementation.size() || CategoryImplementation.size() ||
5791 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005792 // Rewrite Objective-c meta data*
5793 std::string ResultStr;
5794 SynthesizeMetaDataIntoBuffer(ResultStr);
5795 // Emit metadata.
5796 *OutFile << ResultStr;
5797 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005798 OutFile->flush();
5799}