blob: c085e6d017586e5ad8f629ba1282c45dc32f6ad4 [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.
142 llvm::DenseMap<ObjCPropertyRefExpr *, 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).
145 llvm::DenseMap<ObjCPropertyRefExpr *, 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);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000285 Stmt *RewritePropertySetter(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
Steve Naroff08628db2008-12-09 12:56:34 +00001206Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1207 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001208 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1209 // This allows us to reuse all the fun and games in SynthMessageExpr().
1210 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1211 ObjCMessageExpr *MsgExpr;
1212 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1213 llvm::SmallVector<Expr *, 1> ExprVec;
1214 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001215
Steve Naroff1042ff32008-12-08 16:43:47 +00001216 Stmt *Receiver = PropRefExpr->getBase();
1217 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1218 if (PRE && PropGetters[PRE]) {
1219 // This allows us to handle chain/nested property getters.
1220 Receiver = PropGetters[PRE];
1221 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001222 if (isa<ObjCSuperExpr>(Receiver))
1223 MsgExpr = ObjCMessageExpr::Create(*Context,
1224 PDecl->getType().getNonReferenceType(),
1225 /*FIXME?*/SourceLocation(),
1226 Receiver->getLocStart(),
1227 /*IsInstanceSuper=*/true,
1228 cast<Expr>(Receiver)->getType(),
1229 PDecl->getSetterName(),
1230 PDecl->getSetterMethodDecl(),
1231 &ExprVec[0], 1,
1232 /*FIXME:*/SourceLocation());
1233 else
1234 MsgExpr = ObjCMessageExpr::Create(*Context,
1235 PDecl->getType().getNonReferenceType(),
1236 /*FIXME: */SourceLocation(),
1237 cast<Expr>(Receiver),
1238 PDecl->getSetterName(),
1239 PDecl->getSetterMethodDecl(),
1240 &ExprVec[0], 1,
1241 /*FIXME:*/SourceLocation());
Steve Naroff4588d0f2008-12-04 16:24:46 +00001242 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Steve Naroff4588d0f2008-12-04 16:24:46 +00001244 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001245 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001246 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001247 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1248 // to things that stay around.
1249 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001250 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001251}
1252
Steve Naroff4588d0f2008-12-04 16:24:46 +00001253Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001254 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1255 // This allows us to reuse all the fun and games in SynthMessageExpr().
1256 ObjCMessageExpr *MsgExpr;
1257 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001258
Steve Naroff1042ff32008-12-08 16:43:47 +00001259 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001260
Steve Naroff1042ff32008-12-08 16:43:47 +00001261 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1262 if (PRE && PropGetters[PRE]) {
1263 // This allows us to handle chain/nested property getters.
1264 Receiver = PropGetters[PRE];
1265 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001266
1267 if (isa<ObjCSuperExpr>(Receiver))
1268 MsgExpr = ObjCMessageExpr::Create(*Context,
1269 PDecl->getType().getNonReferenceType(),
1270 /*FIXME:*/SourceLocation(),
1271 Receiver->getLocStart(),
1272 /*IsInstanceSuper=*/true,
1273 cast<Expr>(Receiver)->getType(),
1274 PDecl->getGetterName(),
1275 PDecl->getGetterMethodDecl(),
1276 0, 0,
1277 /*FIXME:*/SourceLocation());
1278 else
1279 MsgExpr = ObjCMessageExpr::Create(*Context,
1280 PDecl->getType().getNonReferenceType(),
1281 /*FIXME:*/SourceLocation(),
1282 cast<Expr>(Receiver),
1283 PDecl->getGetterName(),
1284 PDecl->getGetterMethodDecl(),
1285 0, 0,
1286 /*FIXME:*/SourceLocation());
Steve Narofff326f402008-12-03 00:56:33 +00001287
Steve Naroff22216db2008-12-04 23:50:32 +00001288 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001289
1290 if (!PropParentMap)
1291 PropParentMap = new ParentMap(CurrentBody);
1292
1293 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1294 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1295 // We stash away the ReplacingStmt since actually doing the
1296 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1297 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001298 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1299 // to things that stay around.
1300 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001301 return PropRefExpr; // return the original...
1302 } else {
1303 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001304 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001305 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1306 // to things that stay around.
1307 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001308 return ReplacingStmt;
1309 }
Steve Narofff326f402008-12-03 00:56:33 +00001310}
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001313 SourceLocation OrigStart,
1314 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001315 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001316 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001317 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001318 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001319 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001320 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001321 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001322 // lookup which class implements the instance variable.
1323 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001324 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001325 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001326 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001327
Steve Naroffb1c02372008-05-08 17:52:16 +00001328 // Synthesize an explicit cast to gain access to the ivar.
1329 std::string RecName = clsDeclared->getIdentifier()->getName();
1330 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001331 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001332 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001333 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001334 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1335 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001336 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001337 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001338 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001339 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001340 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1341 IV->getBase()->getLocEnd(),
1342 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001343 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001344 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001345 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001346 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1347 IV->getLocation(),
1348 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001349 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001350 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001351 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001352 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001353 // Cannot delete IV->getBase(), since PE points to it.
1354 // Replace the old base with the cast. This is important when doing
1355 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001356 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001357 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001358 }
Steve Naroff24840f62008-04-18 21:55:08 +00001359 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001360 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001361
Steve Naroff29ce4e52008-05-06 23:20:07 +00001362 // Explicit ivar refs need to have a cast inserted.
1363 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001364 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001365 ObjCInterfaceType *iFaceDecl =
1366 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001367 // lookup which class implements the instance variable.
1368 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001369 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001370 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001371 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001372
Steve Naroff29ce4e52008-05-06 23:20:07 +00001373 // Synthesize an explicit cast to gain access to the ivar.
1374 std::string RecName = clsDeclared->getIdentifier()->getName();
1375 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001376 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001377 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001378 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001379 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1380 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001381 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001382 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001383 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001384 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001385 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001386 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001387 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001388 // Cannot delete IV->getBase(), since PE points to it.
1389 // Replace the old base with the cast. This is important when doing
1390 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001391 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001392 return IV;
1393 }
Steve Naroff05caa482007-11-15 11:33:00 +00001394 }
Steve Naroff24840f62008-04-18 21:55:08 +00001395 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001396}
1397
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001398Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1399 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1400 CI != E; ++CI) {
1401 if (*CI) {
1402 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1403 if (newStmt)
1404 *CI = newStmt;
1405 }
1406 }
1407 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1408 SourceRange OrigStmtRange = S->getSourceRange();
1409 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1410 replaced);
1411 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001412 }
1413 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1414 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1415 return newStmt;
1416 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001417 return S;
1418}
1419
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001420/// SynthCountByEnumWithState - To print:
1421/// ((unsigned int (*)
1422/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001423/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001425/// "countByEnumeratingWithState:objects:count:"),
1426/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001427/// (id *)items, (unsigned int)16)
1428///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001429void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1431 "id *, unsigned int))(void *)objc_msgSend)";
1432 buf += "\n\t\t";
1433 buf += "((id)l_collection,\n\t\t";
1434 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1435 buf += "\n\t\t";
1436 buf += "&enumState, "
1437 "(id *)items, (unsigned int)16)";
1438}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001439
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001440/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1441/// statement to exit to its outer synthesized loop.
1442///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001443Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001444 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1445 return S;
1446 // replace break with goto __break_label
1447 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001448
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001449 SourceLocation startLoc = S->getLocStart();
1450 buf = "goto __break_label_";
1451 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001452 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001453
1454 return 0;
1455}
1456
1457/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1458/// statement to continue with its inner synthesized loop.
1459///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001460Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001461 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1462 return S;
1463 // replace continue with goto __continue_label
1464 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001465
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001466 SourceLocation startLoc = S->getLocStart();
1467 buf = "goto __continue_label_";
1468 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001469 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001471 return 0;
1472}
1473
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001474/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001475/// It rewrites:
1476/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001477
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001478/// Into:
1479/// {
Mike Stump11289f42009-09-09 15:08:12 +00001480/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001482/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001484/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001485/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001486/// if (limit) {
1487/// unsigned long startMutations = *enumState.mutationsPtr;
1488/// do {
1489/// unsigned long counter = 0;
1490/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001491/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001492/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001493/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001494/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001495/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001496/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001497/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001498/// objects:items count:16]);
1499/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001500/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001501/// }
1502/// else
1503/// elem = nil;
1504/// }
1505///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001506Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001507 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001508 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001509 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001510 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001511 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001512 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001513
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001516 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001517 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001518 std::string buf;
1519 buf = "\n{\n\t";
1520 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1521 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001522 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001523 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001524 if (ElementType->isObjCQualifiedIdType() ||
1525 ElementType->isObjCQualifiedInterfaceType())
1526 // Simply use 'id' for all qualified types.
1527 elementTypeAsString = "id";
1528 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001529 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001530 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001531 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001532 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001533 buf += elementName;
1534 buf += ";\n\t";
1535 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001536 else {
1537 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001538 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001539 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1540 if (VD->getType()->isObjCQualifiedIdType() ||
1541 VD->getType()->isObjCQualifiedInterfaceType())
1542 // Simply use 'id' for all qualified types.
1543 elementTypeAsString = "id";
1544 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001545 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548 // struct __objcFastEnumerationState enumState = { 0 };
1549 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1550 // id items[16];
1551 buf += "id items[16];\n\t";
1552 // id l_collection = (id)
1553 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001554 // Find start location of 'collection' the hard way!
1555 const char *startCollectionBuf = startBuf;
1556 startCollectionBuf += 3; // skip 'for'
1557 startCollectionBuf = strchr(startCollectionBuf, '(');
1558 startCollectionBuf++; // skip '('
1559 // find 'in' and skip it.
1560 while (*startCollectionBuf != ' ' ||
1561 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1562 (*(startCollectionBuf+3) != ' ' &&
1563 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1564 startCollectionBuf++;
1565 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001566
1567 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001568 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001569 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001570 SourceLocation rightParenLoc = S->getRParenLoc();
1571 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1572 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001573 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001574
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001575 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1576 // objects:items count:16];
1577 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001578 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 // ((unsigned int (*)
1580 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001581 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001582 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001583 // "countByEnumeratingWithState:objects:count:"),
1584 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001585 // (id *)items, (unsigned int)16);
1586 buf += "unsigned long limit =\n\t\t";
1587 SynthCountByEnumWithState(buf);
1588 buf += ";\n\t";
1589 /// if (limit) {
1590 /// unsigned long startMutations = *enumState.mutationsPtr;
1591 /// do {
1592 /// unsigned long counter = 0;
1593 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001594 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001595 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001596 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001597 buf += "if (limit) {\n\t";
1598 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1599 buf += "do {\n\t\t";
1600 buf += "unsigned long counter = 0;\n\t\t";
1601 buf += "do {\n\t\t\t";
1602 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1603 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1604 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001605 buf += " = (";
1606 buf += elementTypeAsString;
1607 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001608 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001609 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001610
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001611 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001612 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001613 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001614 /// objects:items count:16]);
1615 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001616 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001617 /// }
1618 /// else
1619 /// elem = nil;
1620 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001621 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001622 buf = ";\n\t";
1623 buf += "__continue_label_";
1624 buf += utostr(ObjCBcLabelNo.back());
1625 buf += ": ;";
1626 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001627 buf += "} while (counter < limit);\n\t";
1628 buf += "} while (limit = ";
1629 SynthCountByEnumWithState(buf);
1630 buf += ");\n\t";
1631 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001632 buf += " = ((";
1633 buf += elementTypeAsString;
1634 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001635 buf += "__break_label_";
1636 buf += utostr(ObjCBcLabelNo.back());
1637 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001638 buf += "}\n\t";
1639 buf += "else\n\t\t";
1640 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001641 buf += " = ((";
1642 buf += elementTypeAsString;
1643 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001644 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001645
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001646 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001647 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001648 if (isa<CompoundStmt>(S->getBody())) {
1649 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001650 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001651 } else {
1652 /* Need to treat single statements specially. For example:
1653 *
1654 * for (A *a in b) if (stuff()) break;
1655 * for (A *a in b) xxxyy;
1656 *
1657 * The following code simply scans ahead to the semi to find the actual end.
1658 */
1659 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1660 const char *semiBuf = strchr(stmtBuf, ';');
1661 assert(semiBuf && "Can't find ';'");
1662 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001663 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001664 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001665 Stmts.pop_back();
1666 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001667 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001668}
1669
Mike Stump11289f42009-09-09 15:08:12 +00001670/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001671/// This routine rewrites @synchronized(expr) stmt;
1672/// into:
1673/// objc_sync_enter(expr);
1674/// @try stmt @finally { objc_sync_exit(expr); }
1675///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001676Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001677 // Get the start location and compute the semi location.
1678 SourceLocation startLoc = S->getLocStart();
1679 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001681 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001682
1683 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001684 buf = "objc_sync_enter((id)";
1685 const char *lparenBuf = startBuf;
1686 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001687 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001688 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1689 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001690 // been rewritten! (which implies the SourceLocation's are invalid).
1691 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001692 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001693 while (*endBuf != ')') endBuf--;
1694 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001695 buf = ");\n";
1696 // declare a new scope with two variables, _stack and _rethrow.
1697 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1698 buf += "int buf[18/*32-bit i386*/];\n";
1699 buf += "char *pointers[4];} _stack;\n";
1700 buf += "id volatile _rethrow = 0;\n";
1701 buf += "objc_exception_try_enter(&_stack);\n";
1702 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001703 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001704 startLoc = S->getSynchBody()->getLocEnd();
1705 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001706
Steve Naroffad7013b2008-08-19 13:04:19 +00001707 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001708 SourceLocation lastCurlyLoc = startLoc;
1709 buf = "}\nelse {\n";
1710 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001711 buf += "}\n";
1712 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001713 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001714
1715 std::string syncBuf;
1716 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001717 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00001718 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001719 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001720 std::string syncExprBufS;
1721 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001722 syncExpr->printPretty(syncExprBuf, *Context, 0,
1723 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001724 syncBuf += syncExprBuf.str();
1725 syncBuf += ");";
1726
1727 buf += syncBuf;
1728 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001729 buf += "}\n";
1730 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001731
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001732 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001733
1734 bool hasReturns = false;
1735 HasReturnStmts(S->getSynchBody(), hasReturns);
1736 if (hasReturns)
1737 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1738
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001739 return 0;
1740}
1741
Steve Naroffec60b432009-12-05 21:43:12 +00001742void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1743{
Steve Naroff6d6da252008-12-05 17:03:39 +00001744 // Perform a bottom up traversal of all children.
1745 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1746 CI != E; ++CI)
1747 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001748 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001749
Steve Naroffec60b432009-12-05 21:43:12 +00001750 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001751 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001752 TryFinallyContainsReturnDiag);
1753 }
1754 return;
1755}
1756
Steve Naroffec60b432009-12-05 21:43:12 +00001757void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1758{
1759 // Perform a bottom up traversal of all children.
1760 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1761 CI != E; ++CI)
1762 if (*CI)
1763 HasReturnStmts(*CI, hasReturns);
1764
1765 if (isa<ReturnStmt>(S))
1766 hasReturns = true;
1767 return;
1768}
1769
1770void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1771 // Perform a bottom up traversal of all children.
1772 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1773 CI != E; ++CI)
1774 if (*CI) {
1775 RewriteTryReturnStmts(*CI);
1776 }
1777 if (isa<ReturnStmt>(S)) {
1778 SourceLocation startLoc = S->getLocStart();
1779 const char *startBuf = SM->getCharacterData(startLoc);
1780
1781 const char *semiBuf = strchr(startBuf, ';');
1782 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1783 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1784
1785 std::string buf;
1786 buf = "{ objc_exception_try_exit(&_stack); return";
1787
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001788 ReplaceText(startLoc, 6, buf);
1789 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001790 }
1791 return;
1792}
1793
1794void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1795 // Perform a bottom up traversal of all children.
1796 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1797 CI != E; ++CI)
1798 if (*CI) {
1799 RewriteSyncReturnStmts(*CI, syncExitBuf);
1800 }
1801 if (isa<ReturnStmt>(S)) {
1802 SourceLocation startLoc = S->getLocStart();
1803 const char *startBuf = SM->getCharacterData(startLoc);
1804
1805 const char *semiBuf = strchr(startBuf, ';');
1806 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1807 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1808
1809 std::string buf;
1810 buf = "{ objc_exception_try_exit(&_stack);";
1811 buf += syncExitBuf;
1812 buf += " return";
1813
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001814 ReplaceText(startLoc, 6, buf);
1815 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001816 }
1817 return;
1818}
1819
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001820Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001821 // Get the start location and compute the semi location.
1822 SourceLocation startLoc = S->getLocStart();
1823 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001824
Steve Naroffbf478ec2007-11-07 04:08:17 +00001825 assert((*startBuf == '@') && "bogus @try location");
1826
1827 std::string buf;
1828 // declare a new scope with two variables, _stack and _rethrow.
1829 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1830 buf += "int buf[18/*32-bit i386*/];\n";
1831 buf += "char *pointers[4];} _stack;\n";
1832 buf += "id volatile _rethrow = 0;\n";
1833 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001834 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001836 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001837
Steve Naroffbf478ec2007-11-07 04:08:17 +00001838 startLoc = S->getTryBody()->getLocEnd();
1839 startBuf = SM->getCharacterData(startLoc);
1840
1841 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001842
Steve Naroffbf478ec2007-11-07 04:08:17 +00001843 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001844 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001845 startLoc = startLoc.getFileLocWithOffset(1);
1846 buf = " /* @catch begin */ else {\n";
1847 buf += " id _caught = objc_exception_extract(&_stack);\n";
1848 buf += " objc_exception_try_enter (&_stack);\n";
1849 buf += " if (_setjmp(_stack.buf))\n";
1850 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1851 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001852
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001853 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001854 } else { /* no catch list */
1855 buf = "}\nelse {\n";
1856 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1857 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001858 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001859 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001860 bool sawIdTypedCatch = false;
1861 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001862 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1863 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001864 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001865
Douglas Gregor96c79492010-04-23 22:50:49 +00001866 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001867 buf = "if ("; // we are generating code for the first catch clause
1868 else
1869 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001870 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001871 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001872
Steve Naroffbf478ec2007-11-07 04:08:17 +00001873 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001874
Steve Naroffbf478ec2007-11-07 04:08:17 +00001875 const char *lParenLoc = strchr(startBuf, '(');
1876
Douglas Gregor96c79492010-04-23 22:50:49 +00001877 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001878 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001879 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001880 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1881 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001882 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001883 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001884 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001885
Steve Naroffedb5bc62008-02-01 20:02:07 +00001886 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001887 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001888 } else if (catchDecl) {
1889 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001890 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001891 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001892 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001893 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001894 } else if (const ObjCObjectPointerType *Ptr =
1895 t->getAs<ObjCObjectPointerType>()) {
1896 // Should be a pointer to a class.
1897 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1898 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001899 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001900 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001901 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001902 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001903 }
1904 }
1905 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001906 lastCatchBody = Catch->getCatchBody();
1907 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001908 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1909 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1910 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1911 assert((*rParenBuf == ')') && "bogus @catch paren location");
1912 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001913
Mike Stump11289f42009-09-09 15:08:12 +00001914 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001915 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001916 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001917 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001918 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001919 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001920 }
1921 // Complete the catch list...
1922 if (lastCatchBody) {
1923 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001924 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1925 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001926
Steve Naroff4adbe312008-09-11 15:29:03 +00001927 // Insert the last (implicit) else clause *before* the right curly brace.
1928 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1929 buf = "} /* last catch end */\n";
1930 buf += "else {\n";
1931 buf += " _rethrow = _caught;\n";
1932 buf += " objc_exception_try_exit(&_stack);\n";
1933 buf += "} } /* @catch end */\n";
1934 if (!S->getFinallyStmt())
1935 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001936 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001937
Steve Naroffbf478ec2007-11-07 04:08:17 +00001938 // Set lastCurlyLoc
1939 lastCurlyLoc = lastCatchBody->getLocEnd();
1940 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001941 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001942 startLoc = finalStmt->getLocStart();
1943 startBuf = SM->getCharacterData(startLoc);
1944 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001945
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001946 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001947
Steve Naroffbf478ec2007-11-07 04:08:17 +00001948 Stmt *body = finalStmt->getFinallyBody();
1949 SourceLocation startLoc = body->getLocStart();
1950 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001951 assert(*SM->getCharacterData(startLoc) == '{' &&
1952 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001953 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001954 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001955
Steve Naroffbf478ec2007-11-07 04:08:17 +00001956 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001957 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001959 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001960
Steve Naroffbf478ec2007-11-07 04:08:17 +00001961 // Set lastCurlyLoc
1962 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001963
Steve Naroff6d6da252008-12-05 17:03:39 +00001964 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001965 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001966 } else { /* no finally clause - make sure we synthesize an implicit one */
1967 buf = "{ /* implicit finally clause */\n";
1968 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1969 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1970 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001971 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001972
1973 // Now check for any return/continue/go statements within the @try.
1974 // The implicit finally clause won't called if the @try contains any
1975 // jump statements.
1976 bool hasReturns = false;
1977 HasReturnStmts(S->getTryBody(), hasReturns);
1978 if (hasReturns)
1979 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001980 }
1981 // Now emit the final closing curly brace...
1982 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001983 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001984 return 0;
1985}
1986
Mike Stump11289f42009-09-09 15:08:12 +00001987// This can't be done with ReplaceStmt(S, ThrowExpr), since
1988// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001989// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001990Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001991 // Get the start location and compute the semi location.
1992 SourceLocation startLoc = S->getLocStart();
1993 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001994
Steve Naroffa733c7f2007-11-07 15:32:26 +00001995 assert((*startBuf == '@') && "bogus @throw location");
1996
1997 std::string buf;
1998 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001999 if (S->getThrowExpr())
2000 buf = "objc_exception_throw(";
2001 else // add an implicit argument
2002 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002003
Steve Naroff29788342008-07-25 15:41:30 +00002004 // handle "@ throw" correctly.
2005 const char *wBuf = strchr(startBuf, 'w');
2006 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002007 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002008
Steve Naroffa733c7f2007-11-07 15:32:26 +00002009 const char *semiBuf = strchr(startBuf, ';');
2010 assert((*semiBuf == ';') && "@throw: can't find ';'");
2011 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002012 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002013 return 0;
2014}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002015
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002016Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002017 // Create a new string expression.
2018 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002019 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002020 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002021 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2022 StrEncoding.length(), false,StrType,
2023 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002024 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner4431a1b2007-11-30 22:53:43 +00002026 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002027 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002028 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002029}
2030
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002031Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002032 if (!SelGetUidFunctionDecl)
2033 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002034 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2035 // Create a call to sel_registerName("selName").
2036 llvm::SmallVector<Expr*, 8> SelExprs;
2037 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002038 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002039 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002040 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002041 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002042 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2043 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002044 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002045 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002046 return SelExp;
2047}
2048
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002049CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002050 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2051 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002052 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002053 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002054
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002055 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002056 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002057
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002058 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002059 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002060 ImplicitCastExpr *ICE =
John McCalle3027922010-08-25 11:45:40 +00002061 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall2536c6d2010-08-25 10:28:54 +00002062 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCall9dd450b2009-09-21 23:43:11 +00002064 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002065
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002066 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002067 new (Context) CallExpr(*Context, ICE, args, nargs,
2068 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002069 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002070}
2071
Steve Naroff50d42052007-11-01 13:24:47 +00002072static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2073 const char *&startRef, const char *&endRef) {
2074 while (startBuf < endBuf) {
2075 if (*startBuf == '<')
2076 startRef = startBuf; // mark the start.
2077 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002078 if (startRef && *startRef == '<') {
2079 endRef = startBuf; // mark the end.
2080 return true;
2081 }
2082 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002083 }
2084 startBuf++;
2085 }
2086 return false;
2087}
2088
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002089static void scanToNextArgument(const char *&argRef) {
2090 int angle = 0;
2091 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2092 if (*argRef == '<')
2093 angle++;
2094 else if (*argRef == '>')
2095 angle--;
2096 argRef++;
2097 }
2098 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2099}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002100
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002101bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002102 if (T->isObjCQualifiedIdType())
2103 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002104 if (const PointerType *PT = T->getAs<PointerType>()) {
2105 if (PT->getPointeeType()->isObjCQualifiedIdType())
2106 return true;
2107 }
2108 if (T->isObjCObjectPointerType()) {
2109 T = T->getPointeeType();
2110 return T->isObjCQualifiedInterfaceType();
2111 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002112 if (T->isArrayType()) {
2113 QualType ElemTy = Context->getBaseElementType(T);
2114 return needToScanForQualifiers(ElemTy);
2115 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002116 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002117}
2118
Steve Naroff873bd842008-07-29 18:15:38 +00002119void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2120 QualType Type = E->getType();
2121 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002122 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Steve Naroffdbfc6932008-11-19 21:15:47 +00002124 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2125 Loc = ECE->getLParenLoc();
2126 EndLoc = ECE->getRParenLoc();
2127 } else {
2128 Loc = E->getLocStart();
2129 EndLoc = E->getLocEnd();
2130 }
2131 // This will defend against trying to rewrite synthesized expressions.
2132 if (Loc.isInvalid() || EndLoc.isInvalid())
2133 return;
2134
Steve Naroff873bd842008-07-29 18:15:38 +00002135 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002136 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002137 const char *startRef = 0, *endRef = 0;
2138 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2139 // Get the locations of the startRef, endRef.
2140 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2141 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2142 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002143 InsertText(LessLoc, "/*");
2144 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002145 }
2146 }
2147}
2148
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002149void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002150 SourceLocation Loc;
2151 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002152 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002153 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2154 Loc = VD->getLocation();
2155 Type = VD->getType();
2156 }
2157 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2158 Loc = FD->getLocation();
2159 // Check for ObjC 'id' and class types that have been adorned with protocol
2160 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002161 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002162 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002163 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002164 if (!proto)
2165 return;
2166 Type = proto->getResultType();
2167 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002168 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2169 Loc = FD->getLocation();
2170 Type = FD->getType();
2171 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002172 else
2173 return;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002175 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002176 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002177
Steve Naroff50d42052007-11-01 13:24:47 +00002178 const char *endBuf = SM->getCharacterData(Loc);
2179 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002180 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002181 startBuf--; // scan backward (from the decl location) for return type.
2182 const char *startRef = 0, *endRef = 0;
2183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2186 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2187 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002190 }
2191 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002192 if (!proto)
2193 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002194 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002195 const char *startBuf = SM->getCharacterData(Loc);
2196 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002197 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2198 if (needToScanForQualifiers(proto->getArgType(i))) {
2199 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002200
Steve Naroff50d42052007-11-01 13:24:47 +00002201 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002202 // scan forward (from the decl location) for argument types.
2203 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002204 const char *startRef = 0, *endRef = 0;
2205 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002207 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002208 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002209 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002210 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002211 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002212 InsertText(LessLoc, "/*");
2213 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002214 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002215 startBuf = ++endBuf;
2216 }
2217 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002218 // If the function name is derived from a macro expansion, then the
2219 // argument buffer will not follow the name. Need to speak with Chris.
2220 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002221 startBuf++; // scan forward (from the decl location) for argument types.
2222 startBuf++;
2223 }
Steve Naroff50d42052007-11-01 13:24:47 +00002224 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002225}
2226
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002227void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2228 QualType QT = ND->getType();
2229 const Type* TypePtr = QT->getAs<Type>();
2230 if (!isa<TypeOfExprType>(TypePtr))
2231 return;
2232 while (isa<TypeOfExprType>(TypePtr)) {
2233 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2234 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2235 TypePtr = QT->getAs<Type>();
2236 }
2237 // FIXME. This will not work for multiple declarators; as in:
2238 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002239 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002240 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2241 const char *startBuf = SM->getCharacterData(DeclLoc);
2242 if (ND->getInit()) {
2243 std::string Name(ND->getNameAsString());
2244 TypeAsString += " " + Name + " = ";
2245 Expr *E = ND->getInit();
2246 SourceLocation startLoc;
2247 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2248 startLoc = ECE->getLParenLoc();
2249 else
2250 startLoc = E->getLocStart();
2251 startLoc = SM->getInstantiationLoc(startLoc);
2252 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002254 }
2255 else {
2256 SourceLocation X = ND->getLocEnd();
2257 X = SM->getInstantiationLoc(X);
2258 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002259 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002260 }
2261}
2262
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002263// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002264void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002265 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2266 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002267 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002268 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002269 &ArgTys[0], ArgTys.size(),
2270 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002271 false, false, 0, 0,
2272 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002273 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002274 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002275 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002276 SC_Extern,
2277 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002278}
2279
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002280void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002281 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002282 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002283 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002284 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002285 return;
2286 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002287 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002288}
2289
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002290void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2291 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002292 const char *argPtr = TypeString.c_str();
2293 if (!strchr(argPtr, '^')) {
2294 Str += TypeString;
2295 return;
2296 }
2297 while (*argPtr) {
2298 Str += (*argPtr == '^' ? '*' : *argPtr);
2299 argPtr++;
2300 }
2301}
2302
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002303// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002304void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2305 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002306 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002307 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002308 const char *argPtr = TypeString.c_str();
2309 int paren = 0;
2310 while (*argPtr) {
2311 switch (*argPtr) {
2312 case '(':
2313 Str += *argPtr;
2314 paren++;
2315 break;
2316 case ')':
2317 Str += *argPtr;
2318 paren--;
2319 break;
2320 case '^':
2321 Str += '*';
2322 if (paren == 1)
2323 Str += VD->getNameAsString();
2324 break;
2325 default:
2326 Str += *argPtr;
2327 break;
2328 }
2329 argPtr++;
2330 }
2331}
2332
2333
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002334void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2335 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2336 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2337 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2338 if (!proto)
2339 return;
2340 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002341 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002342 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002343 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002344 FdStr += "(";
2345 unsigned numArgs = proto->getNumArgs();
2346 for (unsigned i = 0; i < numArgs; i++) {
2347 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002348 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002349 if (i+1 < numArgs)
2350 FdStr += ", ";
2351 }
2352 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002353 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002354 CurFunctionDeclToDeclareForBlock = 0;
2355}
2356
Steve Naroff17978c42008-03-11 17:37:02 +00002357// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002358void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002359 if (SuperContructorFunctionDecl)
2360 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002361 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002362 llvm::SmallVector<QualType, 16> ArgTys;
2363 QualType argT = Context->getObjCIdType();
2364 assert(!argT.isNull() && "Can't find 'id' type");
2365 ArgTys.push_back(argT);
2366 ArgTys.push_back(argT);
2367 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2368 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002369 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002370 false, false, 0, 0,
2371 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002372 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002373 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002374 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002375 SC_Extern,
2376 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002377}
2378
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002379// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002380void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002381 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2382 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002383 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002384 assert(!argT.isNull() && "Can't find 'id' type");
2385 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002386 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002387 assert(!argT.isNull() && "Can't find 'SEL' type");
2388 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002389 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002390 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002391 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002392 false, false, 0, 0,
2393 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002394 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002395 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002396 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002397 SC_Extern,
2398 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002399}
2400
Steve Naroff7fa2f042007-11-15 10:28:18 +00002401// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002402void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002403 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2404 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002405 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002406 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002407 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002408 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2409 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2410 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002411 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002412 assert(!argT.isNull() && "Can't find 'SEL' type");
2413 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002414 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002415 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002416 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002417 false, false, 0, 0,
2418 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002419 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002420 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002421 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002422 SC_Extern,
2423 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002424}
2425
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002426// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002427void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002428 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2429 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002430 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002431 assert(!argT.isNull() && "Can't find 'id' type");
2432 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002433 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002434 assert(!argT.isNull() && "Can't find 'SEL' type");
2435 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002436 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002437 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002438 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002439 false, false, 0, 0,
2440 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002441 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002442 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002443 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002444 SC_Extern,
2445 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002446}
2447
Mike Stump11289f42009-09-09 15:08:12 +00002448// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002449// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002450void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002451 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002452 &Context->Idents.get("objc_msgSendSuper_stret");
2453 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002454 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002455 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002456 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002457 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2458 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2459 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002460 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002461 assert(!argT.isNull() && "Can't find 'SEL' type");
2462 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002463 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002464 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002465 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002466 false, false, 0, 0,
2467 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002468 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002469 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002470 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002471 SC_Extern,
2472 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002473}
2474
Steve Naroff2e4e3852008-05-08 22:02:18 +00002475// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002476void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002477 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2478 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002479 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002480 assert(!argT.isNull() && "Can't find 'id' type");
2481 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002482 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002483 assert(!argT.isNull() && "Can't find 'SEL' type");
2484 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002485 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002486 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002487 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002488 false, false, 0, 0,
2489 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002490 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002491 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002492 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002493 SC_Extern,
2494 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002495}
2496
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002497// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002498void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002499 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2500 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002501 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002502 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002503 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002504 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002505 false, false, 0, 0,
2506 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002507 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002508 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002509 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002512}
2513
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002514// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2515void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2516 IdentifierInfo *getSuperClassIdent =
2517 &Context->Idents.get("class_getSuperclass");
2518 llvm::SmallVector<QualType, 16> ArgTys;
2519 ArgTys.push_back(Context->getObjCClassType());
2520 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2521 &ArgTys[0], ArgTys.size(),
2522 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002523 false, false, 0, 0,
2524 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002525 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002526 SourceLocation(),
2527 getSuperClassIdent,
2528 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002529 SC_Extern,
2530 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002531 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002532}
2533
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002534// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002535void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002536 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2537 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002538 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002539 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002540 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002541 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002542 false, false, 0, 0,
2543 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002544 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002545 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002546 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002547 SC_Extern,
2548 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002549}
2550
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002551Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002552 QualType strType = getConstantStringStructType();
2553
2554 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002555
2556 std::string tmpName = InFileName;
2557 unsigned i;
2558 for (i=0; i < tmpName.length(); i++) {
2559 char c = tmpName.at(i);
2560 // replace any non alphanumeric characters with '_'.
2561 if (!isalpha(c) && (c < '0' || c > '9'))
2562 tmpName[i] = '_';
2563 }
2564 S += tmpName;
2565 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002566 S += utostr(NumObjCStringLiterals++);
2567
Steve Naroff00a31762008-03-27 22:29:16 +00002568 Preamble += "static __NSConstantStringImpl " + S;
2569 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2570 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002571 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002572 std::string prettyBufS;
2573 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002574 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2575 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002576 Preamble += prettyBuf.str();
2577 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002578 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002579
2580 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002581 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002582 SC_Static, SC_None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002583 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002584 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002585 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002586 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002587 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002588 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalle3027922010-08-25 11:45:40 +00002589 CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002590 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002591 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002592 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002593}
2594
Steve Naroff7fa2f042007-11-15 10:28:18 +00002595// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002596QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002597 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002598 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002599 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002600 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002601 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002602
Steve Naroff7fa2f042007-11-15 10:28:18 +00002603 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002604 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002605 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002606 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002607
Steve Naroff7fa2f042007-11-15 10:28:18 +00002608 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002609 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002610 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2611 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002612 FieldTypes[i], 0,
2613 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002614 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002615 }
Mike Stump11289f42009-09-09 15:08:12 +00002616
Douglas Gregord5058122010-02-11 01:19:42 +00002617 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002618 }
2619 return Context->getTagDeclType(SuperStructDecl);
2620}
2621
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002622QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002623 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002624 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002625 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002626 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002627 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002628
Steve Naroffce8e8862008-03-15 00:55:56 +00002629 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002630 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002631 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002632 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002633 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002634 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002635 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002636 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002637
Steve Naroffce8e8862008-03-15 00:55:56 +00002638 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002639 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002640 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2641 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002642 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002643 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002644 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002645 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002646 }
2647
Douglas Gregord5058122010-02-11 01:19:42 +00002648 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002649 }
2650 return Context->getTagDeclType(ConstantStringDecl);
2651}
2652
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002653Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2654 SourceLocation StartLoc,
2655 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002656 if (!SelGetUidFunctionDecl)
2657 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002658 if (!MsgSendFunctionDecl)
2659 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002660 if (!MsgSendSuperFunctionDecl)
2661 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002662 if (!MsgSendStretFunctionDecl)
2663 SynthMsgSendStretFunctionDecl();
2664 if (!MsgSendSuperStretFunctionDecl)
2665 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002666 if (!MsgSendFpretFunctionDecl)
2667 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002668 if (!GetClassFunctionDecl)
2669 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002670 if (!GetSuperClassFunctionDecl)
2671 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002672 if (!GetMetaClassFunctionDecl)
2673 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002674
Steve Naroff7fa2f042007-11-15 10:28:18 +00002675 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002676 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2677 // May need to use objc_msgSend_stret() as well.
2678 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002679 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2680 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002681 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002682 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002683 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002684 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
Steve Naroff574440f2007-10-24 22:48:43 +00002687 // Synthesize a call to objc_msgSend().
2688 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002689 switch (Exp->getReceiverKind()) {
2690 case ObjCMessageExpr::SuperClass: {
2691 MsgSendFlavor = MsgSendSuperFunctionDecl;
2692 if (MsgSendStretFlavor)
2693 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2694 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002695
Douglas Gregor9a129192010-04-21 00:45:42 +00002696 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor9a129192010-04-21 00:45:42 +00002698 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002699
Douglas Gregor9a129192010-04-21 00:45:42 +00002700 // set the receiver to self, the first argument to all methods.
2701 InitExprs.push_back(
2702 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002703 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002704 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2705 Context->getObjCIdType(),
2706 SourceLocation()))
2707 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002708
Douglas Gregor9a129192010-04-21 00:45:42 +00002709 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2710 llvm::SmallVector<Expr*, 8> ClsExprs;
2711 QualType argType = Context->getPointerType(Context->CharTy);
2712 ClsExprs.push_back(StringLiteral::Create(*Context,
2713 ClassDecl->getIdentifier()->getNameStart(),
2714 ClassDecl->getIdentifier()->getLength(),
2715 false, argType, SourceLocation()));
2716 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2717 &ClsExprs[0],
2718 ClsExprs.size(),
2719 StartLoc,
2720 EndLoc);
2721 // (Class)objc_getClass("CurrentClass")
2722 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2723 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002724 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002725 ClsExprs.clear();
2726 ClsExprs.push_back(ArgExpr);
2727 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2728 &ClsExprs[0], ClsExprs.size(),
2729 StartLoc, EndLoc);
2730
2731 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2732 // To turn off a warning, type-cast to 'id'
2733 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2734 NoTypeInfoCStyleCastExpr(Context,
2735 Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002736 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002737 // struct objc_super
2738 QualType superType = getSuperStructType();
2739 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002740
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 if (LangOpts.Microsoft) {
2742 SynthSuperContructorFunctionDecl();
2743 // Simulate a contructor call...
2744 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2745 superType, SourceLocation());
2746 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2747 InitExprs.size(),
2748 superType, SourceLocation());
2749 // The code for super is a little tricky to prevent collision with
2750 // the structure definition in the header. The rewriter has it's own
2751 // internal definition (__rw_objc_super) that is uses. This is why
2752 // we need the cast below. For example:
2753 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2754 //
John McCalle3027922010-08-25 11:45:40 +00002755 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002756 Context->getPointerType(SuperRep->getType()),
2757 SourceLocation());
2758 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2759 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002760 CK_Unknown, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002761 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002762 // (struct objc_super) { <exprs from above> }
2763 InitListExpr *ILE =
2764 new (Context) InitListExpr(*Context, SourceLocation(),
2765 &InitExprs[0], InitExprs.size(),
2766 SourceLocation());
2767 TypeSourceInfo *superTInfo
2768 = Context->getTrivialTypeSourceInfo(superType);
2769 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2770 superType, ILE, false);
2771 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002772 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002773 Context->getPointerType(SuperRep->getType()),
2774 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002775 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 MsgExprs.push_back(SuperRep);
2777 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002778 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002779
2780 case ObjCMessageExpr::Class: {
2781 llvm::SmallVector<Expr*, 8> ClsExprs;
2782 QualType argType = Context->getPointerType(Context->CharTy);
2783 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002784 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 IdentifierInfo *clsName = Class->getIdentifier();
2786 ClsExprs.push_back(StringLiteral::Create(*Context,
2787 clsName->getNameStart(),
2788 clsName->getLength(),
2789 false, argType,
2790 SourceLocation()));
2791 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2792 &ClsExprs[0],
2793 ClsExprs.size(),
2794 StartLoc, EndLoc);
2795 MsgExprs.push_back(Cls);
2796 break;
2797 }
2798
2799 case ObjCMessageExpr::SuperInstance:{
2800 MsgSendFlavor = MsgSendSuperFunctionDecl;
2801 if (MsgSendStretFlavor)
2802 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2803 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2804 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2805 llvm::SmallVector<Expr*, 4> InitExprs;
2806
2807 InitExprs.push_back(
2808 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002809 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002810 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2811 Context->getObjCIdType(),
2812 SourceLocation()))
2813 ); // set the 'receiver'.
2814
2815 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2816 llvm::SmallVector<Expr*, 8> ClsExprs;
2817 QualType argType = Context->getPointerType(Context->CharTy);
2818 ClsExprs.push_back(StringLiteral::Create(*Context,
2819 ClassDecl->getIdentifier()->getNameStart(),
2820 ClassDecl->getIdentifier()->getLength(),
2821 false, argType, SourceLocation()));
2822 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2823 &ClsExprs[0],
2824 ClsExprs.size(),
2825 StartLoc, EndLoc);
2826 // (Class)objc_getClass("CurrentClass")
2827 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2828 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002829 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002830 ClsExprs.clear();
2831 ClsExprs.push_back(ArgExpr);
2832 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2833 &ClsExprs[0], ClsExprs.size(),
2834 StartLoc, EndLoc);
2835
2836 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2837 // To turn off a warning, type-cast to 'id'
2838 InitExprs.push_back(
2839 // set 'super class', using class_getSuperclass().
2840 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002841 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002842 // struct objc_super
2843 QualType superType = getSuperStructType();
2844 Expr *SuperRep;
2845
2846 if (LangOpts.Microsoft) {
2847 SynthSuperContructorFunctionDecl();
2848 // Simulate a contructor call...
2849 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2850 superType, SourceLocation());
2851 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2852 InitExprs.size(),
2853 superType, SourceLocation());
2854 // The code for super is a little tricky to prevent collision with
2855 // the structure definition in the header. The rewriter has it's own
2856 // internal definition (__rw_objc_super) that is uses. This is why
2857 // we need the cast below. For example:
2858 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2859 //
John McCalle3027922010-08-25 11:45:40 +00002860 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002861 Context->getPointerType(SuperRep->getType()),
2862 SourceLocation());
2863 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2864 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002865 CK_Unknown, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002866 } else {
2867 // (struct objc_super) { <exprs from above> }
2868 InitListExpr *ILE =
2869 new (Context) InitListExpr(*Context, SourceLocation(),
2870 &InitExprs[0], InitExprs.size(),
2871 SourceLocation());
2872 TypeSourceInfo *superTInfo
2873 = Context->getTrivialTypeSourceInfo(superType);
2874 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2875 superType, ILE, false);
2876 }
2877 MsgExprs.push_back(SuperRep);
2878 break;
2879 }
2880
2881 case ObjCMessageExpr::Instance: {
2882 // Remove all type-casts because it may contain objc-style types; e.g.
2883 // Foo<Proto> *.
2884 Expr *recExpr = Exp->getInstanceReceiver();
2885 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2886 recExpr = CE->getSubExpr();
2887 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002888 CK_Unknown, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002889 MsgExprs.push_back(recExpr);
2890 break;
2891 }
2892 }
2893
Steve Naroffa397efd2007-11-03 11:27:19 +00002894 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002895 llvm::SmallVector<Expr*, 8> SelExprs;
2896 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002897 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002898 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002899 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002900 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002901 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002902 &SelExprs[0], SelExprs.size(),
2903 StartLoc,
2904 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002905 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002906
Steve Naroff574440f2007-10-24 22:48:43 +00002907 // Now push any user supplied arguments.
2908 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002909 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002910 // Make all implicit casts explicit...ICE comes in handy:-)
2911 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2912 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002913 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002914 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002915 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002916 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002917 (void)convertBlockPointerToFunctionPointer(type);
John McCalle3027922010-08-25 11:45:40 +00002918 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00002919 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002920 }
2921 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002922 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002923 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002924 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002925 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002926 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002927 CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002930 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002931 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2932 // out the argument in the original expression (since we aren't deleting
2933 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2934 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002935 }
Steve Narofff36987c2007-11-04 22:37:50 +00002936 // Generate the funky cast.
2937 CastExpr *cast;
2938 llvm::SmallVector<QualType, 8> ArgTypes;
2939 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002940
Steve Narofff36987c2007-11-04 22:37:50 +00002941 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002942 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2943 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2944 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002945 ArgTypes.push_back(Context->getObjCIdType());
2946 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002947 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002948 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002949 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2950 E = OMD->param_end(); PI != E; ++PI) {
2951 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002952 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002953 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002954 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002955 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002956 ArgTypes.push_back(t);
2957 }
Chris Lattnera4997152009-02-20 18:43:26 +00002958 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2959 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002960 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002961 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002962 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002963 }
2964 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002965 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002966
Steve Narofff36987c2007-11-04 22:37:50 +00002967 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002968 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002969 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002970
Mike Stump11289f42009-09-09 15:08:12 +00002971 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002972 // If we don't do this cast, we get the following bizarre warning/note:
2973 // xx.m:13: warning: function called through a non-compatible type
2974 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002975 cast = NoTypeInfoCStyleCastExpr(Context,
2976 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00002977 CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002978
Steve Narofff36987c2007-11-04 22:37:50 +00002979 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002980 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002981 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002982 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002983 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002984 false, false, 0, 0,
2985 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00002986 castType = Context->getPointerType(castType);
John McCalle3027922010-08-25 11:45:40 +00002987 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00002988 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002989
2990 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002991 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002992
John McCall9dd450b2009-09-21 23:43:11 +00002993 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002994 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002995 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002996 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002997 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002998 if (MsgSendStretFlavor) {
2999 // We have the method which returns a struct/union. Must also generate
3000 // call to objc_msgSend_stret and hang both varieties on a conditional
3001 // expression which dictate which one to envoke depending on size of
3002 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003003
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003004 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003005 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003006 SourceLocation());
3007 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003008 cast = NoTypeInfoCStyleCastExpr(Context,
3009 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00003010 CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003011 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003012 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003013 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003014 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003015 false, false, 0, 0,
3016 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +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);
Mike Stump11289f42009-09-09 15:08:12 +00003020
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003021 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003022 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003023
John McCall9dd450b2009-09-21 23:43:11 +00003024 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003025 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003026 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003027 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003028
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003029 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003030 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003031 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003032 Context->getSizeType(),
3033 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003034 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3035 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3036 // For X86 it is more complicated and some kind of target specific routine
3037 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003038 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003039 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003040 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3041 llvm::APInt(IntSize, 8),
3042 Context->IntTy,
3043 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003044 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCalle3027922010-08-25 11:45:40 +00003045 BO_LE,
Mike Stump11289f42009-09-09 15:08:12 +00003046 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003047 SourceLocation());
3048 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003049 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003050 new (Context) ConditionalOperator(lessThanExpr,
3051 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003052 SourceLocation(), STCE, (Expr*)0,
3053 returnType);
3054 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3055 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003056 }
Mike Stump11289f42009-09-09 15:08:12 +00003057 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003058 return ReplacingStmt;
3059}
3060
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003061Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003062 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3063 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003064
Steve Naroff574440f2007-10-24 22:48:43 +00003065 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003066 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003067
3068 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003069 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003070}
3071
Steve Naroffd9803712009-04-29 16:37:50 +00003072// typedef struct objc_object Protocol;
3073QualType RewriteObjC::getProtocolType() {
3074 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003075 TypeSourceInfo *TInfo
3076 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003077 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003078 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003079 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003080 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003081 }
3082 return Context->getTypeDeclType(ProtocolTypeDecl);
3083}
3084
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003085/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003086/// a synthesized/forward data reference (to the protocol's metadata).
3087/// The forward references (and metadata) are generated in
3088/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003089Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003090 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3091 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003092 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003093 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003094 SC_Extern, SC_None);
Steve Naroffd9803712009-04-29 16:37:50 +00003095 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003096 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003097 Context->getPointerType(DRE->getType()),
3098 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003099 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalle3027922010-08-25 11:45:40 +00003100 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003101 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003102 ReplaceStmt(Exp, castExpr);
3103 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003104 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003105 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003106
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003107}
3108
Mike Stump11289f42009-09-09 15:08:12 +00003109bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003110 const char *endBuf) {
3111 while (startBuf < endBuf) {
3112 if (*startBuf == '#') {
3113 // Skip whitespace.
3114 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3115 ;
3116 if (!strncmp(startBuf, "if", strlen("if")) ||
3117 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3118 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3119 !strncmp(startBuf, "define", strlen("define")) ||
3120 !strncmp(startBuf, "undef", strlen("undef")) ||
3121 !strncmp(startBuf, "else", strlen("else")) ||
3122 !strncmp(startBuf, "elif", strlen("elif")) ||
3123 !strncmp(startBuf, "endif", strlen("endif")) ||
3124 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3125 !strncmp(startBuf, "include", strlen("include")) ||
3126 !strncmp(startBuf, "import", strlen("import")) ||
3127 !strncmp(startBuf, "include_next", strlen("include_next")))
3128 return true;
3129 }
3130 startBuf++;
3131 }
3132 return false;
3133}
3134
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003135/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003136/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003137void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003138 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003139 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003140 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003141 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003142 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003143 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003144 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003145 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003146 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003147 SourceLocation LocStart = CDecl->getLocStart();
3148 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003149
Steve Naroffdde78982007-11-14 19:25:57 +00003150 const char *startBuf = SM->getCharacterData(LocStart);
3151 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003152
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003153 // If no ivars and no root or if its root, directly or indirectly,
3154 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003155 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3156 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003157 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003158 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003159 return;
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
3162 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003163 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003164 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003165 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003166 if (LangOpts.Microsoft)
3167 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003168
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003169 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003170 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003171 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003172 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003173 // If the buffer contains preprocessor directives, we do more fine-grained
3174 // rewrites. This is intended to fix code that looks like (which occurs in
3175 // NSURL.h, for example):
3176 //
3177 // #ifdef XYZ
3178 // @interface Foo : NSObject
3179 // #else
3180 // @interface FooBar : NSObject
3181 // #endif
3182 // {
3183 // int i;
3184 // }
3185 // @end
3186 //
3187 // This clause is segregated to avoid breaking the common case.
3188 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003189 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003190 CDecl->getClassLoc();
3191 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003192 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003193
Chris Lattnerf5b77512009-02-20 18:18:36 +00003194 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003195 // advance to the end of the referenced protocols.
3196 while (endHeader < cursor && *endHeader != '>') endHeader++;
3197 endHeader++;
3198 }
3199 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003200 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003201 } else {
3202 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003203 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003204 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003205 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003206 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003207 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003208 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003209 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003210 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003211
Steve Naroffdde78982007-11-14 19:25:57 +00003212 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003213 SourceLocation OnePastCurly =
3214 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003215 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003216 }
3217 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003218
Steve Naroffdde78982007-11-14 19:25:57 +00003219 // Now comment out any visibility specifiers.
3220 while (cursor < endBuf) {
3221 if (*cursor == '@') {
3222 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003223 // Skip whitespace.
3224 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3225 /*scan*/;
3226
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003227 // FIXME: presence of @public, etc. inside comment results in
3228 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003229 if (!strncmp(cursor, "public", strlen("public")) ||
3230 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003231 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003232 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003233 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003234 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003235 // FIXME: If there are cases where '<' is used in ivar declaration part
3236 // of user code, then scan the ivar list and use needToScanForQualifiers
3237 // for type checking.
3238 else if (*cursor == '<') {
3239 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003240 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003241 cursor = strchr(cursor, '>');
3242 cursor++;
3243 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003244 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003245 } else if (*cursor == '^') { // rewrite block specifier.
3246 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003247 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003248 }
Steve Naroffdde78982007-11-14 19:25:57 +00003249 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003250 }
Steve Naroffdde78982007-11-14 19:25:57 +00003251 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003252 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003253 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003254 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003255 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003256 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003257 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003258 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003259 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003260 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003261 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003262 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003263 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003264 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003265}
3266
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003267// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003268/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003269template<typename MethodIterator>
3270void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3271 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003272 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003273 llvm::StringRef prefix,
3274 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003275 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003276 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003277
Chris Lattner31bc07e2007-12-12 07:46:12 +00003278 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003279 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003280 SEL _cmd;
3281 char *method_types;
3282 void *_imp;
3283 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003284 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003285 Result += "\nstruct _objc_method {\n";
3286 Result += "\tSEL _cmd;\n";
3287 Result += "\tchar *method_types;\n";
3288 Result += "\tvoid *_imp;\n";
3289 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003290
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003291 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003294 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003295
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003296 /* struct {
3297 struct _objc_method_list *next_method;
3298 int method_count;
3299 struct _objc_method method_list[];
3300 }
3301 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003302 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003303 Result += "\nstatic struct {\n";
3304 Result += "\tstruct _objc_method_list *next_method;\n";
3305 Result += "\tint method_count;\n";
3306 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003307 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003308 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003309 Result += prefix;
3310 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3311 Result += "_METHODS_";
3312 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003313 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003314 Result += IsInstanceMethod ? "inst" : "cls";
3315 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003316 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003317
Chris Lattner31bc07e2007-12-12 07:46:12 +00003318 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003319 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003320 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003321 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003322 Result += "\", \"";
3323 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003324 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003325 Result += MethodInternalNames[*MethodBegin];
3326 Result += "}\n";
3327 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3328 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003329 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003330 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003331 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003332 Result += "\", \"";
3333 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003334 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003335 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003336 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003337 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003338 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003339}
3340
Steve Naroffd9803712009-04-29 16:37:50 +00003341/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003342void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003343RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3344 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003345 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003346
3347 // Output struct protocol_methods holder of method selector and type.
3348 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3349 /* struct protocol_methods {
3350 SEL _cmd;
3351 char *method_types;
3352 }
3353 */
3354 Result += "\nstruct _protocol_methods {\n";
3355 Result += "\tstruct objc_selector *_cmd;\n";
3356 Result += "\tchar *method_types;\n";
3357 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003358
Steve Naroffd9803712009-04-29 16:37:50 +00003359 objc_protocol_methods = true;
3360 }
3361 // Do not synthesize the protocol more than once.
3362 if (ObjCSynthesizedProtocols.count(PDecl))
3363 return;
Mike Stump11289f42009-09-09 15:08:12 +00003364
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003365 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3366 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3367 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003368 /* struct _objc_protocol_method_list {
3369 int protocol_method_count;
3370 struct protocol_methods protocols[];
3371 }
Steve Naroff251084d2008-03-12 01:06:30 +00003372 */
Steve Naroffd9803712009-04-29 16:37:50 +00003373 Result += "\nstatic struct {\n";
3374 Result += "\tint protocol_method_count;\n";
3375 Result += "\tstruct _protocol_methods protocol_methods[";
3376 Result += utostr(NumMethods);
3377 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3378 Result += PDecl->getNameAsString();
3379 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3380 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003381
Steve Naroffd9803712009-04-29 16:37:50 +00003382 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003383 for (ObjCProtocolDecl::instmeth_iterator
3384 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003385 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003386 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003387 Result += "\t ,{{(struct objc_selector *)\"";
3388 else
3389 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003390 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003391 std::string MethodTypeString;
3392 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3393 Result += "\", \"";
3394 Result += MethodTypeString;
3395 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003396 }
Steve Naroffd9803712009-04-29 16:37:50 +00003397 Result += "\t }\n};\n";
3398 }
Mike Stump11289f42009-09-09 15:08:12 +00003399
Steve Naroffd9803712009-04-29 16:37:50 +00003400 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003401 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3402 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003403 if (NumMethods > 0) {
3404 /* struct _objc_protocol_method_list {
3405 int protocol_method_count;
3406 struct protocol_methods protocols[];
3407 }
3408 */
3409 Result += "\nstatic struct {\n";
3410 Result += "\tint protocol_method_count;\n";
3411 Result += "\tstruct _protocol_methods protocol_methods[";
3412 Result += utostr(NumMethods);
3413 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3414 Result += PDecl->getNameAsString();
3415 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3416 "{\n\t";
3417 Result += utostr(NumMethods);
3418 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003419
Steve Naroffd9803712009-04-29 16:37:50 +00003420 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003421 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003422 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003423 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003424 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003425 Result += "\t ,{{(struct objc_selector *)\"";
3426 else
3427 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003428 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003429 std::string MethodTypeString;
3430 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3431 Result += "\", \"";
3432 Result += MethodTypeString;
3433 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003434 }
Steve Naroffd9803712009-04-29 16:37:50 +00003435 Result += "\t }\n};\n";
3436 }
3437
3438 // Output:
3439 /* struct _objc_protocol {
3440 // Objective-C 1.0 extensions
3441 struct _objc_protocol_extension *isa;
3442 char *protocol_name;
3443 struct _objc_protocol **protocol_list;
3444 struct _objc_protocol_method_list *instance_methods;
3445 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003446 };
Steve Naroffd9803712009-04-29 16:37:50 +00003447 */
3448 static bool objc_protocol = false;
3449 if (!objc_protocol) {
3450 Result += "\nstruct _objc_protocol {\n";
3451 Result += "\tstruct _objc_protocol_extension *isa;\n";
3452 Result += "\tchar *protocol_name;\n";
3453 Result += "\tstruct _objc_protocol **protocol_list;\n";
3454 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3455 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003456 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003457
Steve Naroffd9803712009-04-29 16:37:50 +00003458 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
Steve Naroffd9803712009-04-29 16:37:50 +00003461 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3462 Result += PDecl->getNameAsString();
3463 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3464 "{\n\t0, \"";
3465 Result += PDecl->getNameAsString();
3466 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003468 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3469 Result += PDecl->getNameAsString();
3470 Result += ", ";
3471 }
3472 else
3473 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003474 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003475 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3476 Result += PDecl->getNameAsString();
3477 Result += "\n";
3478 }
3479 else
3480 Result += "0\n";
3481 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003482
Steve Naroffd9803712009-04-29 16:37:50 +00003483 // Mark this protocol as having been generated.
3484 if (!ObjCSynthesizedProtocols.insert(PDecl))
3485 assert(false && "protocol already synthesized");
3486
3487}
3488
3489void RewriteObjC::
3490RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003491 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003492 std::string &Result) {
3493 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003494
Steve Naroffd9803712009-04-29 16:37:50 +00003495 for (unsigned i = 0; i != Protocols.size(); i++)
3496 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3497
Chris Lattner388f6e92008-07-21 21:33:21 +00003498 // Output the top lovel protocol meta-data for the class.
3499 /* struct _objc_protocol_list {
3500 struct _objc_protocol_list *next;
3501 int protocol_count;
3502 struct _objc_protocol *class_protocols[];
3503 }
3504 */
3505 Result += "\nstatic struct {\n";
3506 Result += "\tstruct _objc_protocol_list *next;\n";
3507 Result += "\tint protocol_count;\n";
3508 Result += "\tstruct _objc_protocol *class_protocols[";
3509 Result += utostr(Protocols.size());
3510 Result += "];\n} _OBJC_";
3511 Result += prefix;
3512 Result += "_PROTOCOLS_";
3513 Result += ClassName;
3514 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3515 "{\n\t0, ";
3516 Result += utostr(Protocols.size());
3517 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003518
Chris Lattner388f6e92008-07-21 21:33:21 +00003519 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003520 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003521 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003522
Chris Lattner388f6e92008-07-21 21:33:21 +00003523 for (unsigned i = 1; i != Protocols.size(); i++) {
3524 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003526 Result += "\n";
3527 }
3528 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003529}
3530
Steve Naroffd9803712009-04-29 16:37:50 +00003531
Mike Stump11289f42009-09-09 15:08:12 +00003532/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003533/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003534void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003536 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003537 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003538 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003539 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003540 CDecl = CDecl->getNextClassCategory())
3541 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3542 break;
Mike Stump11289f42009-09-09 15:08:12 +00003543
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003544 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003545 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003546 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003547
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003548 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003549 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003550 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003551
3552 // If any of our property implementations have associated getters or
3553 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003554 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3555 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003556 Prop != PropEnd; ++Prop) {
3557 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3558 continue;
3559 if (!(*Prop)->getPropertyIvarDecl())
3560 continue;
3561 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3562 if (!PD)
3563 continue;
3564 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3565 InstanceMethods.push_back(Getter);
3566 if (PD->isReadOnly())
3567 continue;
3568 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3569 InstanceMethods.push_back(Setter);
3570 }
3571 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003572 true, "CATEGORY_", FullCategoryName.c_str(),
3573 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003574
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003575 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003576 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003577 false, "CATEGORY_", FullCategoryName.c_str(),
3578 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003580 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003581 // Null CDecl is case of a category implementation with no category interface
3582 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003583 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003584 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003585 /* struct _objc_category {
3586 char *category_name;
3587 char *class_name;
3588 struct _objc_method_list *instance_methods;
3589 struct _objc_method_list *class_methods;
3590 struct _objc_protocol_list *protocols;
3591 // Objective-C 1.0 extensions
3592 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003593 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003594 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003595 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003596 */
Mike Stump11289f42009-09-09 15:08:12 +00003597
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003598 static bool objc_category = false;
3599 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003600 Result += "\nstruct _objc_category {\n";
3601 Result += "\tchar *category_name;\n";
3602 Result += "\tchar *class_name;\n";
3603 Result += "\tstruct _objc_method_list *instance_methods;\n";
3604 Result += "\tstruct _objc_method_list *class_methods;\n";
3605 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003606 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003607 Result += "\tstruct _objc_property_list *instance_properties;\n";
3608 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003609 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003610 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3612 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003613 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003614 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003615 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003616 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003617 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003618
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003619 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003620 Result += "\t, (struct _objc_method_list *)"
3621 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3622 Result += FullCategoryName;
3623 Result += "\n";
3624 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003625 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003626 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003627 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 Result += "\t, (struct _objc_method_list *)"
3629 "&_OBJC_CATEGORY_CLASS_METHODS_";
3630 Result += FullCategoryName;
3631 Result += "\n";
3632 }
3633 else
3634 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003635
Chris Lattnerf5b77512009-02-20 18:18:36 +00003636 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003637 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += FullCategoryName;
3639 Result += "\n";
3640 }
3641 else
3642 Result += "\t, 0\n";
3643 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003644}
3645
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003646/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3647/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003648void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003649 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003650 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003651 if (ivar->isBitField()) {
3652 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3653 // place all bitfields at offset 0.
3654 Result += "0";
3655 } else {
3656 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003657 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003658 if (LangOpts.Microsoft)
3659 Result += "_IMPL";
3660 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003661 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003662 Result += ")";
3663 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003664}
3665
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003666//===----------------------------------------------------------------------===//
3667// Meta Data Emission
3668//===----------------------------------------------------------------------===//
3669
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003670void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003671 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003672 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003673
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003674 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003675 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003676 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003677 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003678 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
Chris Lattner30d23e82007-12-12 07:56:42 +00003681 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003682 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003683 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003684 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003685 if (NumIvars > 0) {
3686 static bool objc_ivar = false;
3687 if (!objc_ivar) {
3688 /* struct _objc_ivar {
3689 char *ivar_name;
3690 char *ivar_type;
3691 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003692 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003693 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 Result += "\nstruct _objc_ivar {\n";
3695 Result += "\tchar *ivar_name;\n";
3696 Result += "\tchar *ivar_type;\n";
3697 Result += "\tint ivar_offset;\n";
3698 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003699
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003700 objc_ivar = true;
3701 }
3702
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003703 /* struct {
3704 int ivar_count;
3705 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003706 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003707 */
Mike Stump11289f42009-09-09 15:08:12 +00003708 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003709 Result += "\tint ivar_count;\n";
3710 Result += "\tstruct _objc_ivar ivar_list[";
3711 Result += utostr(NumIvars);
3712 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003713 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003714 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 "{\n\t";
3716 Result += utostr(NumIvars);
3717 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003718
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003719 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003720 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003721 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003722 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003723 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003724 IV != IVEnd; ++IV)
3725 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003726 IVI = IDecl->ivar_begin();
3727 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003728 } else {
3729 IVI = CDecl->ivar_begin();
3730 IVE = CDecl->ivar_end();
3731 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003732 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003733 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003734 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003735 std::string TmpString, StrEncoding;
3736 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3737 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003738 Result += StrEncoding;
3739 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003740 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003741 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003742 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003743 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003744 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003745 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003746 std::string TmpString, StrEncoding;
3747 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3748 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003749 Result += StrEncoding;
3750 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003751 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003752 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003755 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003758 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003759 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003760 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003761
3762 // If any of our property implementations have associated getters or
3763 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003764 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3765 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003766 Prop != PropEnd; ++Prop) {
3767 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3768 continue;
3769 if (!(*Prop)->getPropertyIvarDecl())
3770 continue;
3771 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3772 if (!PD)
3773 continue;
3774 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3775 InstanceMethods.push_back(Getter);
3776 if (PD->isReadOnly())
3777 continue;
3778 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3779 InstanceMethods.push_back(Setter);
3780 }
3781 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003782 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003784 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003785 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003786 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003787
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003788 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003789 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003790 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003791
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003792 // Declaration of class/meta-class metadata
3793 /* struct _objc_class {
3794 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003795 const char *super_class_name;
3796 char *name;
3797 long version;
3798 long info;
3799 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003800 struct _objc_ivar_list *ivars;
3801 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003802 struct objc_cache *cache;
3803 struct objc_protocol_list *protocols;
3804 const char *ivar_layout;
3805 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003806 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003807 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003808 static bool objc_class = false;
3809 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003810 Result += "\nstruct _objc_class {\n";
3811 Result += "\tstruct _objc_class *isa;\n";
3812 Result += "\tconst char *super_class_name;\n";
3813 Result += "\tchar *name;\n";
3814 Result += "\tlong version;\n";
3815 Result += "\tlong info;\n";
3816 Result += "\tlong instance_size;\n";
3817 Result += "\tstruct _objc_ivar_list *ivars;\n";
3818 Result += "\tstruct _objc_method_list *methods;\n";
3819 Result += "\tstruct objc_cache *cache;\n";
3820 Result += "\tstruct _objc_protocol_list *protocols;\n";
3821 Result += "\tconst char *ivar_layout;\n";
3822 Result += "\tstruct _objc_class_ext *ext;\n";
3823 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003824 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003825 }
Mike Stump11289f42009-09-09 15:08:12 +00003826
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003827 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003828 ObjCInterfaceDecl *RootClass = 0;
3829 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003830 while (SuperClass) {
3831 RootClass = SuperClass;
3832 SuperClass = SuperClass->getSuperClass();
3833 }
3834 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003835
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003836 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003837 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003838 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003839 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003840 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003841 Result += "\"";
3842
3843 if (SuperClass) {
3844 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003846 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003847 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003848 Result += "\"";
3849 }
3850 else {
3851 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003852 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003853 Result += "\"";
3854 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003855 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003856 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003857 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003858 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003859 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003860 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003861 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003862 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003863 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003864 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003865 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003866 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003867 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003868 Result += ",0,0\n";
3869 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003870 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003871 Result += "\t,0,0,0,0\n";
3872 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003873
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003874 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003875 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003876 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003877 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003878 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003879 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003880 if (SuperClass) {
3881 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003882 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003883 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003884 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003885 Result += "\"";
3886 }
3887 else {
3888 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003889 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003890 Result += "\"";
3891 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003892 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003893 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003894 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003895 Result += ",0";
3896 else {
3897 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003898 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003899 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003900 if (LangOpts.Microsoft)
3901 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003902 Result += ")";
3903 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003904 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003905 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003906 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003907 Result += "\n\t";
3908 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003909 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003910 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003911 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003912 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003913 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003914 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003915 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003916 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003917 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003918 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003919 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003921 Result += ", 0,0\n";
3922 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003923 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003924 Result += ",0,0,0\n";
3925 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003926}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003927
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003928/// RewriteImplementations - This routine rewrites all method implementations
3929/// and emits meta-data.
3930
Steve Narofff8cfd162008-11-13 20:07:04 +00003931void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003932 int ClsDefCount = ClassImplementation.size();
3933 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003934
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003935 // Rewrite implemented methods
3936 for (int i = 0; i < ClsDefCount; i++)
3937 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003938
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003939 for (int i = 0; i < CatDefCount; i++)
3940 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003941}
Mike Stump11289f42009-09-09 15:08:12 +00003942
Steve Narofff8cfd162008-11-13 20:07:04 +00003943void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3944 int ClsDefCount = ClassImplementation.size();
3945 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003946
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003947 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003948 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003949 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003950
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003951 // For each implemented category, write out all its meta data.
3952 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003953 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003954
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003955 // Write objc_symtab metadata
3956 /*
3957 struct _objc_symtab
3958 {
3959 long sel_ref_cnt;
3960 SEL *refs;
3961 short cls_def_cnt;
3962 short cat_def_cnt;
3963 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003964 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003965 */
Mike Stump11289f42009-09-09 15:08:12 +00003966
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003967 Result += "\nstruct _objc_symtab {\n";
3968 Result += "\tlong sel_ref_cnt;\n";
3969 Result += "\tSEL *refs;\n";
3970 Result += "\tshort cls_def_cnt;\n";
3971 Result += "\tshort cat_def_cnt;\n";
3972 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3973 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003974
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003975 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003976 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003977 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003978 + ", " + utostr(CatDefCount) + "\n";
3979 for (int i = 0; i < ClsDefCount; i++) {
3980 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003981 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003982 Result += "\n";
3983 }
Mike Stump11289f42009-09-09 15:08:12 +00003984
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003985 for (int i = 0; i < CatDefCount; i++) {
3986 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003987 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003988 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003989 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003990 Result += "\n";
3991 }
Mike Stump11289f42009-09-09 15:08:12 +00003992
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003993 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003994
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003995 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003996
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003997 /*
3998 struct _objc_module {
3999 long version;
4000 long size;
4001 const char *name;
4002 struct _objc_symtab *symtab;
4003 }
4004 */
Mike Stump11289f42009-09-09 15:08:12 +00004005
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004006 Result += "\nstruct _objc_module {\n";
4007 Result += "\tlong version;\n";
4008 Result += "\tlong size;\n";
4009 Result += "\tconst char *name;\n";
4010 Result += "\tstruct _objc_symtab *symtab;\n";
4011 Result += "};\n\n";
4012 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004013 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004014 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004015 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004016 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004017
4018 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004019 if (ProtocolExprDecls.size()) {
4020 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4021 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004022 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004023 E = ProtocolExprDecls.end(); I != E; ++I) {
4024 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4025 Result += (*I)->getNameAsString();
4026 Result += " = &_OBJC_PROTOCOL_";
4027 Result += (*I)->getNameAsString();
4028 Result += ";\n";
4029 }
4030 Result += "#pragma data_seg(pop)\n\n";
4031 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004032 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004033 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004034 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4035 Result += "&_OBJC_MODULES;\n";
4036 Result += "#pragma data_seg(pop)\n\n";
4037 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004038}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004039
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004040void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4041 const std::string &Name,
4042 ValueDecl *VD) {
4043 assert(BlockByRefDeclNo.count(VD) &&
4044 "RewriteByRefString: ByRef decl missing");
4045 ResultStr += "struct __Block_byref_" + Name +
4046 "_" + utostr(BlockByRefDeclNo[VD]) ;
4047}
4048
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004049static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4050 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4051 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4052 return false;
4053}
4054
Steve Naroff677ab3a2008-10-27 17:20:55 +00004055std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004056 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004057 std::string Tag) {
4058 const FunctionType *AFT = CE->getFunctionType();
4059 QualType RT = AFT->getResultType();
4060 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004061 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004062 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004063
Steve Naroff677ab3a2008-10-27 17:20:55 +00004064 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004065
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004066 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004067 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004068 // block (to reference imported block decl refs).
4069 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004070 } else if (BD->param_empty()) {
4071 S += "(" + StructRef + " *__cself)";
4072 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004073 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004074 assert(FT && "SynthesizeBlockFunc: No function proto");
4075 S += '(';
4076 // first add the implicit argument.
4077 S += StructRef + " *__cself, ";
4078 std::string ParamStr;
4079 for (BlockDecl::param_iterator AI = BD->param_begin(),
4080 E = BD->param_end(); AI != E; ++AI) {
4081 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004082 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004083 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004084 if (convertBlockPointerToFunctionPointer(QT))
4085 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004086 else
4087 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 S += ParamStr;
4089 }
4090 if (FT->isVariadic()) {
4091 if (!BD->param_empty()) S += ", ";
4092 S += "...";
4093 }
4094 S += ')';
4095 }
4096 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004097
Steve Naroff677ab3a2008-10-27 17:20:55 +00004098 // Create local declarations to avoid rewriting all closure decl ref exprs.
4099 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004100 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101 E = BlockByRefDecls.end(); I != E; ++I) {
4102 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004103 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004104 std::string TypeString;
4105 RewriteByRefString(TypeString, Name, (*I));
4106 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004107 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004108 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004109 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004110 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004111 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 E = BlockByCopyDecls.end(); I != E; ++I) {
4113 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004114 // Handle nested closure invocation. For example:
4115 //
4116 // void (^myImportedClosure)(void);
4117 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004118 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 // void (^anotherClosure)(void);
4120 // anotherClosure = ^(void) {
4121 // myImportedClosure(); // import and invoke the closure
4122 // };
4123 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004124 if (isTopLevelBlockPointerType((*I)->getType())) {
4125 RewriteBlockPointerTypeVariable(S, (*I));
4126 S += " = (";
4127 RewriteBlockPointerType(S, (*I)->getType());
4128 S += ")";
4129 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4130 }
4131 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004132 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004133 QualType QT = (*I)->getType();
4134 if (HasLocalVariableExternalStorage(*I))
4135 QT = Context->getPointerType(QT);
4136 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004137 S += Name + " = __cself->" +
4138 (*I)->getNameAsString() + "; // bound by copy\n";
4139 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 }
4141 std::string RewrittenStr = RewrittenBlockExprs[CE];
4142 const char *cstr = RewrittenStr.c_str();
4143 while (*cstr++ != '{') ;
4144 S += cstr;
4145 S += "\n";
4146 return S;
4147}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004148
Steve Naroff677ab3a2008-10-27 17:20:55 +00004149std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004150 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004151 std::string Tag) {
4152 std::string StructRef = "struct " + Tag;
4153 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004154
Steve Naroff677ab3a2008-10-27 17:20:55 +00004155 S += funcName;
4156 S += "_block_copy_" + utostr(i);
4157 S += "(" + StructRef;
4158 S += "*dst, " + StructRef;
4159 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004160 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004161 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004162 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004163 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004164 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004165 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004166 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004167 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004168 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004169 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004170 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004171 S += "}\n";
4172
Steve Naroff677ab3a2008-10-27 17:20:55 +00004173 S += "\nstatic void __";
4174 S += funcName;
4175 S += "_block_dispose_" + utostr(i);
4176 S += "(" + StructRef;
4177 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004178 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004179 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004180 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004181 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004182 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004183 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004184 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004185 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186 }
Mike Stump11289f42009-09-09 15:08:12 +00004187 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188 return S;
4189}
4190
Steve Naroff30484702009-12-06 21:14:13 +00004191std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4192 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004193 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004194 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004197 S += " struct " + Desc;
4198 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004199
Steve Naroff30484702009-12-06 21:14:13 +00004200 Constructor += "(void *fp, "; // Invoke function pointer.
4201 Constructor += "struct " + Desc; // Descriptor pointer.
4202 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004203
Steve Naroff677ab3a2008-10-27 17:20:55 +00004204 if (BlockDeclRefs.size()) {
4205 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004206 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 E = BlockByCopyDecls.end(); I != E; ++I) {
4208 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004209 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004210 std::string ArgName = "_" + FieldName;
4211 // Handle nested closure invocation. For example:
4212 //
4213 // void (^myImportedBlock)(void);
4214 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004215 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004216 // void (^anotherBlock)(void);
4217 // anotherBlock = ^(void) {
4218 // myImportedBlock(); // import and invoke the closure
4219 // };
4220 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004221 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 S += "struct __block_impl *";
4223 Constructor += ", void *" + ArgName;
4224 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004225 QualType QT = (*I)->getType();
4226 if (HasLocalVariableExternalStorage(*I))
4227 QT = Context->getPointerType(QT);
4228 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4229 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004230 Constructor += ", " + ArgName;
4231 }
4232 S += FieldName + ";\n";
4233 }
4234 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004235 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004236 E = BlockByRefDecls.end(); I != E; ++I) {
4237 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004238 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004239 std::string ArgName = "_" + FieldName;
4240 // Handle nested closure invocation. For example:
4241 //
4242 // void (^myImportedBlock)(void);
4243 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004244 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245 // void (^anotherBlock)(void);
4246 // anotherBlock = ^(void) {
4247 // myImportedBlock(); // import and invoke the closure
4248 // };
4249 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004250 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 S += "struct __block_impl *";
4252 Constructor += ", void *" + ArgName;
4253 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004254 std::string TypeString;
4255 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004256 TypeString += " *";
4257 FieldName = TypeString + FieldName;
4258 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 Constructor += ", " + ArgName;
4260 }
4261 S += FieldName + "; // by ref\n";
4262 }
4263 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004264 Constructor += ", int flags=0)";
4265 // Initialize all "by copy" arguments.
4266 bool firsTime = true;
4267 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4268 E = BlockByCopyDecls.end(); I != E; ++I) {
4269 std::string Name = (*I)->getNameAsString();
4270 if (firsTime) {
4271 Constructor += " : ";
4272 firsTime = false;
4273 }
4274 else
4275 Constructor += ", ";
4276 if (isTopLevelBlockPointerType((*I)->getType()))
4277 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4278 else
4279 Constructor += Name + "(_" + Name + ")";
4280 }
4281 // Initialize all "by ref" arguments.
4282 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4283 E = BlockByRefDecls.end(); I != E; ++I) {
4284 std::string Name = (*I)->getNameAsString();
4285 if (firsTime) {
4286 Constructor += " : ";
4287 firsTime = false;
4288 }
4289 else
4290 Constructor += ", ";
4291 if (isTopLevelBlockPointerType((*I)->getType()))
4292 Constructor += Name + "((struct __block_impl *)_"
4293 + Name + "->__forwarding)";
4294 else
4295 Constructor += Name + "(_" + Name + "->__forwarding)";
4296 }
4297
4298 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004299 if (GlobalVarDecl)
4300 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4301 else
4302 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004303 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004304
Steve Naroff30484702009-12-06 21:14:13 +00004305 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004306 } else {
4307 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004308 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004309 if (GlobalVarDecl)
4310 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4311 else
4312 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004313 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4314 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004315 }
4316 Constructor += " ";
4317 Constructor += "}\n";
4318 S += Constructor;
4319 S += "};\n";
4320 return S;
4321}
4322
Steve Naroff30484702009-12-06 21:14:13 +00004323std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4324 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004325 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004326 unsigned hasCopy) {
4327 std::string S = "\nstatic struct " + DescTag;
4328
4329 S += " {\n unsigned long reserved;\n";
4330 S += " unsigned long Block_size;\n";
4331 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004332 S += " void (*copy)(struct ";
4333 S += ImplTag; S += "*, struct ";
4334 S += ImplTag; S += "*);\n";
4335
4336 S += " void (*dispose)(struct ";
4337 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004338 }
4339 S += "} ";
4340
4341 S += DescTag + "_DATA = { 0, sizeof(struct ";
4342 S += ImplTag + ")";
4343 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004344 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4345 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004346 }
4347 S += "};\n";
4348 return S;
4349}
4350
Steve Naroff677ab3a2008-10-27 17:20:55 +00004351void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004352 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004353 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004354 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004355 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004356 bool RewriteSC = (GlobalVarDecl &&
4357 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004358 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004359 GlobalVarDecl->getType().getCVRQualifiers());
4360 if (RewriteSC) {
4361 std::string SC(" void __");
4362 SC += GlobalVarDecl->getNameAsString();
4363 SC += "() {}";
4364 InsertText(FunLocStart, SC);
4365 }
4366
Steve Naroff677ab3a2008-10-27 17:20:55 +00004367 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004368 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4369 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004370 // Need to copy-in the inner copied-in variables not actually used in this
4371 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004372 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4373 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4374 ValueDecl *VD = Exp->getDecl();
4375 BlockDeclRefs.push_back(Exp);
4376 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4377 BlockByCopyDeclsPtrSet.insert(VD);
4378 BlockByCopyDecls.push_back(VD);
4379 }
4380 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4381 BlockByRefDeclsPtrSet.insert(VD);
4382 BlockByRefDecls.push_back(VD);
4383 }
4384 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004385
Daniel Dunbar56df9772010-08-17 22:39:59 +00004386 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4387 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004388
Steve Naroff30484702009-12-06 21:14:13 +00004389 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004390
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004391 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004392
Steve Naroff30484702009-12-06 21:14:13 +00004393 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004394
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004395 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004396
4397 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004398 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004399 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004400 }
Steve Naroff30484702009-12-06 21:14:13 +00004401 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4402 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004403 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004404
Steve Naroff677ab3a2008-10-27 17:20:55 +00004405 BlockDeclRefs.clear();
4406 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004407 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004408 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004409 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004410 ImportedBlockDecls.clear();
4411 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004412 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004413 // Must insert any 'const/volatile/static here. Since it has been
4414 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004415 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004416 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004417 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004418 if (GlobalVarDecl->getType().isConstQualified())
4419 SC += "const ";
4420 if (GlobalVarDecl->getType().isVolatileQualified())
4421 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004422 if (GlobalVarDecl->getType().isRestrictQualified())
4423 SC += "restrict ";
4424 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004425 }
4426
Steve Naroff677ab3a2008-10-27 17:20:55 +00004427 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004428 InnerDeclRefsCount.clear();
4429 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004430 RewrittenBlockExprs.clear();
4431}
4432
4433void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4434 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004435 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004436
Steve Naroff677ab3a2008-10-27 17:20:55 +00004437 SynthesizeBlockLiterals(FunLocStart, FuncName);
4438}
4439
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004440static void BuildUniqueMethodName(std::string &Name,
4441 ObjCMethodDecl *MD) {
4442 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004443 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004444 Name += "__" + MD->getSelector().getAsString();
4445 // Convert colons to underscores.
4446 std::string::size_type loc = 0;
4447 while ((loc = Name.find(":", loc)) != std::string::npos)
4448 Name.replace(loc, 1, "_");
4449}
4450
Steve Naroff677ab3a2008-10-27 17:20:55 +00004451void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004452 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4453 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004454 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004455 std::string FuncName;
4456 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004457 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458}
4459
4460void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4461 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4462 CI != E; ++CI)
4463 if (*CI) {
4464 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4465 GetBlockDeclRefExprs(CBE->getBody());
4466 else
4467 GetBlockDeclRefExprs(*CI);
4468 }
4469 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004470 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004471 // FIXME: Handle enums.
4472 if (!isa<FunctionDecl>(CDRE->getDecl()))
4473 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004474 }
4475 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4476 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4477 BlockDeclRefExpr *BDRE =
4478 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4479 DRE->getLocation(), false);
4480 BlockDeclRefs.push_back(BDRE);
4481 }
4482
Steve Naroff677ab3a2008-10-27 17:20:55 +00004483 return;
4484}
4485
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004486void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4487 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004488 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004489 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4490 CI != E; ++CI)
4491 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004492 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4493 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004494 GetInnerBlockDeclRefExprs(CBE->getBody(),
4495 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004496 InnerContexts);
4497 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004498 else
4499 GetInnerBlockDeclRefExprs(*CI,
4500 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004501 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004502
4503 }
4504 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004505 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004506 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004507 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004508 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004509 }
4510 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4511 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4512 if (Var->isFunctionOrMethodVarDecl())
4513 ImportedLocalExternalDecls.insert(Var);
4514 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004515
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004516 return;
4517}
4518
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004519/// convertFunctionTypeOfBlocks - This routine converts a function type
4520/// whose result type may be a block pointer or whose argument type(s)
4521/// might be block pointers to an equivalent funtion type replacing
4522/// all block pointers to function pointers.
4523QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4524 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4525 // FTP will be null for closures that don't take arguments.
4526 // Generate a funky cast.
4527 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004528 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004529 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004530
4531 if (FTP) {
4532 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4533 E = FTP->arg_type_end(); I && (I != E); ++I) {
4534 QualType t = *I;
4535 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004536 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004537 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004538 ArgTypes.push_back(t);
4539 }
4540 }
4541 QualType FuncType;
4542 // FIXME. Does this work if block takes no argument but has a return type
4543 // which is of block type?
4544 if (HasBlockType)
4545 FuncType = Context->getFunctionType(Res,
4546 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4547 false, false, 0, 0, FunctionType::ExtInfo());
4548 else FuncType = QualType(FT, 0);
4549 return FuncType;
4550}
4551
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004552Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004553 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004554 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004555
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004556 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004557 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004558 } else if (const BlockDeclRefExpr *CDRE =
4559 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004560 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004561 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004562 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004563 }
4564 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4565 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4566 }
4567 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4568 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4569 else if (const ConditionalOperator *CEXPR =
4570 dyn_cast<ConditionalOperator>(BlockExp)) {
4571 Expr *LHSExp = CEXPR->getLHS();
4572 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4573 Expr *RHSExp = CEXPR->getRHS();
4574 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4575 Expr *CONDExp = CEXPR->getCond();
4576 ConditionalOperator *CondExpr =
4577 new (Context) ConditionalOperator(CONDExp,
4578 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004579 SourceLocation(), cast<Expr>(RHSStmt),
4580 (Expr*)0,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004581 Exp->getType());
4582 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004583 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4584 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004585 } else {
4586 assert(1 && "RewriteBlockClass: Bad type");
4587 }
4588 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004589 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004590 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004591 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004592 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004593
Abramo Bagnara6150c882010-05-11 21:36:43 +00004594 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004595 SourceLocation(),
4596 &Context->Idents.get("__block_impl"));
4597 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004598
Steve Naroff350b6652008-10-30 10:07:53 +00004599 // Generate a funky cast.
4600 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004601
Steve Naroff350b6652008-10-30 10:07:53 +00004602 // Push the block argument type.
4603 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004604 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004605 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004606 E = FTP->arg_type_end(); I && (I != E); ++I) {
4607 QualType t = *I;
4608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004609 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004610 ArgTypes.push_back(t);
4611 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004612 }
Steve Naroff350b6652008-10-30 10:07:53 +00004613 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004614 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004615 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4616 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004617 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004618
Steve Naroff350b6652008-10-30 10:07:53 +00004619 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004620
John McCall97513962010-01-15 18:39:57 +00004621 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalle3027922010-08-25 11:45:40 +00004622 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00004623 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004624 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004625 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4626 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004627 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004628
Douglas Gregor91f84212008-12-11 16:49:14 +00004629 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004630 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004631 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004632 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4633 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004634
John McCall97513962010-01-15 18:39:57 +00004635 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalle3027922010-08-25 11:45:40 +00004636 CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004637 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004638
Steve Naroff350b6652008-10-30 10:07:53 +00004639 llvm::SmallVector<Expr*, 8> BlkExprs;
4640 // Add the implicit argument.
4641 BlkExprs.push_back(BlkCast);
4642 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004643 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004644 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004645 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004646 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004647 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4648 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004649 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004650 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004651}
4652
Steve Naroffd9803712009-04-29 16:37:50 +00004653// We need to return the rewritten expression to handle cases where the
4654// BlockDeclRefExpr is embedded in another expression being rewritten.
4655// For example:
4656//
4657// int main() {
4658// __block Foo *f;
4659// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004660//
Steve Naroffd9803712009-04-29 16:37:50 +00004661// void (^myblock)() = ^() {
4662// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4663// i = 77;
4664// };
4665//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004666Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004667 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004668 // for each DeclRefExp where BYREFVAR is name of the variable.
4669 ValueDecl *VD;
4670 bool isArrow = true;
4671 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4672 VD = BDRE->getDecl();
4673 else {
4674 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4675 isArrow = false;
4676 }
4677
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004678 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4679 &Context->Idents.get("__forwarding"),
4680 Context->VoidPtrTy, 0,
4681 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004682 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4683 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004684 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004685
Daniel Dunbar56df9772010-08-17 22:39:59 +00004686 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004687 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4688 &Context->Idents.get(Name),
4689 Context->VoidPtrTy, 0,
4690 /*BitWidth=*/0, /*Mutable=*/true);
4691 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004692 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004693
4694
4695
Steve Narofff26a1d42009-02-02 17:19:26 +00004696 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004697 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4698 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004699 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004700 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004701}
4702
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004703// Rewrites the imported local variable V with external storage
4704// (static, extern, etc.) as *V
4705//
4706Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4707 ValueDecl *VD = DRE->getDecl();
4708 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4709 if (!ImportedLocalExternalDecls.count(Var))
4710 return DRE;
John McCalle3027922010-08-25 11:45:40 +00004711 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004712 DRE->getType(), DRE->getLocation());
4713 // Need parens to enforce precedence.
4714 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4715 Exp);
4716 ReplaceStmt(DRE, PE);
4717 return PE;
4718}
4719
Steve Naroffc989a7b2008-11-03 23:29:32 +00004720void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4721 SourceLocation LocStart = CE->getLParenLoc();
4722 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004723
4724 // Need to avoid trying to rewrite synthesized casts.
4725 if (LocStart.isInvalid())
4726 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004727 // Need to avoid trying to rewrite casts contained in macros.
4728 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4729 return;
Mike Stump11289f42009-09-09 15:08:12 +00004730
Steve Naroff677ab3a2008-10-27 17:20:55 +00004731 const char *startBuf = SM->getCharacterData(LocStart);
4732 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004733 QualType QT = CE->getType();
4734 const Type* TypePtr = QT->getAs<Type>();
4735 if (isa<TypeOfExprType>(TypePtr)) {
4736 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4737 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4738 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004739 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004740 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004741 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004742 return;
4743 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004744 // advance the location to startArgList.
4745 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004746
Steve Naroff677ab3a2008-10-27 17:20:55 +00004747 while (*argPtr++ && (argPtr < endBuf)) {
4748 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004749 case '^':
4750 // Replace the '^' with '*'.
4751 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004752 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004753 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004754 }
4755 }
4756 return;
4757}
4758
4759void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4760 SourceLocation DeclLoc = FD->getLocation();
4761 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004762
Steve Naroff677ab3a2008-10-27 17:20:55 +00004763 // We have 1 or more arguments that have closure pointers.
4764 const char *startBuf = SM->getCharacterData(DeclLoc);
4765 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004766
Steve Naroff677ab3a2008-10-27 17:20:55 +00004767 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004768
Steve Naroff677ab3a2008-10-27 17:20:55 +00004769 parenCount++;
4770 // advance the location to startArgList.
4771 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4772 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004773
Steve Naroff677ab3a2008-10-27 17:20:55 +00004774 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004775
Steve Naroff677ab3a2008-10-27 17:20:55 +00004776 while (*argPtr++ && parenCount) {
4777 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004778 case '^':
4779 // Replace the '^' with '*'.
4780 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004781 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004782 break;
4783 case '(':
4784 parenCount++;
4785 break;
4786 case ')':
4787 parenCount--;
4788 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004789 }
4790 }
4791 return;
4792}
4793
4794bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004795 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004796 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004797 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004798 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004799 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004800 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004801 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004802 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004803 }
4804 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004805 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004806 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004807 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004808 return true;
4809 }
4810 return false;
4811}
4812
Ted Kremenek5a201952009-02-07 01:47:29 +00004813void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4814 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004815 const char *argPtr = strchr(Name, '(');
4816 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004817
Steve Naroff677ab3a2008-10-27 17:20:55 +00004818 LParen = argPtr; // output the start.
4819 argPtr++; // skip past the left paren.
4820 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Steve Naroff677ab3a2008-10-27 17:20:55 +00004822 while (*argPtr && parenCount) {
4823 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004824 case '(': parenCount++; break;
4825 case ')': parenCount--; break;
4826 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004827 }
4828 if (parenCount) argPtr++;
4829 }
4830 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4831 RParen = argPtr; // output the end
4832}
4833
4834void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4835 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4836 RewriteBlockPointerFunctionArgs(FD);
4837 return;
Mike Stump11289f42009-09-09 15:08:12 +00004838 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004839 // Handle Variables and Typedefs.
4840 SourceLocation DeclLoc = ND->getLocation();
4841 QualType DeclT;
4842 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4843 DeclT = VD->getType();
4844 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4845 DeclT = TDD->getUnderlyingType();
4846 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4847 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004848 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004849 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004850
Steve Naroff677ab3a2008-10-27 17:20:55 +00004851 const char *startBuf = SM->getCharacterData(DeclLoc);
4852 const char *endBuf = startBuf;
4853 // scan backward (from the decl location) for the end of the previous decl.
4854 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4855 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004856
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 // *startBuf != '^' if we are dealing with a pointer to function that
4858 // may take block argument types (which will be handled below).
4859 if (*startBuf == '^') {
4860 // Replace the '^' with '*', computing a negative offset.
4861 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004862 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004863 }
4864 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4865 // Replace the '^' with '*' for arguments.
4866 DeclLoc = ND->getLocation();
4867 startBuf = SM->getCharacterData(DeclLoc);
4868 const char *argListBegin, *argListEnd;
4869 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4870 while (argListBegin < argListEnd) {
4871 if (*argListBegin == '^') {
4872 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004873 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004874 }
4875 argListBegin++;
4876 }
4877 }
4878 return;
4879}
4880
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004881
4882/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4883/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4884/// struct Block_byref_id_object *src) {
4885/// _Block_object_assign (&_dest->object, _src->object,
4886/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4887/// [|BLOCK_FIELD_IS_WEAK]) // object
4888/// _Block_object_assign(&_dest->object, _src->object,
4889/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4890/// [|BLOCK_FIELD_IS_WEAK]) // block
4891/// }
4892/// And:
4893/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4894/// _Block_object_dispose(_src->object,
4895/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4896/// [|BLOCK_FIELD_IS_WEAK]) // object
4897/// _Block_object_dispose(_src->object,
4898/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4899/// [|BLOCK_FIELD_IS_WEAK]) // block
4900/// }
4901
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004902std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4903 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004904 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004905 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004906 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004907 CopyDestroyCache.insert(flag);
4908 S = "static void __Block_byref_id_object_copy_";
4909 S += utostr(flag);
4910 S += "(void *dst, void *src) {\n";
4911
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004912 // offset into the object pointer is computed as:
4913 // void * + void* + int + int + void* + void *
4914 unsigned IntSize =
4915 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4916 unsigned VoidPtrSize =
4917 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4918
4919 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4920 S += " _Block_object_assign((char*)dst + ";
4921 S += utostr(offset);
4922 S += ", *(void * *) ((char*)src + ";
4923 S += utostr(offset);
4924 S += "), ";
4925 S += utostr(flag);
4926 S += ");\n}\n";
4927
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004928 S += "static void __Block_byref_id_object_dispose_";
4929 S += utostr(flag);
4930 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004931 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4932 S += utostr(offset);
4933 S += "), ";
4934 S += utostr(flag);
4935 S += ");\n}\n";
4936 return S;
4937}
4938
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004939/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4940/// the declaration into:
4941/// struct __Block_byref_ND {
4942/// void *__isa; // NULL for everything except __weak pointers
4943/// struct __Block_byref_ND *__forwarding;
4944/// int32_t __flags;
4945/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004946/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4947/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004948/// typex ND;
4949/// };
4950///
4951/// It then replaces declaration of ND variable with:
4952/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4953/// __size=sizeof(struct __Block_byref_ND),
4954/// ND=initializer-if-any};
4955///
4956///
4957void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004958 // Insert declaration for the function in which block literal is
4959 // used.
4960 if (CurFunctionDeclToDeclareForBlock)
4961 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004962 int flag = 0;
4963 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004964 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004965 if (DeclLoc.isInvalid())
4966 // If type location is missing, it is because of missing type (a warning).
4967 // Use variable's location which is good for this case.
4968 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004969 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004970 SourceLocation X = ND->getLocEnd();
4971 X = SM->getInstantiationLoc(X);
4972 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004973 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004974 std::string ByrefType;
4975 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004976 ByrefType += " {\n";
4977 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004978 RewriteByRefString(ByrefType, Name, ND);
4979 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004980 ByrefType += " int __flags;\n";
4981 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004982 // Add void *__Block_byref_id_object_copy;
4983 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004984 QualType Ty = ND->getType();
4985 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4986 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004987 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4988 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004989 }
4990
4991 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004992 ByrefType += " " + Name + ";\n";
4993 ByrefType += "};\n";
4994 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004995 SourceLocation FunLocStart;
4996 if (CurFunctionDef)
4997 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4998 else {
4999 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5000 FunLocStart = CurMethodDef->getLocStart();
5001 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005002 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005003 if (Ty.isObjCGCWeak()) {
5004 flag |= BLOCK_FIELD_IS_WEAK;
5005 isa = 1;
5006 }
5007
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005008 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005009 flag = BLOCK_BYREF_CALLER;
5010 QualType Ty = ND->getType();
5011 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5012 if (Ty->isBlockPointerType())
5013 flag |= BLOCK_FIELD_IS_BLOCK;
5014 else
5015 flag |= BLOCK_FIELD_IS_OBJECT;
5016 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005017 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005018 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005019 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005020
5021 // struct __Block_byref_ND ND =
5022 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5023 // initializer-if-any};
5024 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005025 unsigned flags = 0;
5026 if (HasCopyAndDispose)
5027 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005028 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005029 ByrefType.clear();
5030 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005031 std::string ForwardingCastType("(");
5032 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005033 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005034 ByrefType += " " + Name + " = {(void*)";
5035 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005036 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005037 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005038 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005039 ByrefType += "sizeof(";
5040 RewriteByRefString(ByrefType, Name, ND);
5041 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005042 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005043 ByrefType += ", __Block_byref_id_object_copy_";
5044 ByrefType += utostr(flag);
5045 ByrefType += ", __Block_byref_id_object_dispose_";
5046 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005047 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005048 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005049 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005050 }
5051 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005052 SourceLocation startLoc;
5053 Expr *E = ND->getInit();
5054 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5055 startLoc = ECE->getLParenLoc();
5056 else
5057 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005058 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005059 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005060 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005061 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005062 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005063 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005064 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005065 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005066 ByrefType += "sizeof(";
5067 RewriteByRefString(ByrefType, Name, ND);
5068 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005069 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005070 ByrefType += "__Block_byref_id_object_copy_";
5071 ByrefType += utostr(flag);
5072 ByrefType += ", __Block_byref_id_object_dispose_";
5073 ByrefType += utostr(flag);
5074 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005075 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005076 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005077
5078 // Complete the newly synthesized compound expression by inserting a right
5079 // curly brace before the end of the declaration.
5080 // FIXME: This approach avoids rewriting the initializer expression. It
5081 // also assumes there is only one declarator. For example, the following
5082 // isn't currently supported by this routine (in general):
5083 //
5084 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5085 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005086 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5087 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005088 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5089 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005090 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005091
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005092 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005093 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005094 return;
5095}
5096
Mike Stump11289f42009-09-09 15:08:12 +00005097void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005098 // Add initializers for any closure decl refs.
5099 GetBlockDeclRefExprs(Exp->getBody());
5100 if (BlockDeclRefs.size()) {
5101 // Unique all "by copy" declarations.
5102 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005103 if (!BlockDeclRefs[i]->isByRef()) {
5104 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5105 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5106 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5107 }
5108 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005109 // Unique all "by ref" declarations.
5110 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5111 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005112 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5113 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5114 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5115 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005116 }
5117 // Find any imported blocks...they will need special attention.
5118 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005119 if (BlockDeclRefs[i]->isByRef() ||
5120 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005121 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005122 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005123 }
5124}
5125
Daniel Dunbar56df9772010-08-17 22:39:59 +00005126FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005127 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005128 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005129 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005130 ID, FType, 0, SC_Extern,
5131 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005132}
5133
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005134Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5135 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 Blocks.push_back(Exp);
5137
5138 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005139
5140 // Add inner imported variables now used in current block.
5141 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005142 if (!InnerBlockDeclRefs.empty()) {
5143 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5144 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5145 ValueDecl *VD = Exp->getDecl();
5146 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005147 // We need to save the copied-in variables in nested
5148 // blocks because it is needed at the end for some of the API generations.
5149 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005150 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5151 BlockDeclRefs.push_back(Exp);
5152 BlockByCopyDeclsPtrSet.insert(VD);
5153 BlockByCopyDecls.push_back(VD);
5154 }
5155 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5156 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5157 BlockDeclRefs.push_back(Exp);
5158 BlockByRefDeclsPtrSet.insert(VD);
5159 BlockByRefDecls.push_back(VD);
5160 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005161 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005162 // Find any imported blocks...they will need special attention.
5163 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5164 if (InnerBlockDeclRefs[i]->isByRef() ||
5165 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5166 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5167 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005168 }
5169 InnerDeclRefsCount.push_back(countOfInnerDecls);
5170
Steve Narofff4b992a2008-10-28 20:29:00 +00005171 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005172
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005174 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005175 else if (CurMethodDef)
5176 BuildUniqueMethodName(FuncName, CurMethodDef);
5177 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005178 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005179
Steve Narofff4b992a2008-10-28 20:29:00 +00005180 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005181
Steve Narofff4b992a2008-10-28 20:29:00 +00005182 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5183 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005184
Steve Narofff4b992a2008-10-28 20:29:00 +00005185 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005186 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5187 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005188
5189 FunctionDecl *FD;
5190 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005191
Steve Narofff4b992a2008-10-28 20:29:00 +00005192 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005193 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek5a201952009-02-07 01:47:29 +00005194 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005195
Steve Narofff4b992a2008-10-28 20:29:00 +00005196 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005197
Steve Naroffe2514232008-10-29 21:23:59 +00005198 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005199 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek5a201952009-02-07 01:47:29 +00005200 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5201 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005202 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005203 CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005204 InitExprs.push_back(castExpr);
5205
Steve Naroff30484702009-12-06 21:14:13 +00005206 // Initialize the block descriptor.
5207 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005208
Steve Naroff30484702009-12-06 21:14:13 +00005209 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5210 &Context->Idents.get(DescData.c_str()),
5211 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005212 SC_Static, SC_None);
Steve Naroff30484702009-12-06 21:14:13 +00005213 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5214 new (Context) DeclRefExpr(NewVD,
5215 Context->VoidPtrTy, SourceLocation()),
John McCalle3027922010-08-25 11:45:40 +00005216 UO_AddrOf,
Steve Naroff30484702009-12-06 21:14:13 +00005217 Context->getPointerType(Context->VoidPtrTy),
5218 SourceLocation());
5219 InitExprs.push_back(DescRefExpr);
5220
Steve Narofff4b992a2008-10-28 20:29:00 +00005221 // Add initializers for any closure decl refs.
5222 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005223 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005224 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005225 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005226 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005227 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005228 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005229 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005230 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005231 if (HasLocalVariableExternalStorage(*I)) {
5232 QualType QT = (*I)->getType();
5233 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005234 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005235 SourceLocation());
5236 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005237 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005238 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005239 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005240 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005241 CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005242 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005243 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005244 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005245 if (HasLocalVariableExternalStorage(*I)) {
5246 QualType QT = (*I)->getType();
5247 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005248 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005249 SourceLocation());
5250 }
5251
Steve Narofff4b992a2008-10-28 20:29:00 +00005252 }
Mike Stump11289f42009-09-09 15:08:12 +00005253 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005254 }
5255 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005256 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005257 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005258 ValueDecl *ND = (*I);
5259 std::string Name(ND->getNameAsString());
5260 std::string RecName;
5261 RewriteByRefString(RecName, Name, ND);
5262 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5263 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005264 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005265 SourceLocation(), II);
5266 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5267 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5268
Daniel Dunbar56df9772010-08-17 22:39:59 +00005269 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005270 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005271 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005272 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005273 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005274 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005275 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005276 }
5277 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005278 if (ImportedBlockDecls.size()) {
5279 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5280 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005281 unsigned IntSize =
5282 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005283 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5284 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005285 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005286 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005287 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5288 FType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005289 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005290 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005291 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005292 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00005293 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 BlockDeclRefs.clear();
5295 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005296 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005297 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005298 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005299 ImportedBlockDecls.clear();
5300 return NewRep;
5301}
5302
5303//===----------------------------------------------------------------------===//
5304// Function Body / Expression rewriting
5305//===----------------------------------------------------------------------===//
5306
Steve Naroff4588d0f2008-12-04 16:24:46 +00005307// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5308// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5309// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5310// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5311// Since the rewriter isn't capable of rewriting rewritten code, it's important
5312// we get this right.
5313void RewriteObjC::CollectPropertySetters(Stmt *S) {
5314 // Perform a bottom up traversal of all children.
5315 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5316 CI != E; ++CI)
5317 if (*CI)
5318 CollectPropertySetters(*CI);
5319
5320 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5321 if (BinOp->isAssignmentOp()) {
5322 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5323 PropSetters[PRE] = BinOp;
5324 }
5325 }
5326}
5327
Steve Narofff4b992a2008-10-28 20:29:00 +00005328Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005329 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005330 isa<DoStmt>(S) || isa<ForStmt>(S))
5331 Stmts.push_back(S);
5332 else if (isa<ObjCForCollectionStmt>(S)) {
5333 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005334 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005335 }
Mike Stump11289f42009-09-09 15:08:12 +00005336
Steve Narofff4b992a2008-10-28 20:29:00 +00005337 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005338
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 // Perform a bottom up rewrite of all children.
5340 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5341 CI != E; ++CI)
5342 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005343 Stmt *newStmt;
5344 Stmt *S = (*CI);
5345 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5346 Expr *OldBase = IvarRefExpr->getBase();
5347 bool replaced = false;
5348 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5349 if (replaced) {
5350 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5351 ReplaceStmt(OldBase, IRE->getBase());
5352 else
5353 ReplaceStmt(S, newStmt);
5354 }
5355 }
5356 else
5357 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005358 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005359 *CI = newStmt;
5360 }
Mike Stump11289f42009-09-09 15:08:12 +00005361
Steve Narofff4b992a2008-10-28 20:29:00 +00005362 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005363 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005364 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5365 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005366 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005367 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005368 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005369 // Rewrite the block body in place.
5370 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005371 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005372 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005373 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005374 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005375
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005376 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5377
Steve Narofff4b992a2008-10-28 20:29:00 +00005378 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005379 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005380 return blockTranscribed;
5381 }
5382 // Handle specific things.
5383 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5384 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005385
Steve Naroff4588d0f2008-12-04 16:24:46 +00005386 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5387 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5388 if (BinOp) {
5389 // Because the rewriter doesn't allow us to rewrite rewritten code,
5390 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005391 DisableReplaceStmt = true;
5392 // Save the source range. Even if we disable the replacement, the
5393 // rewritten node will have been inserted into the tree. If the synthesized
5394 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005395 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005396 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5397 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005398 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005399 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005400 //
5401 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5402 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5403 // to see the original expression). Consider this example:
5404 //
5405 // Foo *obj1, *obj2;
5406 //
5407 // obj1.i = [obj2 rrrr];
5408 //
5409 // 'BinOp' for the previous expression looks like:
5410 //
5411 // (BinaryOperator 0x231ccf0 'int' '='
5412 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5413 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5414 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5415 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5416 //
5417 // 'newStmt' represents the rewritten message expression. For example:
5418 //
5419 // (CallExpr 0x231d300 'id':'struct objc_object *'
5420 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5421 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5422 // (CStyleCastExpr 0x231d220 'void *'
5423 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5424 //
5425 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5426 // can be used as the setter argument. ReplaceStmt() will still 'see'
5427 // the original RHS (since we haven't altered BinOp).
5428 //
Mike Stump11289f42009-09-09 15:08:12 +00005429 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005430 // node. As a result, we now leak the original AST nodes.
5431 //
Steve Naroff08628db2008-12-09 12:56:34 +00005432 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005433 } else {
5434 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005435 }
5436 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005437 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5438 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005439
Steve Narofff4b992a2008-10-28 20:29:00 +00005440 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5441 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005442
Steve Narofff4b992a2008-10-28 20:29:00 +00005443 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005444#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005445 // Before we rewrite it, put the original message expression in a comment.
5446 SourceLocation startLoc = MessExpr->getLocStart();
5447 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005448
Steve Narofff4b992a2008-10-28 20:29:00 +00005449 const char *startBuf = SM->getCharacterData(startLoc);
5450 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005451
Steve Narofff4b992a2008-10-28 20:29:00 +00005452 std::string messString;
5453 messString += "// ";
5454 messString.append(startBuf, endBuf-startBuf+1);
5455 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005456
5457 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005458 // InsertText(clang::SourceLocation, char const*, unsigned int).
5459 // InsertText(startLoc, messString.c_str(), messString.size());
5460 // Tried this, but it didn't work either...
5461 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005462#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005463 return RewriteMessageExpr(MessExpr);
5464 }
Mike Stump11289f42009-09-09 15:08:12 +00005465
Steve Narofff4b992a2008-10-28 20:29:00 +00005466 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5467 return RewriteObjCTryStmt(StmtTry);
5468
5469 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5470 return RewriteObjCSynchronizedStmt(StmtTry);
5471
5472 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5473 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005474
Steve Narofff4b992a2008-10-28 20:29:00 +00005475 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5476 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005477
5478 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005479 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005480 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005481 OrigStmtRange.getEnd());
5482 if (BreakStmt *StmtBreakStmt =
5483 dyn_cast<BreakStmt>(S))
5484 return RewriteBreakStmt(StmtBreakStmt);
5485 if (ContinueStmt *StmtContinueStmt =
5486 dyn_cast<ContinueStmt>(S))
5487 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005488
5489 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005490 // and cast exprs.
5491 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5492 // FIXME: What we're doing here is modifying the type-specifier that
5493 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005494 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005495 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5496 // the context of an ObjCForCollectionStmt. For example:
5497 // NSArray *someArray;
5498 // for (id <FooProtocol> index in someArray) ;
5499 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5500 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005501 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005502 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005503
Steve Narofff4b992a2008-10-28 20:29:00 +00005504 // Blocks rewrite rules.
5505 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5506 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005507 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005508 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005509 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005510 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005511 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005512 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005513 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005514 if (VD->hasAttr<BlocksAttr>()) {
5515 static unsigned uniqueByrefDeclCount = 0;
5516 assert(!BlockByRefDeclNo.count(ND) &&
5517 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5518 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005519 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005520 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005521 else
5522 RewriteTypeOfDecl(VD);
5523 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005524 }
5525 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005526 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005527 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005528 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005529 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5530 }
5531 }
5532 }
Mike Stump11289f42009-09-09 15:08:12 +00005533
Steve Narofff4b992a2008-10-28 20:29:00 +00005534 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5535 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005536
5537 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005538 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5539 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005540 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5541 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005542 && "Statement stack mismatch");
5543 Stmts.pop_back();
5544 }
5545 // Handle blocks rewriting.
5546 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5547 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005548 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005549 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005550 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5551 ValueDecl *VD = DRE->getDecl();
5552 if (VD->hasAttr<BlocksAttr>())
5553 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005554 if (HasLocalVariableExternalStorage(VD))
5555 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005556 }
5557
Steve Narofff4b992a2008-10-28 20:29:00 +00005558 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005559 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005560 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005561 ReplaceStmt(S, BlockCall);
5562 return BlockCall;
5563 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005564 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005565 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005566 RewriteCastExpr(CE);
5567 }
5568#if 0
5569 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005570 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5571 ICE->getSubExpr(),
5572 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005573 // Get the new text.
5574 std::string SStr;
5575 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005576 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005577 const std::string &Str = Buf.str();
5578
5579 printf("CAST = %s\n", &Str[0]);
5580 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5581 delete S;
5582 return Replacement;
5583 }
5584#endif
5585 // Return this stmt unmodified.
5586 return S;
5587}
5588
Steve Naroffe70a52a2009-12-05 15:55:59 +00005589void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5590 for (RecordDecl::field_iterator i = RD->field_begin(),
5591 e = RD->field_end(); i != e; ++i) {
5592 FieldDecl *FD = *i;
5593 if (isTopLevelBlockPointerType(FD->getType()))
5594 RewriteBlockPointerDecl(FD);
5595 if (FD->getType()->isObjCQualifiedIdType() ||
5596 FD->getType()->isObjCQualifiedInterfaceType())
5597 RewriteObjCQualifiedInterfaceTypes(FD);
5598 }
5599}
5600
Steve Narofff4b992a2008-10-28 20:29:00 +00005601/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5602/// main file of the input.
5603void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5604 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005605 if (FD->isOverloadedOperator())
5606 return;
Mike Stump11289f42009-09-09 15:08:12 +00005607
Steve Narofff4b992a2008-10-28 20:29:00 +00005608 // Since function prototypes don't have ParmDecl's, we check the function
5609 // prototype. This enables us to rewrite function declarations and
5610 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005611 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005612
Sebastian Redla7b98a72009-04-26 20:35:05 +00005613 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005614 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005615 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005616 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005617 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005618 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005619 Body =
5620 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5621 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005622 CurrentBody = 0;
5623 if (PropParentMap) {
5624 delete PropParentMap;
5625 PropParentMap = 0;
5626 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005627 // This synthesizes and inserts the block "impl" struct, invoke function,
5628 // and any copy/dispose helper functions.
5629 InsertBlockLiteralsWithinFunction(FD);
5630 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005631 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005632 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005633 return;
5634 }
5635 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005636 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005637 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005638 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005639 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005640 Body =
5641 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5642 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005643 CurrentBody = 0;
5644 if (PropParentMap) {
5645 delete PropParentMap;
5646 PropParentMap = 0;
5647 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005648 InsertBlockLiteralsWithinMethod(MD);
5649 CurMethodDef = 0;
5650 }
5651 }
5652 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5653 ClassImplementation.push_back(CI);
5654 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5655 CategoryImplementation.push_back(CI);
5656 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5657 RewriteForwardClassDecl(CD);
5658 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5659 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005660 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005661 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005662 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005663 CheckFunctionPointerDecl(VD->getType(), VD);
5664 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005665 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005666 RewriteCastExpr(CE);
5667 }
5668 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005669 } else if (VD->getType()->isRecordType()) {
5670 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5671 if (RD->isDefinition())
5672 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005673 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005674 if (VD->getInit()) {
5675 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005676 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005677 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005678 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005679 CurrentBody = 0;
5680 if (PropParentMap) {
5681 delete PropParentMap;
5682 PropParentMap = 0;
5683 }
Mike Stump11289f42009-09-09 15:08:12 +00005684 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005685 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005686 GlobalVarDecl = 0;
5687
5688 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005689 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005690 RewriteCastExpr(CE);
5691 }
5692 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005693 return;
5694 }
5695 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005696 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005697 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005698 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005699 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5700 return;
5701 }
5702 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005703 if (RD->isDefinition())
5704 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005705 return;
5706 }
5707 // Nothing yet.
5708}
5709
Chris Lattnercf169832009-03-28 04:11:33 +00005710void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005711 if (Diags.hasErrorOccurred())
5712 return;
Mike Stump11289f42009-09-09 15:08:12 +00005713
Steve Narofff4b992a2008-10-28 20:29:00 +00005714 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005715
Steve Naroffd9803712009-04-29 16:37:50 +00005716 // Here's a great place to add any extra declarations that may be needed.
5717 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005718 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005719 E = ProtocolExprDecls.end(); I != E; ++I)
5720 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5721
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005722 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005723 if (ClassImplementation.size() || CategoryImplementation.size())
5724 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005725
Steve Narofff4b992a2008-10-28 20:29:00 +00005726 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5727 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005728 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005729 Rewrite.getRewriteBufferFor(MainFileID)) {
5730 //printf("Changed:\n");
5731 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5732 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005733 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005734 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005735
Steve Naroffd9803712009-04-29 16:37:50 +00005736 if (ClassImplementation.size() || CategoryImplementation.size() ||
5737 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005738 // Rewrite Objective-c meta data*
5739 std::string ResultStr;
5740 SynthesizeMetaDataIntoBuffer(ResultStr);
5741 // Emit metadata.
5742 *OutFile << ResultStr;
5743 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005744 OutFile->flush();
5745}