blob: 980709149684f97d203559b7f85aaa08e7944ad3 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarc1b17292010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner3c799d72007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Steve Naroff1042ff32008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000311
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattner3c799d72007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000337
Steve Naroffd9803712009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(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
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000736static std::string getIvarAccessString(ObjCIvarDecl *OID) {
737 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000738 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 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000766
Steve Naroff003d00e2008-12-02 16:05:55 +0000767 if (!OID)
768 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000769 unsigned Attributes = PD->getPropertyAttributes();
770 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
771 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
772 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000773 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000774 if (GenGetProperty && !objcGetPropertyDefined) {
775 objcGetPropertyDefined = true;
776 // FIXME. Is this attribute correct in all cases?
777 Getr = "\nextern \"C\" __declspec(dllimport) "
778 "id objc_getProperty(id, SEL, long, bool);\n";
779 }
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000780 RewriteObjCMethodDecl(OID->getContainingInterface(),
781 PD->getGetterMethodDecl(), Getr);
Steve Naroff003d00e2008-12-02 16:05:55 +0000782 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, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000815 SynthesizeIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000816 Getr += ", 1)";
817 }
818 else
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000819 Getr += "return " + getIvarAccessString(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
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000836 RewriteObjCMethodDecl(OID->getContainingInterface(),
837 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000838 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000839 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000840 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000841 if (GenSetProperty) {
842 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000843 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000844 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000845 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000846 Setr += ", ";
847 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
848 Setr += "0, ";
849 else
850 Setr += "1, ";
851 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
852 Setr += "1)";
853 else
854 Setr += "0)";
855 }
856 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000857 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000858 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000859 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000860 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000861 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000862}
Chris Lattner16a0de42007-10-11 18:38:32 +0000863
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000864void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000865 // Get the start location and compute the semi location.
866 SourceLocation startLoc = ClassDecl->getLocation();
867 const char *startBuf = SM->getCharacterData(startLoc);
868 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattner3c799d72007-10-24 17:06:59 +0000870 // Translate to typedef's that forward reference structs with the same name
871 // as the class. As a convenience, we include the original declaration
872 // as a comment.
873 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000874 typedefString += "// @class ";
875 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
876 I != E; ++I) {
877 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
878 typedefString += ForwardDecl->getNameAsString();
879 if (I+1 != E)
880 typedefString += ", ";
881 else
882 typedefString += ";\n";
883 }
884
Chris Lattner9ee23b72009-02-20 18:04:31 +0000885 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
886 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000887 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000888 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000889 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000890 typedefString += "\n";
891 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000892 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000893 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000894 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000895 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000896 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Steve Naroff574440f2007-10-24 22:48:43 +0000899 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000900 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000901}
902
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000903void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000904 // When method is a synthesized one, such as a getter/setter there is
905 // nothing to rewrite.
906 if (Method->isSynthesized())
907 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000908 SourceLocation LocStart = Method->getLocStart();
909 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000910
Chris Lattner88ea93e2009-02-04 01:06:56 +0000911 if (SM->getInstantiationLineNumber(LocEnd) >
912 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000913 InsertText(LocStart, "#if 0\n");
914 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000915 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000916 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000917 }
918}
919
Mike Stump11289f42009-09-09 15:08:12 +0000920void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000921 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000922
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000923 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000924 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000925}
926
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000927void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000928 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000929
Steve Naroff5448cf62007-10-30 13:30:57 +0000930 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000931 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000932
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000933 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
934 E = CatDecl->prop_end(); I != E; ++I)
935 RewriteProperty(*I);
936
Mike Stump11289f42009-09-09 15:08:12 +0000937 for (ObjCCategoryDecl::instmeth_iterator
938 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000939 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000940 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000941 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000942 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000943 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000944 RewriteMethodDeclaration(*I);
945
Steve Naroff5448cf62007-10-30 13:30:57 +0000946 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000947 ReplaceText(CatDecl->getAtEndRange().getBegin(),
948 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000949}
950
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000951void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000952 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000953
Steve Narofff921385f2007-10-30 16:42:30 +0000954 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000955 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000956
957 for (ObjCProtocolDecl::instmeth_iterator
958 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000959 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000960 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000961 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000962 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000963 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000964 RewriteMethodDeclaration(*I);
965
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000966 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
967 E = PDecl->prop_end(); I != E; ++I)
968 RewriteProperty(*I);
969
Steve Narofff921385f2007-10-30 16:42:30 +0000970 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000971 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000972 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000973
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000974 // Must comment out @optional/@required
975 const char *startBuf = SM->getCharacterData(LocStart);
976 const char *endBuf = SM->getCharacterData(LocEnd);
977 for (const char *p = startBuf; p < endBuf; p++) {
978 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000979 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000980 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000982 }
983 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000984 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000985 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +0000986
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000987 }
988 }
Steve Narofff921385f2007-10-30 16:42:30 +0000989}
990
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000991void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000992 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000993 if (LocStart.isInvalid())
994 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000995 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000996 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000997}
998
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000999void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1000 const FunctionType *&FPRetType) {
1001 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001002 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001003 else if (T->isFunctionPointerType() ||
1004 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001005 // needs special handling, since pointer-to-functions have special
1006 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001007 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001008 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001009 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001010 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001011 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001012 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001013 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001014 ResultStr += FPRetType->getResultType().getAsString(
1015 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001016 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001017 }
1018 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001019 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001020}
1021
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001022void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1023 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001024 std::string &ResultStr) {
1025 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1026 const FunctionType *FPRetType = 0;
1027 ResultStr += "\nstatic ";
1028 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001029 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001030
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001031 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001032 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregorffca3a22009-01-09 17:18:27 +00001034 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001035 NameStr += "_I_";
1036 else
1037 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001038
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001039 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001040 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001041
1042 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001043 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001044 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001045 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001048 {
1049 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 int len = selString.size();
1051 for (int i = 0; i < len; i++)
1052 if (selString[i] == ':')
1053 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001054 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001055 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001056 // Remember this name for metadata emission
1057 MethodInternalNames[OMD] = NameStr;
1058 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001059
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 // Rewrite arguments
1061 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001062
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001064 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001065 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001067 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001068 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001069 ResultStr += "struct ";
1070 }
1071 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001072 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001073 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 }
1075 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001076 ResultStr += Context->getObjCClassType().getAsString(
1077 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001079 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001080 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001082
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001083 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001084 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1085 E = OMD->param_end(); PI != E; ++PI) {
1086 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001088 if (PDecl->getType()->isObjCQualifiedIdType()) {
1089 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001090 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001091 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001093 QualType QT = PDecl->getType();
1094 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1095 if (convertBlockPointerToFunctionPointer(QT))
1096 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1097 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001098 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001099 ResultStr += Name;
1100 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001101 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001102 if (OMD->isVariadic())
1103 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001104 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001105
Steve Naroffb067bbd2008-07-16 14:40:40 +00001106 if (FPRetType) {
1107 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001108
Steve Naroffb067bbd2008-07-16 14:40:40 +00001109 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001110 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001111 ResultStr += "(";
1112 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1113 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001114 std::string ParamStr = FT->getArgType(i).getAsString(
1115 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001116 ResultStr += ParamStr;
1117 }
1118 if (FT->isVariadic()) {
1119 if (FT->getNumArgs()) ResultStr += ", ";
1120 ResultStr += "...";
1121 }
1122 ResultStr += ")";
1123 } else {
1124 ResultStr += "()";
1125 }
1126 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001127}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001128void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001129 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1130 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001131
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001132 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001133
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001134 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001135 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1136 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001137 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001138 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001139 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001140 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001141 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001142 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001143
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001144 const char *startBuf = SM->getCharacterData(LocStart);
1145 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001146 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001149 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001150 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1151 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001152 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001153 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001154 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001155 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001156 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001157 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001158
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001159 const char *startBuf = SM->getCharacterData(LocStart);
1160 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001161 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001162 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001163 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001164 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001165 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001166 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001167 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001168 }
1169
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001170 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001171}
1172
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001173void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001174 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001175 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001176 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001177 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001178 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001179 ResultStr += "\n";
1180 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001181 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001182 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001183 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001184 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001185 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001186 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001188 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001189 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001190
1191 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001192 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001193 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001194 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001195 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001196 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001197 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001198 for (ObjCInterfaceDecl::classmeth_iterator
1199 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001200 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001201 RewriteMethodDeclaration(*I);
1202
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001203 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001204 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1205 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001206}
1207
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001208Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001209 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001210 ObjCMethodDecl *OMD = 0;
1211 QualType Ty;
1212 Selector Sel;
1213 Stmt *Receiver;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001214 bool Super = false;
1215 QualType SuperTy;
1216 SourceLocation SuperLocation;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001217 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001218 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001219 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1220 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1221 OMD = PDecl->getSetterMethodDecl();
1222 Ty = PDecl->getType();
1223 Sel = PDecl->getSetterName();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001224 Super = PropRefExpr->isSuperReceiver();
1225 if (!Super)
1226 Receiver = PropRefExpr->getBase();
1227 else {
1228 SuperTy = PropRefExpr->getSuperType();
1229 SuperLocation = PropRefExpr->getSuperLocation();
1230 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001231 }
1232 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1233 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1234 OMD = ImplicitRefExpr->getSetterMethod();
1235 Sel = OMD->getSelector();
1236 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001237 Super = ImplicitRefExpr->isSuperReceiver();
1238 if (!Super)
1239 Receiver = ImplicitRefExpr->getBase();
1240 else {
1241 SuperTy = ImplicitRefExpr->getSuperType();
1242 SuperLocation = ImplicitRefExpr->getSuperLocation();
1243 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001244 }
1245
1246 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001247 llvm::SmallVector<Expr *, 1> ExprVec;
1248 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001249
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001250 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1251 if (PropGetters[Exp])
1252 // This allows us to handle chain/nested property/implicit getters.
1253 Receiver = PropGetters[Exp];
1254
1255 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001256 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001257 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001258 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001259 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001260 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001261 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001262 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001263 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001264 &ExprVec[0], 1,
1265 /*FIXME:*/SourceLocation());
1266 else
1267 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001268 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001269 /*FIXME: */SourceLocation(),
1270 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001271 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001272 &ExprVec[0], 1,
1273 /*FIXME:*/SourceLocation());
Steve Naroff4588d0f2008-12-04 16:24:46 +00001274 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Steve Naroff4588d0f2008-12-04 16:24:46 +00001276 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001277 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001278 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001279 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1280 // to things that stay around.
1281 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001282 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001283}
1284
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001285Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1286 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001287 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001288 Stmt *Receiver;
1289 ObjCMethodDecl *OMD = 0;
1290 QualType Ty;
1291 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001292 bool Super = false;
1293 QualType SuperTy;
1294 SourceLocation SuperLocation;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001295 if (ObjCPropertyRefExpr *PropRefExpr =
1296 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1297 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1298 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001299 Ty = PDecl->getType();
1300 Sel = PDecl->getGetterName();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001301 Super = PropRefExpr->isSuperReceiver();
1302 if (!Super)
1303 Receiver = PropRefExpr->getBase();
1304 else {
1305 SuperTy = PropRefExpr->getSuperType();
1306 SuperLocation = PropRefExpr->getSuperLocation();
1307 }
Steve Naroff1042ff32008-12-08 16:43:47 +00001308 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001309 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1310 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1311 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001312 Sel = OMD->getSelector();
1313 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001314 Super = ImplicitRefExpr->isSuperReceiver();
1315 if (!Super)
1316 Receiver = ImplicitRefExpr->getBase();
1317 else {
1318 SuperTy = ImplicitRefExpr->getSuperType();
1319 SuperLocation = ImplicitRefExpr->getSuperLocation();
1320 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001321 }
1322
1323 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1324
1325 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1326 if (PropGetters[Exp])
1327 // This allows us to handle chain/nested property/implicit getters.
1328 Receiver = PropGetters[Exp];
1329
1330 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001331 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001332 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001333 Ty.getNonReferenceType(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001334 /*FIXME?*/SourceLocation(),
1335 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001336 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001337 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001338 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001339 0, 0,
1340 /*FIXME:*/SourceLocation());
1341 else
1342 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001343 Ty.getNonReferenceType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001344 /*FIXME:*/SourceLocation(),
1345 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001346 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001347 0, 0,
1348 /*FIXME:*/SourceLocation());
Steve Narofff326f402008-12-03 00:56:33 +00001349
Steve Naroff22216db2008-12-04 23:50:32 +00001350 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001351
1352 if (!PropParentMap)
1353 PropParentMap = new ParentMap(CurrentBody);
1354
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001355 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1356 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1357 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001358 // We stash away the ReplacingStmt since actually doing the
1359 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001360 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001361 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1362 // to things that stay around.
1363 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001364 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001365 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001366 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001367 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001368 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1369 // to things that stay around.
1370 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001371 return ReplacingStmt;
1372 }
Steve Narofff326f402008-12-03 00:56:33 +00001373}
1374
Mike Stump11289f42009-09-09 15:08:12 +00001375Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001376 SourceLocation OrigStart,
1377 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001378 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001379 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001380 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001381 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001382 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001383 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001384 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001385 // lookup which class implements the instance variable.
1386 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001387 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001388 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001389 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001390
Steve Naroffb1c02372008-05-08 17:52:16 +00001391 // Synthesize an explicit cast to gain access to the ivar.
1392 std::string RecName = clsDeclared->getIdentifier()->getName();
1393 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001394 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001395 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001396 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001397 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1398 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001399 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001400 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001401 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001402 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001403 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1404 IV->getBase()->getLocEnd(),
1405 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001406 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001407 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001408 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001409 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1410 IV->getLocation(),
1411 D->getType());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001412 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001413 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001414 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001415 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001416 // Cannot delete IV->getBase(), since PE points to it.
1417 // Replace the old base with the cast. This is important when doing
1418 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001419 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001420 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001421 }
Steve Naroff24840f62008-04-18 21:55:08 +00001422 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001423 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001424
Steve Naroff29ce4e52008-05-06 23:20:07 +00001425 // Explicit ivar refs need to have a cast inserted.
1426 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001427 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001428 ObjCInterfaceType *iFaceDecl =
1429 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001430 // lookup which class implements the instance variable.
1431 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001432 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001433 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001434 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001435
Steve Naroff29ce4e52008-05-06 23:20:07 +00001436 // Synthesize an explicit cast to gain access to the ivar.
1437 std::string RecName = clsDeclared->getIdentifier()->getName();
1438 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001439 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001440 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001441 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001442 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1443 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001444 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalle3027922010-08-25 11:45:40 +00001445 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001446 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001447 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001448 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001449 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001450 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001451 // Cannot delete IV->getBase(), since PE points to it.
1452 // Replace the old base with the cast. This is important when doing
1453 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001454 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001455 return IV;
1456 }
Steve Naroff05caa482007-11-15 11:33:00 +00001457 }
Steve Naroff24840f62008-04-18 21:55:08 +00001458 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001459}
1460
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001461Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1462 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1463 CI != E; ++CI) {
1464 if (*CI) {
1465 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1466 if (newStmt)
1467 *CI = newStmt;
1468 }
1469 }
1470 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1471 SourceRange OrigStmtRange = S->getSourceRange();
1472 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1473 replaced);
1474 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001475 }
1476 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1477 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1478 return newStmt;
1479 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001480 return S;
1481}
1482
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483/// SynthCountByEnumWithState - To print:
1484/// ((unsigned int (*)
1485/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001486/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001488/// "countByEnumeratingWithState:objects:count:"),
1489/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490/// (id *)items, (unsigned int)16)
1491///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001492void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001493 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1494 "id *, unsigned int))(void *)objc_msgSend)";
1495 buf += "\n\t\t";
1496 buf += "((id)l_collection,\n\t\t";
1497 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1498 buf += "\n\t\t";
1499 buf += "&enumState, "
1500 "(id *)items, (unsigned int)16)";
1501}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001502
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001503/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1504/// statement to exit to its outer synthesized loop.
1505///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001506Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001507 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1508 return S;
1509 // replace break with goto __break_label
1510 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001512 SourceLocation startLoc = S->getLocStart();
1513 buf = "goto __break_label_";
1514 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001515 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001516
1517 return 0;
1518}
1519
1520/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1521/// statement to continue with its inner synthesized loop.
1522///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001523Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001524 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1525 return S;
1526 // replace continue with goto __continue_label
1527 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001528
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001529 SourceLocation startLoc = S->getLocStart();
1530 buf = "goto __continue_label_";
1531 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001532 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001533
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534 return 0;
1535}
1536
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001537/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001538/// It rewrites:
1539/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001541/// Into:
1542/// {
Mike Stump11289f42009-09-09 15:08:12 +00001543/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001544/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001545/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001546/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001547/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001549/// if (limit) {
1550/// unsigned long startMutations = *enumState.mutationsPtr;
1551/// do {
1552/// unsigned long counter = 0;
1553/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001554/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001555/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001556/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001557/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001558/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001559/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001560/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001561/// objects:items count:16]);
1562/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001563/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001564/// }
1565/// else
1566/// elem = nil;
1567/// }
1568///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001569Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001570 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001571 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001572 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001573 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001574 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001575 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001576
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001578 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001579 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001580 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001581 std::string buf;
1582 buf = "\n{\n\t";
1583 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1584 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001585 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001586 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001587 if (ElementType->isObjCQualifiedIdType() ||
1588 ElementType->isObjCQualifiedInterfaceType())
1589 // Simply use 'id' for all qualified types.
1590 elementTypeAsString = "id";
1591 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001592 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001593 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001594 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001595 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001596 buf += elementName;
1597 buf += ";\n\t";
1598 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001599 else {
1600 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001601 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001602 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1603 if (VD->getType()->isObjCQualifiedIdType() ||
1604 VD->getType()->isObjCQualifiedInterfaceType())
1605 // Simply use 'id' for all qualified types.
1606 elementTypeAsString = "id";
1607 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001608 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001611 // struct __objcFastEnumerationState enumState = { 0 };
1612 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1613 // id items[16];
1614 buf += "id items[16];\n\t";
1615 // id l_collection = (id)
1616 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001617 // Find start location of 'collection' the hard way!
1618 const char *startCollectionBuf = startBuf;
1619 startCollectionBuf += 3; // skip 'for'
1620 startCollectionBuf = strchr(startCollectionBuf, '(');
1621 startCollectionBuf++; // skip '('
1622 // find 'in' and skip it.
1623 while (*startCollectionBuf != ' ' ||
1624 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1625 (*(startCollectionBuf+3) != ' ' &&
1626 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1627 startCollectionBuf++;
1628 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001629
1630 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001631 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001632 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001633 SourceLocation rightParenLoc = S->getRParenLoc();
1634 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1635 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001636 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001637
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001638 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1639 // objects:items count:16];
1640 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001641 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001642 // ((unsigned int (*)
1643 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001644 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001645 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001646 // "countByEnumeratingWithState:objects:count:"),
1647 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 // (id *)items, (unsigned int)16);
1649 buf += "unsigned long limit =\n\t\t";
1650 SynthCountByEnumWithState(buf);
1651 buf += ";\n\t";
1652 /// if (limit) {
1653 /// unsigned long startMutations = *enumState.mutationsPtr;
1654 /// do {
1655 /// unsigned long counter = 0;
1656 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001657 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001658 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001659 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001660 buf += "if (limit) {\n\t";
1661 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1662 buf += "do {\n\t\t";
1663 buf += "unsigned long counter = 0;\n\t\t";
1664 buf += "do {\n\t\t\t";
1665 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1666 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1667 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001668 buf += " = (";
1669 buf += elementTypeAsString;
1670 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001671 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001672 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001673
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001674 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001675 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001676 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001677 /// objects:items count:16]);
1678 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001679 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 /// }
1681 /// else
1682 /// elem = nil;
1683 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001684 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001685 buf = ";\n\t";
1686 buf += "__continue_label_";
1687 buf += utostr(ObjCBcLabelNo.back());
1688 buf += ": ;";
1689 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001690 buf += "} while (counter < limit);\n\t";
1691 buf += "} while (limit = ";
1692 SynthCountByEnumWithState(buf);
1693 buf += ");\n\t";
1694 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001695 buf += " = ((";
1696 buf += elementTypeAsString;
1697 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001698 buf += "__break_label_";
1699 buf += utostr(ObjCBcLabelNo.back());
1700 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001701 buf += "}\n\t";
1702 buf += "else\n\t\t";
1703 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001704 buf += " = ((";
1705 buf += elementTypeAsString;
1706 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001707 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001708
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001709 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001710 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001711 if (isa<CompoundStmt>(S->getBody())) {
1712 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001713 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001714 } else {
1715 /* Need to treat single statements specially. For example:
1716 *
1717 * for (A *a in b) if (stuff()) break;
1718 * for (A *a in b) xxxyy;
1719 *
1720 * The following code simply scans ahead to the semi to find the actual end.
1721 */
1722 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1723 const char *semiBuf = strchr(stmtBuf, ';');
1724 assert(semiBuf && "Can't find ';'");
1725 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001726 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001727 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001728 Stmts.pop_back();
1729 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001730 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001731}
1732
Mike Stump11289f42009-09-09 15:08:12 +00001733/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001734/// This routine rewrites @synchronized(expr) stmt;
1735/// into:
1736/// objc_sync_enter(expr);
1737/// @try stmt @finally { objc_sync_exit(expr); }
1738///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001739Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001740 // Get the start location and compute the semi location.
1741 SourceLocation startLoc = S->getLocStart();
1742 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001743
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001744 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001745
1746 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001747 buf = "objc_sync_enter((id)";
1748 const char *lparenBuf = startBuf;
1749 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001750 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001751 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1752 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001753 // been rewritten! (which implies the SourceLocation's are invalid).
1754 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001755 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001756 while (*endBuf != ')') endBuf--;
1757 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001758 buf = ");\n";
1759 // declare a new scope with two variables, _stack and _rethrow.
1760 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1761 buf += "int buf[18/*32-bit i386*/];\n";
1762 buf += "char *pointers[4];} _stack;\n";
1763 buf += "id volatile _rethrow = 0;\n";
1764 buf += "objc_exception_try_enter(&_stack);\n";
1765 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001766 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001767 startLoc = S->getSynchBody()->getLocEnd();
1768 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001769
Steve Naroffad7013b2008-08-19 13:04:19 +00001770 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001771 SourceLocation lastCurlyLoc = startLoc;
1772 buf = "}\nelse {\n";
1773 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001774 buf += "}\n";
1775 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001776 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001777
1778 std::string syncBuf;
1779 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001780 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00001781 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00001782 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001783 std::string syncExprBufS;
1784 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001785 syncExpr->printPretty(syncExprBuf, *Context, 0,
1786 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001787 syncBuf += syncExprBuf.str();
1788 syncBuf += ");";
1789
1790 buf += syncBuf;
1791 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001792 buf += "}\n";
1793 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001794
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001795 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001796
1797 bool hasReturns = false;
1798 HasReturnStmts(S->getSynchBody(), hasReturns);
1799 if (hasReturns)
1800 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1801
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001802 return 0;
1803}
1804
Steve Naroffec60b432009-12-05 21:43:12 +00001805void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1806{
Steve Naroff6d6da252008-12-05 17:03:39 +00001807 // Perform a bottom up traversal of all children.
1808 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1809 CI != E; ++CI)
1810 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001811 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001812
Steve Naroffec60b432009-12-05 21:43:12 +00001813 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001814 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001815 TryFinallyContainsReturnDiag);
1816 }
1817 return;
1818}
1819
Steve Naroffec60b432009-12-05 21:43:12 +00001820void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1821{
1822 // Perform a bottom up traversal of all children.
1823 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1824 CI != E; ++CI)
1825 if (*CI)
1826 HasReturnStmts(*CI, hasReturns);
1827
1828 if (isa<ReturnStmt>(S))
1829 hasReturns = true;
1830 return;
1831}
1832
1833void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1834 // Perform a bottom up traversal of all children.
1835 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1836 CI != E; ++CI)
1837 if (*CI) {
1838 RewriteTryReturnStmts(*CI);
1839 }
1840 if (isa<ReturnStmt>(S)) {
1841 SourceLocation startLoc = S->getLocStart();
1842 const char *startBuf = SM->getCharacterData(startLoc);
1843
1844 const char *semiBuf = strchr(startBuf, ';');
1845 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1846 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1847
1848 std::string buf;
1849 buf = "{ objc_exception_try_exit(&_stack); return";
1850
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001851 ReplaceText(startLoc, 6, buf);
1852 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001853 }
1854 return;
1855}
1856
1857void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1858 // Perform a bottom up traversal of all children.
1859 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1860 CI != E; ++CI)
1861 if (*CI) {
1862 RewriteSyncReturnStmts(*CI, syncExitBuf);
1863 }
1864 if (isa<ReturnStmt>(S)) {
1865 SourceLocation startLoc = S->getLocStart();
1866 const char *startBuf = SM->getCharacterData(startLoc);
1867
1868 const char *semiBuf = strchr(startBuf, ';');
1869 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1870 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1871
1872 std::string buf;
1873 buf = "{ objc_exception_try_exit(&_stack);";
1874 buf += syncExitBuf;
1875 buf += " return";
1876
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001877 ReplaceText(startLoc, 6, buf);
1878 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001879 }
1880 return;
1881}
1882
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001883Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001887
Steve Naroffbf478ec2007-11-07 04:08:17 +00001888 assert((*startBuf == '@') && "bogus @try location");
1889
1890 std::string buf;
1891 // declare a new scope with two variables, _stack and _rethrow.
1892 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1893 buf += "int buf[18/*32-bit i386*/];\n";
1894 buf += "char *pointers[4];} _stack;\n";
1895 buf += "id volatile _rethrow = 0;\n";
1896 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001897 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001899 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001900
Steve Naroffbf478ec2007-11-07 04:08:17 +00001901 startLoc = S->getTryBody()->getLocEnd();
1902 startBuf = SM->getCharacterData(startLoc);
1903
1904 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001905
Steve Naroffbf478ec2007-11-07 04:08:17 +00001906 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001907 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001908 startLoc = startLoc.getFileLocWithOffset(1);
1909 buf = " /* @catch begin */ else {\n";
1910 buf += " id _caught = objc_exception_extract(&_stack);\n";
1911 buf += " objc_exception_try_enter (&_stack);\n";
1912 buf += " if (_setjmp(_stack.buf))\n";
1913 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1914 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001915
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001916 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001917 } else { /* no catch list */
1918 buf = "}\nelse {\n";
1919 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1920 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001922 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001923 bool sawIdTypedCatch = false;
1924 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001925 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1926 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001927 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001928
Douglas Gregor96c79492010-04-23 22:50:49 +00001929 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001930 buf = "if ("; // we are generating code for the first catch clause
1931 else
1932 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001933 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001934 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroffbf478ec2007-11-07 04:08:17 +00001936 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001937
Steve Naroffbf478ec2007-11-07 04:08:17 +00001938 const char *lParenLoc = strchr(startBuf, '(');
1939
Douglas Gregor96c79492010-04-23 22:50:49 +00001940 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001941 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001942 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001943 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1944 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001945 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001946 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001947 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001948
Steve Naroffedb5bc62008-02-01 20:02:07 +00001949 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001950 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001951 } else if (catchDecl) {
1952 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001953 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001954 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001955 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001956 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001957 } else if (const ObjCObjectPointerType *Ptr =
1958 t->getAs<ObjCObjectPointerType>()) {
1959 // Should be a pointer to a class.
1960 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1961 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001962 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001963 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001964 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001965 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001966 }
1967 }
1968 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001969 lastCatchBody = Catch->getCatchBody();
1970 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001971 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1972 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1973 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1974 assert((*rParenBuf == ')') && "bogus @catch paren location");
1975 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001976
Mike Stump11289f42009-09-09 15:08:12 +00001977 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001978 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001979 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001980 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001981 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001982 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001983 }
1984 // Complete the catch list...
1985 if (lastCatchBody) {
1986 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001987 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1988 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001989
Steve Naroff4adbe312008-09-11 15:29:03 +00001990 // Insert the last (implicit) else clause *before* the right curly brace.
1991 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1992 buf = "} /* last catch end */\n";
1993 buf += "else {\n";
1994 buf += " _rethrow = _caught;\n";
1995 buf += " objc_exception_try_exit(&_stack);\n";
1996 buf += "} } /* @catch end */\n";
1997 if (!S->getFinallyStmt())
1998 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001999 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002000
Steve Naroffbf478ec2007-11-07 04:08:17 +00002001 // Set lastCurlyLoc
2002 lastCurlyLoc = lastCatchBody->getLocEnd();
2003 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002004 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002005 startLoc = finalStmt->getLocStart();
2006 startBuf = SM->getCharacterData(startLoc);
2007 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002008
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002009 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002010
Steve Naroffbf478ec2007-11-07 04:08:17 +00002011 Stmt *body = finalStmt->getFinallyBody();
2012 SourceLocation startLoc = body->getLocStart();
2013 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002014 assert(*SM->getCharacterData(startLoc) == '{' &&
2015 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002016 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002017 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002018
Steve Naroffbf478ec2007-11-07 04:08:17 +00002019 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002020 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002021 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002022 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002023
Steve Naroffbf478ec2007-11-07 04:08:17 +00002024 // Set lastCurlyLoc
2025 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002026
Steve Naroff6d6da252008-12-05 17:03:39 +00002027 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002028 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002029 } else { /* no finally clause - make sure we synthesize an implicit one */
2030 buf = "{ /* implicit finally clause */\n";
2031 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2032 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2033 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002034 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002035
2036 // Now check for any return/continue/go statements within the @try.
2037 // The implicit finally clause won't called if the @try contains any
2038 // jump statements.
2039 bool hasReturns = false;
2040 HasReturnStmts(S->getTryBody(), hasReturns);
2041 if (hasReturns)
2042 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002043 }
2044 // Now emit the final closing curly brace...
2045 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002046 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002047 return 0;
2048}
2049
Mike Stump11289f42009-09-09 15:08:12 +00002050// This can't be done with ReplaceStmt(S, ThrowExpr), since
2051// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002052// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002053Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002054 // Get the start location and compute the semi location.
2055 SourceLocation startLoc = S->getLocStart();
2056 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002057
Steve Naroffa733c7f2007-11-07 15:32:26 +00002058 assert((*startBuf == '@') && "bogus @throw location");
2059
2060 std::string buf;
2061 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002062 if (S->getThrowExpr())
2063 buf = "objc_exception_throw(";
2064 else // add an implicit argument
2065 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002066
Steve Naroff29788342008-07-25 15:41:30 +00002067 // handle "@ throw" correctly.
2068 const char *wBuf = strchr(startBuf, 'w');
2069 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002070 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002071
Steve Naroffa733c7f2007-11-07 15:32:26 +00002072 const char *semiBuf = strchr(startBuf, ';');
2073 assert((*semiBuf == ';') && "@throw: can't find ';'");
2074 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002075 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002076 return 0;
2077}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002078
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002079Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002080 // Create a new string expression.
2081 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002082 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002083 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002084 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2085 StrEncoding.length(), false,StrType,
2086 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002087 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner4431a1b2007-11-30 22:53:43 +00002089 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002090 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002091 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002092}
2093
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002094Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002095 if (!SelGetUidFunctionDecl)
2096 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002097 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2098 // Create a call to sel_registerName("selName").
2099 llvm::SmallVector<Expr*, 8> SelExprs;
2100 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002101 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002102 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002103 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002104 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002105 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2106 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002107 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002108 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002109 return SelExp;
2110}
2111
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002112CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002113 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2114 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002115 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002116 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002117
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002118 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002119 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002120
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002121 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002122 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002123 ImplicitCastExpr *ICE =
John McCalle3027922010-08-25 11:45:40 +00002124 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall2536c6d2010-08-25 10:28:54 +00002125 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002126
John McCall9dd450b2009-09-21 23:43:11 +00002127 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002128
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002129 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002130 new (Context) CallExpr(*Context, ICE, args, nargs,
2131 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002132 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002133}
2134
Steve Naroff50d42052007-11-01 13:24:47 +00002135static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2136 const char *&startRef, const char *&endRef) {
2137 while (startBuf < endBuf) {
2138 if (*startBuf == '<')
2139 startRef = startBuf; // mark the start.
2140 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002141 if (startRef && *startRef == '<') {
2142 endRef = startBuf; // mark the end.
2143 return true;
2144 }
2145 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002146 }
2147 startBuf++;
2148 }
2149 return false;
2150}
2151
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152static void scanToNextArgument(const char *&argRef) {
2153 int angle = 0;
2154 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2155 if (*argRef == '<')
2156 angle++;
2157 else if (*argRef == '>')
2158 angle--;
2159 argRef++;
2160 }
2161 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2162}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002163
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002164bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002165 if (T->isObjCQualifiedIdType())
2166 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002167 if (const PointerType *PT = T->getAs<PointerType>()) {
2168 if (PT->getPointeeType()->isObjCQualifiedIdType())
2169 return true;
2170 }
2171 if (T->isObjCObjectPointerType()) {
2172 T = T->getPointeeType();
2173 return T->isObjCQualifiedInterfaceType();
2174 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002175 if (T->isArrayType()) {
2176 QualType ElemTy = Context->getBaseElementType(T);
2177 return needToScanForQualifiers(ElemTy);
2178 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002179 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002180}
2181
Steve Naroff873bd842008-07-29 18:15:38 +00002182void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2183 QualType Type = E->getType();
2184 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002185 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002186
Steve Naroffdbfc6932008-11-19 21:15:47 +00002187 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2188 Loc = ECE->getLParenLoc();
2189 EndLoc = ECE->getRParenLoc();
2190 } else {
2191 Loc = E->getLocStart();
2192 EndLoc = E->getLocEnd();
2193 }
2194 // This will defend against trying to rewrite synthesized expressions.
2195 if (Loc.isInvalid() || EndLoc.isInvalid())
2196 return;
2197
Steve Naroff873bd842008-07-29 18:15:38 +00002198 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002199 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002200 const char *startRef = 0, *endRef = 0;
2201 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2202 // Get the locations of the startRef, endRef.
2203 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2204 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2205 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002206 InsertText(LessLoc, "/*");
2207 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002208 }
2209 }
2210}
2211
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002212void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002213 SourceLocation Loc;
2214 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002215 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002216 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2217 Loc = VD->getLocation();
2218 Type = VD->getType();
2219 }
2220 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2221 Loc = FD->getLocation();
2222 // Check for ObjC 'id' and class types that have been adorned with protocol
2223 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002224 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002225 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002226 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002227 if (!proto)
2228 return;
2229 Type = proto->getResultType();
2230 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002231 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2232 Loc = FD->getLocation();
2233 Type = FD->getType();
2234 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002235 else
2236 return;
Mike Stump11289f42009-09-09 15:08:12 +00002237
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002238 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002239 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002240
Steve Naroff50d42052007-11-01 13:24:47 +00002241 const char *endBuf = SM->getCharacterData(Loc);
2242 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002243 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002244 startBuf--; // scan backward (from the decl location) for return type.
2245 const char *startRef = 0, *endRef = 0;
2246 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2247 // Get the locations of the startRef, endRef.
2248 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2249 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2250 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002251 InsertText(LessLoc, "/*");
2252 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002253 }
2254 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002255 if (!proto)
2256 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002257 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002258 const char *startBuf = SM->getCharacterData(Loc);
2259 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002260 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2261 if (needToScanForQualifiers(proto->getArgType(i))) {
2262 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002263
Steve Naroff50d42052007-11-01 13:24:47 +00002264 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002265 // scan forward (from the decl location) for argument types.
2266 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002267 const char *startRef = 0, *endRef = 0;
2268 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2269 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002270 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002271 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002272 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002273 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002274 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002275 InsertText(LessLoc, "/*");
2276 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002277 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002278 startBuf = ++endBuf;
2279 }
2280 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002281 // If the function name is derived from a macro expansion, then the
2282 // argument buffer will not follow the name. Need to speak with Chris.
2283 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002284 startBuf++; // scan forward (from the decl location) for argument types.
2285 startBuf++;
2286 }
Steve Naroff50d42052007-11-01 13:24:47 +00002287 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002288}
2289
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002290void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2291 QualType QT = ND->getType();
2292 const Type* TypePtr = QT->getAs<Type>();
2293 if (!isa<TypeOfExprType>(TypePtr))
2294 return;
2295 while (isa<TypeOfExprType>(TypePtr)) {
2296 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2297 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2298 TypePtr = QT->getAs<Type>();
2299 }
2300 // FIXME. This will not work for multiple declarators; as in:
2301 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002302 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002303 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2304 const char *startBuf = SM->getCharacterData(DeclLoc);
2305 if (ND->getInit()) {
2306 std::string Name(ND->getNameAsString());
2307 TypeAsString += " " + Name + " = ";
2308 Expr *E = ND->getInit();
2309 SourceLocation startLoc;
2310 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2311 startLoc = ECE->getLParenLoc();
2312 else
2313 startLoc = E->getLocStart();
2314 startLoc = SM->getInstantiationLoc(startLoc);
2315 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002316 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002317 }
2318 else {
2319 SourceLocation X = ND->getLocEnd();
2320 X = SM->getInstantiationLoc(X);
2321 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002322 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002323 }
2324}
2325
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002326// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002327void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002328 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2329 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002330 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002331 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002332 &ArgTys[0], ArgTys.size(),
2333 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002334 false, false, 0, 0,
2335 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002336 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002337 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002338 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002339 SC_Extern,
2340 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002341}
2342
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002343void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002344 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002345 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002346 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002347 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002348 return;
2349 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002350 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002351}
2352
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002353void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2354 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002355 const char *argPtr = TypeString.c_str();
2356 if (!strchr(argPtr, '^')) {
2357 Str += TypeString;
2358 return;
2359 }
2360 while (*argPtr) {
2361 Str += (*argPtr == '^' ? '*' : *argPtr);
2362 argPtr++;
2363 }
2364}
2365
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002366// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002367void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2368 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002369 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002370 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002371 const char *argPtr = TypeString.c_str();
2372 int paren = 0;
2373 while (*argPtr) {
2374 switch (*argPtr) {
2375 case '(':
2376 Str += *argPtr;
2377 paren++;
2378 break;
2379 case ')':
2380 Str += *argPtr;
2381 paren--;
2382 break;
2383 case '^':
2384 Str += '*';
2385 if (paren == 1)
2386 Str += VD->getNameAsString();
2387 break;
2388 default:
2389 Str += *argPtr;
2390 break;
2391 }
2392 argPtr++;
2393 }
2394}
2395
2396
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002397void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2398 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2399 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2400 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2401 if (!proto)
2402 return;
2403 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002404 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002405 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002406 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002407 FdStr += "(";
2408 unsigned numArgs = proto->getNumArgs();
2409 for (unsigned i = 0; i < numArgs; i++) {
2410 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002411 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002412 if (i+1 < numArgs)
2413 FdStr += ", ";
2414 }
2415 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002416 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002417 CurFunctionDeclToDeclareForBlock = 0;
2418}
2419
Steve Naroff17978c42008-03-11 17:37:02 +00002420// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002421void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002422 if (SuperContructorFunctionDecl)
2423 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002424 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002425 llvm::SmallVector<QualType, 16> ArgTys;
2426 QualType argT = Context->getObjCIdType();
2427 assert(!argT.isNull() && "Can't find 'id' type");
2428 ArgTys.push_back(argT);
2429 ArgTys.push_back(argT);
2430 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2431 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002432 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002433 false, false, 0, 0,
2434 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002435 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002436 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002437 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002438 SC_Extern,
2439 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002440}
2441
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002442// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002443void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002444 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2445 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002446 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002447 assert(!argT.isNull() && "Can't find 'id' type");
2448 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002449 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002450 assert(!argT.isNull() && "Can't find 'SEL' type");
2451 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002452 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002453 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002454 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002455 false, false, 0, 0,
2456 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002457 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002458 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002459 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002460 SC_Extern,
2461 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002462}
2463
Steve Naroff7fa2f042007-11-15 10:28:18 +00002464// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002465void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2467 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002468 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002469 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002470 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002471 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2472 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2473 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002474 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002475 assert(!argT.isNull() && "Can't find 'SEL' type");
2476 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002477 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002478 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002479 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002480 false, false, 0, 0,
2481 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002482 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002483 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002484 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002485 SC_Extern,
2486 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002487}
2488
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002489// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002490void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2492 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002493 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002494 assert(!argT.isNull() && "Can't find 'id' type");
2495 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002496 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002497 assert(!argT.isNull() && "Can't find 'SEL' type");
2498 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002499 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002500 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002501 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002502 false, false, 0, 0,
2503 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002504 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002505 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002506 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002507 SC_Extern,
2508 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002509}
2510
Mike Stump11289f42009-09-09 15:08:12 +00002511// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002512// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002513void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002514 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002515 &Context->Idents.get("objc_msgSendSuper_stret");
2516 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002517 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002518 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002519 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002520 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2521 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2522 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002523 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002524 assert(!argT.isNull() && "Can't find 'SEL' type");
2525 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002526 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002527 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002528 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002529 false, false, 0, 0,
2530 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002531 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002532 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002533 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002534 SC_Extern,
2535 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002536}
2537
Steve Naroff2e4e3852008-05-08 22:02:18 +00002538// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002539void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002540 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2541 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002542 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002543 assert(!argT.isNull() && "Can't find 'id' type");
2544 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002545 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002546 assert(!argT.isNull() && "Can't find 'SEL' type");
2547 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002548 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002549 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002550 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002551 false, false, 0, 0,
2552 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002553 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002554 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002555 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002556 SC_Extern,
2557 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002558}
2559
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002560// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002561void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002562 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2563 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002564 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002565 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002566 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002567 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002568 false, false, 0, 0,
2569 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002570 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002571 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002572 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002573 SC_Extern,
2574 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002575}
2576
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002577// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2578void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2579 IdentifierInfo *getSuperClassIdent =
2580 &Context->Idents.get("class_getSuperclass");
2581 llvm::SmallVector<QualType, 16> ArgTys;
2582 ArgTys.push_back(Context->getObjCClassType());
2583 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2584 &ArgTys[0], ArgTys.size(),
2585 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002586 false, false, 0, 0,
2587 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002588 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002589 SourceLocation(),
2590 getSuperClassIdent,
2591 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002592 SC_Extern,
2593 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002594 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002595}
2596
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002597// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002598void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002599 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2600 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002601 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002602 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002603 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002604 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002605 false, false, 0, 0,
2606 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002607 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002608 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002609 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002610 SC_Extern,
2611 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002612}
2613
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002614Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002615 QualType strType = getConstantStringStructType();
2616
2617 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002618
2619 std::string tmpName = InFileName;
2620 unsigned i;
2621 for (i=0; i < tmpName.length(); i++) {
2622 char c = tmpName.at(i);
2623 // replace any non alphanumeric characters with '_'.
2624 if (!isalpha(c) && (c < '0' || c > '9'))
2625 tmpName[i] = '_';
2626 }
2627 S += tmpName;
2628 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002629 S += utostr(NumObjCStringLiterals++);
2630
Steve Naroff00a31762008-03-27 22:29:16 +00002631 Preamble += "static __NSConstantStringImpl " + S;
2632 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2633 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002634 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002635 std::string prettyBufS;
2636 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002637 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2638 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002639 Preamble += prettyBuf.str();
2640 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002641 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002642
2643 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002644 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002645 SC_Static, SC_None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002646 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002647 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002648 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002649 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002650 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002651 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalle3027922010-08-25 11:45:40 +00002652 CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002653 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002654 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002655 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002656}
2657
Steve Naroff7fa2f042007-11-15 10:28:18 +00002658// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002659QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002660 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002661 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002662 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002663 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002664 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002665
Steve Naroff7fa2f042007-11-15 10:28:18 +00002666 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002667 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002668 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002669 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002670
Steve Naroff7fa2f042007-11-15 10:28:18 +00002671 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002672 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002673 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2674 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002675 FieldTypes[i], 0,
2676 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002677 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002678 }
Mike Stump11289f42009-09-09 15:08:12 +00002679
Douglas Gregord5058122010-02-11 01:19:42 +00002680 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002681 }
2682 return Context->getTagDeclType(SuperStructDecl);
2683}
2684
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002685QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002686 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002687 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002688 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002689 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002690 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroffce8e8862008-03-15 00:55:56 +00002692 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002693 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002694 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002695 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002696 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002697 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002698 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002699 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002700
Steve Naroffce8e8862008-03-15 00:55:56 +00002701 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002702 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002703 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2704 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002705 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002706 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002707 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002708 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002709 }
2710
Douglas Gregord5058122010-02-11 01:19:42 +00002711 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002712 }
2713 return Context->getTagDeclType(ConstantStringDecl);
2714}
2715
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002716Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2717 SourceLocation StartLoc,
2718 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002719 if (!SelGetUidFunctionDecl)
2720 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002721 if (!MsgSendFunctionDecl)
2722 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002723 if (!MsgSendSuperFunctionDecl)
2724 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002725 if (!MsgSendStretFunctionDecl)
2726 SynthMsgSendStretFunctionDecl();
2727 if (!MsgSendSuperStretFunctionDecl)
2728 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002729 if (!MsgSendFpretFunctionDecl)
2730 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002731 if (!GetClassFunctionDecl)
2732 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002733 if (!GetSuperClassFunctionDecl)
2734 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002735 if (!GetMetaClassFunctionDecl)
2736 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002737
Steve Naroff7fa2f042007-11-15 10:28:18 +00002738 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002739 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2740 // May need to use objc_msgSend_stret() as well.
2741 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002742 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2743 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002744 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002745 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002746 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002747 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002748 }
Mike Stump11289f42009-09-09 15:08:12 +00002749
Steve Naroff574440f2007-10-24 22:48:43 +00002750 // Synthesize a call to objc_msgSend().
2751 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002752 switch (Exp->getReceiverKind()) {
2753 case ObjCMessageExpr::SuperClass: {
2754 MsgSendFlavor = MsgSendSuperFunctionDecl;
2755 if (MsgSendStretFlavor)
2756 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2757 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregor9a129192010-04-21 00:45:42 +00002759 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002760
Douglas Gregor9a129192010-04-21 00:45:42 +00002761 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002762
Douglas Gregor9a129192010-04-21 00:45:42 +00002763 // set the receiver to self, the first argument to all methods.
2764 InitExprs.push_back(
2765 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002766 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002767 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2768 Context->getObjCIdType(),
2769 SourceLocation()))
2770 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2773 llvm::SmallVector<Expr*, 8> ClsExprs;
2774 QualType argType = Context->getPointerType(Context->CharTy);
2775 ClsExprs.push_back(StringLiteral::Create(*Context,
2776 ClassDecl->getIdentifier()->getNameStart(),
2777 ClassDecl->getIdentifier()->getLength(),
2778 false, argType, SourceLocation()));
2779 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2780 &ClsExprs[0],
2781 ClsExprs.size(),
2782 StartLoc,
2783 EndLoc);
2784 // (Class)objc_getClass("CurrentClass")
2785 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2786 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002787 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002788 ClsExprs.clear();
2789 ClsExprs.push_back(ArgExpr);
2790 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2791 &ClsExprs[0], ClsExprs.size(),
2792 StartLoc, EndLoc);
2793
2794 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2795 // To turn off a warning, type-cast to 'id'
2796 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2797 NoTypeInfoCStyleCastExpr(Context,
2798 Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002799 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002800 // struct objc_super
2801 QualType superType = getSuperStructType();
2802 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002803
Douglas Gregor9a129192010-04-21 00:45:42 +00002804 if (LangOpts.Microsoft) {
2805 SynthSuperContructorFunctionDecl();
2806 // Simulate a contructor call...
2807 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2808 superType, SourceLocation());
2809 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2810 InitExprs.size(),
2811 superType, SourceLocation());
2812 // The code for super is a little tricky to prevent collision with
2813 // the structure definition in the header. The rewriter has it's own
2814 // internal definition (__rw_objc_super) that is uses. This is why
2815 // we need the cast below. For example:
2816 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2817 //
John McCalle3027922010-08-25 11:45:40 +00002818 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002819 Context->getPointerType(SuperRep->getType()),
2820 SourceLocation());
2821 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2822 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002823 CK_Unknown, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002824 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002825 // (struct objc_super) { <exprs from above> }
2826 InitListExpr *ILE =
2827 new (Context) InitListExpr(*Context, SourceLocation(),
2828 &InitExprs[0], InitExprs.size(),
2829 SourceLocation());
2830 TypeSourceInfo *superTInfo
2831 = Context->getTrivialTypeSourceInfo(superType);
2832 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2833 superType, ILE, false);
2834 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002835 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002836 Context->getPointerType(SuperRep->getType()),
2837 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002838 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 MsgExprs.push_back(SuperRep);
2840 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002841 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002842
2843 case ObjCMessageExpr::Class: {
2844 llvm::SmallVector<Expr*, 8> ClsExprs;
2845 QualType argType = Context->getPointerType(Context->CharTy);
2846 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002847 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002848 IdentifierInfo *clsName = Class->getIdentifier();
2849 ClsExprs.push_back(StringLiteral::Create(*Context,
2850 clsName->getNameStart(),
2851 clsName->getLength(),
2852 false, argType,
2853 SourceLocation()));
2854 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2855 &ClsExprs[0],
2856 ClsExprs.size(),
2857 StartLoc, EndLoc);
2858 MsgExprs.push_back(Cls);
2859 break;
2860 }
2861
2862 case ObjCMessageExpr::SuperInstance:{
2863 MsgSendFlavor = MsgSendSuperFunctionDecl;
2864 if (MsgSendStretFlavor)
2865 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2866 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2867 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2868 llvm::SmallVector<Expr*, 4> InitExprs;
2869
2870 InitExprs.push_back(
2871 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002872 CK_Unknown,
Douglas Gregor9a129192010-04-21 00:45:42 +00002873 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2874 Context->getObjCIdType(),
2875 SourceLocation()))
2876 ); // set the 'receiver'.
2877
2878 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2879 llvm::SmallVector<Expr*, 8> ClsExprs;
2880 QualType argType = Context->getPointerType(Context->CharTy);
2881 ClsExprs.push_back(StringLiteral::Create(*Context,
2882 ClassDecl->getIdentifier()->getNameStart(),
2883 ClassDecl->getIdentifier()->getLength(),
2884 false, argType, SourceLocation()));
2885 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2886 &ClsExprs[0],
2887 ClsExprs.size(),
2888 StartLoc, EndLoc);
2889 // (Class)objc_getClass("CurrentClass")
2890 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2891 Context->getObjCClassType(),
John McCalle3027922010-08-25 11:45:40 +00002892 CK_Unknown, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002893 ClsExprs.clear();
2894 ClsExprs.push_back(ArgExpr);
2895 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2896 &ClsExprs[0], ClsExprs.size(),
2897 StartLoc, EndLoc);
2898
2899 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2900 // To turn off a warning, type-cast to 'id'
2901 InitExprs.push_back(
2902 // set 'super class', using class_getSuperclass().
2903 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002904 CK_Unknown, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002905 // struct objc_super
2906 QualType superType = getSuperStructType();
2907 Expr *SuperRep;
2908
2909 if (LangOpts.Microsoft) {
2910 SynthSuperContructorFunctionDecl();
2911 // Simulate a contructor call...
2912 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2913 superType, SourceLocation());
2914 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2915 InitExprs.size(),
2916 superType, SourceLocation());
2917 // The code for super is a little tricky to prevent collision with
2918 // the structure definition in the header. The rewriter has it's own
2919 // internal definition (__rw_objc_super) that is uses. This is why
2920 // we need the cast below. For example:
2921 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2922 //
John McCalle3027922010-08-25 11:45:40 +00002923 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002924 Context->getPointerType(SuperRep->getType()),
2925 SourceLocation());
2926 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2927 Context->getPointerType(superType),
John McCalle3027922010-08-25 11:45:40 +00002928 CK_Unknown, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002929 } else {
2930 // (struct objc_super) { <exprs from above> }
2931 InitListExpr *ILE =
2932 new (Context) InitListExpr(*Context, SourceLocation(),
2933 &InitExprs[0], InitExprs.size(),
2934 SourceLocation());
2935 TypeSourceInfo *superTInfo
2936 = Context->getTrivialTypeSourceInfo(superType);
2937 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2938 superType, ILE, false);
2939 }
2940 MsgExprs.push_back(SuperRep);
2941 break;
2942 }
2943
2944 case ObjCMessageExpr::Instance: {
2945 // Remove all type-casts because it may contain objc-style types; e.g.
2946 // Foo<Proto> *.
2947 Expr *recExpr = Exp->getInstanceReceiver();
2948 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2949 recExpr = CE->getSubExpr();
2950 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002951 CK_Unknown, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002952 MsgExprs.push_back(recExpr);
2953 break;
2954 }
2955 }
2956
Steve Naroffa397efd2007-11-03 11:27:19 +00002957 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002958 llvm::SmallVector<Expr*, 8> SelExprs;
2959 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002960 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002961 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002962 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002963 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002964 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002965 &SelExprs[0], SelExprs.size(),
2966 StartLoc,
2967 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002968 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002969
Steve Naroff574440f2007-10-24 22:48:43 +00002970 // Now push any user supplied arguments.
2971 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002972 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002973 // Make all implicit casts explicit...ICE comes in handy:-)
2974 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2975 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002976 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002977 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002978 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002979 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002980 (void)convertBlockPointerToFunctionPointer(type);
John McCalle3027922010-08-25 11:45:40 +00002981 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00002982 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002983 }
2984 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002985 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002986 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002987 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002988 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002989 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalle3027922010-08-25 11:45:40 +00002990 CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002991 }
Mike Stump11289f42009-09-09 15:08:12 +00002992 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002993 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002994 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2995 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002996 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002997 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002998 }
Steve Narofff36987c2007-11-04 22:37:50 +00002999 // Generate the funky cast.
3000 CastExpr *cast;
3001 llvm::SmallVector<QualType, 8> ArgTypes;
3002 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003003
Steve Narofff36987c2007-11-04 22:37:50 +00003004 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003005 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3006 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3007 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003008 ArgTypes.push_back(Context->getObjCIdType());
3009 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003010 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003011 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003012 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3013 E = OMD->param_end(); PI != E; ++PI) {
3014 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003015 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003016 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003017 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003018 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003019 ArgTypes.push_back(t);
3020 }
Chris Lattnera4997152009-02-20 18:43:26 +00003021 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3022 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003023 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003024 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003025 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003026 }
3027 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003028 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003029
Steve Narofff36987c2007-11-04 22:37:50 +00003030 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003031 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003032 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003033
Mike Stump11289f42009-09-09 15:08:12 +00003034 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003035 // If we don't do this cast, we get the following bizarre warning/note:
3036 // xx.m:13: warning: function called through a non-compatible type
3037 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003038 cast = NoTypeInfoCStyleCastExpr(Context,
3039 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00003040 CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Steve Narofff36987c2007-11-04 22:37:50 +00003042 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003043 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003044 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003045 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003046 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003047 false, false, 0, 0,
3048 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003049 castType = Context->getPointerType(castType);
John McCalle3027922010-08-25 11:45:40 +00003050 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003051 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003052
3053 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003054 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003055
John McCall9dd450b2009-09-21 23:43:11 +00003056 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003057 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003058 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003059 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003060 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003061 if (MsgSendStretFlavor) {
3062 // We have the method which returns a struct/union. Must also generate
3063 // call to objc_msgSend_stret and hang both varieties on a conditional
3064 // expression which dictate which one to envoke depending on size of
3065 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003066
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003067 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003068 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003069 SourceLocation());
3070 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003071 cast = NoTypeInfoCStyleCastExpr(Context,
3072 Context->getPointerType(Context->VoidTy),
John McCalle3027922010-08-25 11:45:40 +00003073 CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003074 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003075 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003076 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003077 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003078 false, false, 0, 0,
3079 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003080 castType = Context->getPointerType(castType);
John McCalle3027922010-08-25 11:45:40 +00003081 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003082 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003083
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003084 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003085 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003086
John McCall9dd450b2009-09-21 23:43:11 +00003087 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003088 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003089 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003090 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003091
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003092 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003093 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003094 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003095 Context->getSizeType(),
3096 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003097 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3098 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3099 // For X86 it is more complicated and some kind of target specific routine
3100 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003101 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003102 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003103 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3104 llvm::APInt(IntSize, 8),
3105 Context->IntTy,
3106 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003107 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCalle3027922010-08-25 11:45:40 +00003108 BO_LE,
Mike Stump11289f42009-09-09 15:08:12 +00003109 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003110 SourceLocation());
3111 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003112 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003113 new (Context) ConditionalOperator(lessThanExpr,
3114 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003115 SourceLocation(), STCE, (Expr*)0,
3116 returnType);
3117 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3118 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003119 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003120 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003121 return ReplacingStmt;
3122}
3123
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003124Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003125 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3126 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003127
Steve Naroff574440f2007-10-24 22:48:43 +00003128 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003129 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003130
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003131 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003132 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003133}
3134
Steve Naroffd9803712009-04-29 16:37:50 +00003135// typedef struct objc_object Protocol;
3136QualType RewriteObjC::getProtocolType() {
3137 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003138 TypeSourceInfo *TInfo
3139 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003140 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003141 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003142 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003143 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003144 }
3145 return Context->getTypeDeclType(ProtocolTypeDecl);
3146}
3147
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003148/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003149/// a synthesized/forward data reference (to the protocol's metadata).
3150/// The forward references (and metadata) are generated in
3151/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003152Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003153 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3154 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003155 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003156 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003157 SC_Extern, SC_None);
Steve Naroffd9803712009-04-29 16:37:50 +00003158 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003159 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003160 Context->getPointerType(DRE->getType()),
3161 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003162 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalle3027922010-08-25 11:45:40 +00003163 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00003164 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003165 ReplaceStmt(Exp, castExpr);
3166 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003167 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003168 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003169
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003170}
3171
Mike Stump11289f42009-09-09 15:08:12 +00003172bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003173 const char *endBuf) {
3174 while (startBuf < endBuf) {
3175 if (*startBuf == '#') {
3176 // Skip whitespace.
3177 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3178 ;
3179 if (!strncmp(startBuf, "if", strlen("if")) ||
3180 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3181 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3182 !strncmp(startBuf, "define", strlen("define")) ||
3183 !strncmp(startBuf, "undef", strlen("undef")) ||
3184 !strncmp(startBuf, "else", strlen("else")) ||
3185 !strncmp(startBuf, "elif", strlen("elif")) ||
3186 !strncmp(startBuf, "endif", strlen("endif")) ||
3187 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3188 !strncmp(startBuf, "include", strlen("include")) ||
3189 !strncmp(startBuf, "import", strlen("import")) ||
3190 !strncmp(startBuf, "include_next", strlen("include_next")))
3191 return true;
3192 }
3193 startBuf++;
3194 }
3195 return false;
3196}
3197
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003198/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003199/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003200void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003201 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003202 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003203 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003204 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003205 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003206 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003207 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003208 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003209 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003210 SourceLocation LocStart = CDecl->getLocStart();
3211 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003212
Steve Naroffdde78982007-11-14 19:25:57 +00003213 const char *startBuf = SM->getCharacterData(LocStart);
3214 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003215
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003216 // If no ivars and no root or if its root, directly or indirectly,
3217 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003218 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3219 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003220 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003221 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003222 return;
3223 }
Mike Stump11289f42009-09-09 15:08:12 +00003224
3225 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003226 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003227 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003228 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003229 if (LangOpts.Microsoft)
3230 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003231
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003232 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003233 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003234 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003235 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003236 // If the buffer contains preprocessor directives, we do more fine-grained
3237 // rewrites. This is intended to fix code that looks like (which occurs in
3238 // NSURL.h, for example):
3239 //
3240 // #ifdef XYZ
3241 // @interface Foo : NSObject
3242 // #else
3243 // @interface FooBar : NSObject
3244 // #endif
3245 // {
3246 // int i;
3247 // }
3248 // @end
3249 //
3250 // This clause is segregated to avoid breaking the common case.
3251 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003252 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003253 CDecl->getClassLoc();
3254 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003255 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003256
Chris Lattnerf5b77512009-02-20 18:18:36 +00003257 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003258 // advance to the end of the referenced protocols.
3259 while (endHeader < cursor && *endHeader != '>') endHeader++;
3260 endHeader++;
3261 }
3262 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003263 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003264 } else {
3265 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003266 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003267 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003268 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003269 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003270 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003271 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003272 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003273 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003274
Steve Naroffdde78982007-11-14 19:25:57 +00003275 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003276 SourceLocation OnePastCurly =
3277 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003278 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003279 }
3280 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003281
Steve Naroffdde78982007-11-14 19:25:57 +00003282 // Now comment out any visibility specifiers.
3283 while (cursor < endBuf) {
3284 if (*cursor == '@') {
3285 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003286 // Skip whitespace.
3287 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3288 /*scan*/;
3289
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003290 // FIXME: presence of @public, etc. inside comment results in
3291 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003292 if (!strncmp(cursor, "public", strlen("public")) ||
3293 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003294 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003295 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003296 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003297 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003298 // FIXME: If there are cases where '<' is used in ivar declaration part
3299 // of user code, then scan the ivar list and use needToScanForQualifiers
3300 // for type checking.
3301 else if (*cursor == '<') {
3302 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003303 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003304 cursor = strchr(cursor, '>');
3305 cursor++;
3306 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003307 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003308 } else if (*cursor == '^') { // rewrite block specifier.
3309 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003310 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003311 }
Steve Naroffdde78982007-11-14 19:25:57 +00003312 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003313 }
Steve Naroffdde78982007-11-14 19:25:57 +00003314 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003315 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003316 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003317 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003318 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003319 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003320 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003321 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003322 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003323 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003324 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003325 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003326 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003327 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003328}
3329
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003330// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003331/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003332template<typename MethodIterator>
3333void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3334 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003335 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003336 llvm::StringRef prefix,
3337 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003338 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003339 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003340
Chris Lattner31bc07e2007-12-12 07:46:12 +00003341 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003342 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003343 SEL _cmd;
3344 char *method_types;
3345 void *_imp;
3346 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003347 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003348 Result += "\nstruct _objc_method {\n";
3349 Result += "\tSEL _cmd;\n";
3350 Result += "\tchar *method_types;\n";
3351 Result += "\tvoid *_imp;\n";
3352 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003353
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003354 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003355 }
Mike Stump11289f42009-09-09 15:08:12 +00003356
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003357 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003358
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003359 /* struct {
3360 struct _objc_method_list *next_method;
3361 int method_count;
3362 struct _objc_method method_list[];
3363 }
3364 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003365 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003366 Result += "\nstatic struct {\n";
3367 Result += "\tstruct _objc_method_list *next_method;\n";
3368 Result += "\tint method_count;\n";
3369 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003370 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003371 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003372 Result += prefix;
3373 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3374 Result += "_METHODS_";
3375 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003376 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003377 Result += IsInstanceMethod ? "inst" : "cls";
3378 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003379 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003380
Chris Lattner31bc07e2007-12-12 07:46:12 +00003381 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003382 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003383 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003384 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003385 Result += "\", \"";
3386 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003387 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003388 Result += MethodInternalNames[*MethodBegin];
3389 Result += "}\n";
3390 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3391 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003392 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003393 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003394 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003395 Result += "\", \"";
3396 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003397 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003398 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003399 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003400 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003401 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003402}
3403
Steve Naroffd9803712009-04-29 16:37:50 +00003404/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003405void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003406RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3407 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003408 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003409
3410 // Output struct protocol_methods holder of method selector and type.
3411 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3412 /* struct protocol_methods {
3413 SEL _cmd;
3414 char *method_types;
3415 }
3416 */
3417 Result += "\nstruct _protocol_methods {\n";
3418 Result += "\tstruct objc_selector *_cmd;\n";
3419 Result += "\tchar *method_types;\n";
3420 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003421
Steve Naroffd9803712009-04-29 16:37:50 +00003422 objc_protocol_methods = true;
3423 }
3424 // Do not synthesize the protocol more than once.
3425 if (ObjCSynthesizedProtocols.count(PDecl))
3426 return;
Mike Stump11289f42009-09-09 15:08:12 +00003427
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003428 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3429 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3430 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003431 /* struct _objc_protocol_method_list {
3432 int protocol_method_count;
3433 struct protocol_methods protocols[];
3434 }
Steve Naroff251084d2008-03-12 01:06:30 +00003435 */
Steve Naroffd9803712009-04-29 16:37:50 +00003436 Result += "\nstatic struct {\n";
3437 Result += "\tint protocol_method_count;\n";
3438 Result += "\tstruct _protocol_methods protocol_methods[";
3439 Result += utostr(NumMethods);
3440 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3441 Result += PDecl->getNameAsString();
3442 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3443 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003444
Steve Naroffd9803712009-04-29 16:37:50 +00003445 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003446 for (ObjCProtocolDecl::instmeth_iterator
3447 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003448 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003449 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003450 Result += "\t ,{{(struct objc_selector *)\"";
3451 else
3452 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003453 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003454 std::string MethodTypeString;
3455 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3456 Result += "\", \"";
3457 Result += MethodTypeString;
3458 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003459 }
Steve Naroffd9803712009-04-29 16:37:50 +00003460 Result += "\t }\n};\n";
3461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Steve Naroffd9803712009-04-29 16:37:50 +00003463 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003464 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3465 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003466 if (NumMethods > 0) {
3467 /* struct _objc_protocol_method_list {
3468 int protocol_method_count;
3469 struct protocol_methods protocols[];
3470 }
3471 */
3472 Result += "\nstatic struct {\n";
3473 Result += "\tint protocol_method_count;\n";
3474 Result += "\tstruct _protocol_methods protocol_methods[";
3475 Result += utostr(NumMethods);
3476 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3477 Result += PDecl->getNameAsString();
3478 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3479 "{\n\t";
3480 Result += utostr(NumMethods);
3481 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003482
Steve Naroffd9803712009-04-29 16:37:50 +00003483 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003484 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003485 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003486 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003487 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003488 Result += "\t ,{{(struct objc_selector *)\"";
3489 else
3490 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003491 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003492 std::string MethodTypeString;
3493 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3494 Result += "\", \"";
3495 Result += MethodTypeString;
3496 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003497 }
Steve Naroffd9803712009-04-29 16:37:50 +00003498 Result += "\t }\n};\n";
3499 }
3500
3501 // Output:
3502 /* struct _objc_protocol {
3503 // Objective-C 1.0 extensions
3504 struct _objc_protocol_extension *isa;
3505 char *protocol_name;
3506 struct _objc_protocol **protocol_list;
3507 struct _objc_protocol_method_list *instance_methods;
3508 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003509 };
Steve Naroffd9803712009-04-29 16:37:50 +00003510 */
3511 static bool objc_protocol = false;
3512 if (!objc_protocol) {
3513 Result += "\nstruct _objc_protocol {\n";
3514 Result += "\tstruct _objc_protocol_extension *isa;\n";
3515 Result += "\tchar *protocol_name;\n";
3516 Result += "\tstruct _objc_protocol **protocol_list;\n";
3517 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3518 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003519 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003520
Steve Naroffd9803712009-04-29 16:37:50 +00003521 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003522 }
Mike Stump11289f42009-09-09 15:08:12 +00003523
Steve Naroffd9803712009-04-29 16:37:50 +00003524 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3525 Result += PDecl->getNameAsString();
3526 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3527 "{\n\t0, \"";
3528 Result += PDecl->getNameAsString();
3529 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003530 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003531 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3532 Result += PDecl->getNameAsString();
3533 Result += ", ";
3534 }
3535 else
3536 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003537 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003538 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3539 Result += PDecl->getNameAsString();
3540 Result += "\n";
3541 }
3542 else
3543 Result += "0\n";
3544 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003545
Steve Naroffd9803712009-04-29 16:37:50 +00003546 // Mark this protocol as having been generated.
3547 if (!ObjCSynthesizedProtocols.insert(PDecl))
3548 assert(false && "protocol already synthesized");
3549
3550}
3551
3552void RewriteObjC::
3553RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003554 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003555 std::string &Result) {
3556 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003557
Steve Naroffd9803712009-04-29 16:37:50 +00003558 for (unsigned i = 0; i != Protocols.size(); i++)
3559 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3560
Chris Lattner388f6e92008-07-21 21:33:21 +00003561 // Output the top lovel protocol meta-data for the class.
3562 /* struct _objc_protocol_list {
3563 struct _objc_protocol_list *next;
3564 int protocol_count;
3565 struct _objc_protocol *class_protocols[];
3566 }
3567 */
3568 Result += "\nstatic struct {\n";
3569 Result += "\tstruct _objc_protocol_list *next;\n";
3570 Result += "\tint protocol_count;\n";
3571 Result += "\tstruct _objc_protocol *class_protocols[";
3572 Result += utostr(Protocols.size());
3573 Result += "];\n} _OBJC_";
3574 Result += prefix;
3575 Result += "_PROTOCOLS_";
3576 Result += ClassName;
3577 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3578 "{\n\t0, ";
3579 Result += utostr(Protocols.size());
3580 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003581
Chris Lattner388f6e92008-07-21 21:33:21 +00003582 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003583 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003584 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattner388f6e92008-07-21 21:33:21 +00003586 for (unsigned i = 1; i != Protocols.size(); i++) {
3587 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003588 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003589 Result += "\n";
3590 }
3591 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003592}
3593
Steve Naroffd9803712009-04-29 16:37:50 +00003594
Mike Stump11289f42009-09-09 15:08:12 +00003595/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003596/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003597void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003598 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003599 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003600 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003601 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003602 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003603 CDecl = CDecl->getNextClassCategory())
3604 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3605 break;
Mike Stump11289f42009-09-09 15:08:12 +00003606
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003607 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003608 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003609 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003610
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003611 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003612 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003613 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003614
3615 // If any of our property implementations have associated getters or
3616 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003617 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3618 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003619 Prop != PropEnd; ++Prop) {
3620 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3621 continue;
3622 if (!(*Prop)->getPropertyIvarDecl())
3623 continue;
3624 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3625 if (!PD)
3626 continue;
3627 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3628 InstanceMethods.push_back(Getter);
3629 if (PD->isReadOnly())
3630 continue;
3631 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3632 InstanceMethods.push_back(Setter);
3633 }
3634 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003635 true, "CATEGORY_", FullCategoryName.c_str(),
3636 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003637
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003638 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003639 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003640 false, "CATEGORY_", FullCategoryName.c_str(),
3641 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003642
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003643 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003644 // Null CDecl is case of a category implementation with no category interface
3645 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003646 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003647 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003648 /* struct _objc_category {
3649 char *category_name;
3650 char *class_name;
3651 struct _objc_method_list *instance_methods;
3652 struct _objc_method_list *class_methods;
3653 struct _objc_protocol_list *protocols;
3654 // Objective-C 1.0 extensions
3655 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003656 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003657 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003658 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003659 */
Mike Stump11289f42009-09-09 15:08:12 +00003660
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003661 static bool objc_category = false;
3662 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003663 Result += "\nstruct _objc_category {\n";
3664 Result += "\tchar *category_name;\n";
3665 Result += "\tchar *class_name;\n";
3666 Result += "\tstruct _objc_method_list *instance_methods;\n";
3667 Result += "\tstruct _objc_method_list *class_methods;\n";
3668 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003669 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003670 Result += "\tstruct _objc_property_list *instance_properties;\n";
3671 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003672 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003673 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003674 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3675 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003676 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003677 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003679 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003680 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003681
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003682 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003683 Result += "\t, (struct _objc_method_list *)"
3684 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3685 Result += FullCategoryName;
3686 Result += "\n";
3687 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003688 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003689 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003690 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003691 Result += "\t, (struct _objc_method_list *)"
3692 "&_OBJC_CATEGORY_CLASS_METHODS_";
3693 Result += FullCategoryName;
3694 Result += "\n";
3695 }
3696 else
3697 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003698
Chris Lattnerf5b77512009-02-20 18:18:36 +00003699 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003700 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 Result += FullCategoryName;
3702 Result += "\n";
3703 }
3704 else
3705 Result += "\t, 0\n";
3706 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003707}
3708
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003709/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3710/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003711void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003712 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003713 if (ivar->isBitField()) {
3714 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3715 // place all bitfields at offset 0.
3716 Result += "0";
3717 } else {
3718 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003719 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003720 if (LangOpts.Microsoft)
3721 Result += "_IMPL";
3722 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003723 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003724 Result += ")";
3725 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003726}
3727
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003728//===----------------------------------------------------------------------===//
3729// Meta Data Emission
3730//===----------------------------------------------------------------------===//
3731
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003732void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003733 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003734 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003735
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003736 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003737 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003738 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003739 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003740 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
Chris Lattner30d23e82007-12-12 07:56:42 +00003743 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003744 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003745 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003746 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003747 if (NumIvars > 0) {
3748 static bool objc_ivar = false;
3749 if (!objc_ivar) {
3750 /* struct _objc_ivar {
3751 char *ivar_name;
3752 char *ivar_type;
3753 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003754 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003755 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003756 Result += "\nstruct _objc_ivar {\n";
3757 Result += "\tchar *ivar_name;\n";
3758 Result += "\tchar *ivar_type;\n";
3759 Result += "\tint ivar_offset;\n";
3760 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003761
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003762 objc_ivar = true;
3763 }
3764
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003765 /* struct {
3766 int ivar_count;
3767 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003768 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003769 */
Mike Stump11289f42009-09-09 15:08:12 +00003770 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003771 Result += "\tint ivar_count;\n";
3772 Result += "\tstruct _objc_ivar ivar_list[";
3773 Result += utostr(NumIvars);
3774 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003775 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003776 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003777 "{\n\t";
3778 Result += utostr(NumIvars);
3779 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003780
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003781 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003782 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003783 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003784 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003785 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003786 IV != IVEnd; ++IV)
3787 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003788 IVI = IDecl->ivar_begin();
3789 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003790 } else {
3791 IVI = CDecl->ivar_begin();
3792 IVE = CDecl->ivar_end();
3793 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003794 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003795 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003796 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003797 std::string TmpString, StrEncoding;
3798 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3799 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003800 Result += StrEncoding;
3801 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003802 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003803 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003804 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003805 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003806 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003807 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003808 std::string TmpString, StrEncoding;
3809 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3810 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003811 Result += StrEncoding;
3812 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003813 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003814 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003815 }
Mike Stump11289f42009-09-09 15:08:12 +00003816
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003817 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003818 }
Mike Stump11289f42009-09-09 15:08:12 +00003819
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003820 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003821 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003822 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003823
3824 // If any of our property implementations have associated getters or
3825 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003826 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3827 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003828 Prop != PropEnd; ++Prop) {
3829 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3830 continue;
3831 if (!(*Prop)->getPropertyIvarDecl())
3832 continue;
3833 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3834 if (!PD)
3835 continue;
3836 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3837 InstanceMethods.push_back(Getter);
3838 if (PD->isReadOnly())
3839 continue;
3840 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3841 InstanceMethods.push_back(Setter);
3842 }
3843 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003844 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003845
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003846 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003847 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003848 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003849
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003850 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003851 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003852 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003853
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003854 // Declaration of class/meta-class metadata
3855 /* struct _objc_class {
3856 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003857 const char *super_class_name;
3858 char *name;
3859 long version;
3860 long info;
3861 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003862 struct _objc_ivar_list *ivars;
3863 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003864 struct objc_cache *cache;
3865 struct objc_protocol_list *protocols;
3866 const char *ivar_layout;
3867 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003868 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003869 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003870 static bool objc_class = false;
3871 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003872 Result += "\nstruct _objc_class {\n";
3873 Result += "\tstruct _objc_class *isa;\n";
3874 Result += "\tconst char *super_class_name;\n";
3875 Result += "\tchar *name;\n";
3876 Result += "\tlong version;\n";
3877 Result += "\tlong info;\n";
3878 Result += "\tlong instance_size;\n";
3879 Result += "\tstruct _objc_ivar_list *ivars;\n";
3880 Result += "\tstruct _objc_method_list *methods;\n";
3881 Result += "\tstruct objc_cache *cache;\n";
3882 Result += "\tstruct _objc_protocol_list *protocols;\n";
3883 Result += "\tconst char *ivar_layout;\n";
3884 Result += "\tstruct _objc_class_ext *ext;\n";
3885 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003886 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003887 }
Mike Stump11289f42009-09-09 15:08:12 +00003888
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003889 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003890 ObjCInterfaceDecl *RootClass = 0;
3891 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003892 while (SuperClass) {
3893 RootClass = SuperClass;
3894 SuperClass = SuperClass->getSuperClass();
3895 }
3896 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003897
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003898 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003899 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003900 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003901 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003902 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003903 Result += "\"";
3904
3905 if (SuperClass) {
3906 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003907 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003908 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003909 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003910 Result += "\"";
3911 }
3912 else {
3913 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003914 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003915 Result += "\"";
3916 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003917 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003918 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003919 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003920 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003921 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003922 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003923 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003924 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003925 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003926 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003927 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003928 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003929 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003930 Result += ",0,0\n";
3931 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003932 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003933 Result += "\t,0,0,0,0\n";
3934 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003935
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003936 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003937 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003938 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003939 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003940 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003941 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003942 if (SuperClass) {
3943 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003944 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003945 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003947 Result += "\"";
3948 }
3949 else {
3950 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003952 Result += "\"";
3953 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003954 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003955 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003956 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003957 Result += ",0";
3958 else {
3959 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003960 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003961 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003962 if (LangOpts.Microsoft)
3963 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003964 Result += ")";
3965 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003966 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003967 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003969 Result += "\n\t";
3970 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003971 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003972 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003973 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003974 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003975 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003976 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003977 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003978 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003979 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003980 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003981 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003982 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003983 Result += ", 0,0\n";
3984 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003985 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003986 Result += ",0,0,0\n";
3987 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003988}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003989
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003990/// RewriteImplementations - This routine rewrites all method implementations
3991/// and emits meta-data.
3992
Steve Narofff8cfd162008-11-13 20:07:04 +00003993void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003994 int ClsDefCount = ClassImplementation.size();
3995 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003996
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003997 // Rewrite implemented methods
3998 for (int i = 0; i < ClsDefCount; i++)
3999 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004000
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004001 for (int i = 0; i < CatDefCount; i++)
4002 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004003}
Mike Stump11289f42009-09-09 15:08:12 +00004004
Steve Narofff8cfd162008-11-13 20:07:04 +00004005void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4006 int ClsDefCount = ClassImplementation.size();
4007 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004008
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004009 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004010 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004011 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004012
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004013 // For each implemented category, write out all its meta data.
4014 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004015 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004016
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004017 // Write objc_symtab metadata
4018 /*
4019 struct _objc_symtab
4020 {
4021 long sel_ref_cnt;
4022 SEL *refs;
4023 short cls_def_cnt;
4024 short cat_def_cnt;
4025 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004026 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004027 */
Mike Stump11289f42009-09-09 15:08:12 +00004028
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004029 Result += "\nstruct _objc_symtab {\n";
4030 Result += "\tlong sel_ref_cnt;\n";
4031 Result += "\tSEL *refs;\n";
4032 Result += "\tshort cls_def_cnt;\n";
4033 Result += "\tshort cat_def_cnt;\n";
4034 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4035 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004036
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004037 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004038 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004039 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004040 + ", " + utostr(CatDefCount) + "\n";
4041 for (int i = 0; i < ClsDefCount; i++) {
4042 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004043 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004044 Result += "\n";
4045 }
Mike Stump11289f42009-09-09 15:08:12 +00004046
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004047 for (int i = 0; i < CatDefCount; i++) {
4048 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004049 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004050 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004051 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004052 Result += "\n";
4053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004055 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004056
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004057 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004058
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004059 /*
4060 struct _objc_module {
4061 long version;
4062 long size;
4063 const char *name;
4064 struct _objc_symtab *symtab;
4065 }
4066 */
Mike Stump11289f42009-09-09 15:08:12 +00004067
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004068 Result += "\nstruct _objc_module {\n";
4069 Result += "\tlong version;\n";
4070 Result += "\tlong size;\n";
4071 Result += "\tconst char *name;\n";
4072 Result += "\tstruct _objc_symtab *symtab;\n";
4073 Result += "};\n\n";
4074 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004075 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004076 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004077 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004078 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004079
4080 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004081 if (ProtocolExprDecls.size()) {
4082 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4083 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004084 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004085 E = ProtocolExprDecls.end(); I != E; ++I) {
4086 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4087 Result += (*I)->getNameAsString();
4088 Result += " = &_OBJC_PROTOCOL_";
4089 Result += (*I)->getNameAsString();
4090 Result += ";\n";
4091 }
4092 Result += "#pragma data_seg(pop)\n\n";
4093 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004094 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004095 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004096 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4097 Result += "&_OBJC_MODULES;\n";
4098 Result += "#pragma data_seg(pop)\n\n";
4099 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004100}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004101
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004102void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4103 const std::string &Name,
4104 ValueDecl *VD) {
4105 assert(BlockByRefDeclNo.count(VD) &&
4106 "RewriteByRefString: ByRef decl missing");
4107 ResultStr += "struct __Block_byref_" + Name +
4108 "_" + utostr(BlockByRefDeclNo[VD]) ;
4109}
4110
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004111static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4112 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4113 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4114 return false;
4115}
4116
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004118 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 std::string Tag) {
4120 const FunctionType *AFT = CE->getFunctionType();
4121 QualType RT = AFT->getResultType();
4122 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004123 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004124 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004125
Steve Naroff677ab3a2008-10-27 17:20:55 +00004126 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004128 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004129 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004130 // block (to reference imported block decl refs).
4131 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 } else if (BD->param_empty()) {
4133 S += "(" + StructRef + " *__cself)";
4134 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004135 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 assert(FT && "SynthesizeBlockFunc: No function proto");
4137 S += '(';
4138 // first add the implicit argument.
4139 S += StructRef + " *__cself, ";
4140 std::string ParamStr;
4141 for (BlockDecl::param_iterator AI = BD->param_begin(),
4142 E = BD->param_end(); AI != E; ++AI) {
4143 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004144 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004145 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004146 if (convertBlockPointerToFunctionPointer(QT))
4147 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004148 else
4149 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004150 S += ParamStr;
4151 }
4152 if (FT->isVariadic()) {
4153 if (!BD->param_empty()) S += ", ";
4154 S += "...";
4155 }
4156 S += ')';
4157 }
4158 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004159
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 // Create local declarations to avoid rewriting all closure decl ref exprs.
4161 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004162 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163 E = BlockByRefDecls.end(); I != E; ++I) {
4164 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004165 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004166 std::string TypeString;
4167 RewriteByRefString(TypeString, Name, (*I));
4168 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004169 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004170 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004171 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004173 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004174 E = BlockByCopyDecls.end(); I != E; ++I) {
4175 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176 // Handle nested closure invocation. For example:
4177 //
4178 // void (^myImportedClosure)(void);
4179 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004180 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181 // void (^anotherClosure)(void);
4182 // anotherClosure = ^(void) {
4183 // myImportedClosure(); // import and invoke the closure
4184 // };
4185 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004186 if (isTopLevelBlockPointerType((*I)->getType())) {
4187 RewriteBlockPointerTypeVariable(S, (*I));
4188 S += " = (";
4189 RewriteBlockPointerType(S, (*I)->getType());
4190 S += ")";
4191 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4192 }
4193 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004194 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004195 QualType QT = (*I)->getType();
4196 if (HasLocalVariableExternalStorage(*I))
4197 QT = Context->getPointerType(QT);
4198 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004199 S += Name + " = __cself->" +
4200 (*I)->getNameAsString() + "; // bound by copy\n";
4201 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 }
4203 std::string RewrittenStr = RewrittenBlockExprs[CE];
4204 const char *cstr = RewrittenStr.c_str();
4205 while (*cstr++ != '{') ;
4206 S += cstr;
4207 S += "\n";
4208 return S;
4209}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004210
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004212 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 std::string Tag) {
4214 std::string StructRef = "struct " + Tag;
4215 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004216
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 S += funcName;
4218 S += "_block_copy_" + utostr(i);
4219 S += "(" + StructRef;
4220 S += "*dst, " + StructRef;
4221 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004222 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004223 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004224 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004225 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004226 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004227 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004228 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004229 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004230 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004231 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004232 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004233 S += "}\n";
4234
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 S += "\nstatic void __";
4236 S += funcName;
4237 S += "_block_dispose_" + utostr(i);
4238 S += "(" + StructRef;
4239 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004240 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004242 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004243 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004244 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004245 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004246 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004247 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250 return S;
4251}
4252
Steve Naroff30484702009-12-06 21:14:13 +00004253std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4254 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004255 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004257
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004259 S += " struct " + Desc;
4260 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004261
Steve Naroff30484702009-12-06 21:14:13 +00004262 Constructor += "(void *fp, "; // Invoke function pointer.
4263 Constructor += "struct " + Desc; // Descriptor pointer.
4264 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004265
Steve Naroff677ab3a2008-10-27 17:20:55 +00004266 if (BlockDeclRefs.size()) {
4267 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004268 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 E = BlockByCopyDecls.end(); I != E; ++I) {
4270 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004271 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004272 std::string ArgName = "_" + FieldName;
4273 // Handle nested closure invocation. For example:
4274 //
4275 // void (^myImportedBlock)(void);
4276 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004277 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 // void (^anotherBlock)(void);
4279 // anotherBlock = ^(void) {
4280 // myImportedBlock(); // import and invoke the closure
4281 // };
4282 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004283 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284 S += "struct __block_impl *";
4285 Constructor += ", void *" + ArgName;
4286 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004287 QualType QT = (*I)->getType();
4288 if (HasLocalVariableExternalStorage(*I))
4289 QT = Context->getPointerType(QT);
4290 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4291 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004292 Constructor += ", " + ArgName;
4293 }
4294 S += FieldName + ";\n";
4295 }
4296 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004297 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298 E = BlockByRefDecls.end(); I != E; ++I) {
4299 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004300 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004301 std::string ArgName = "_" + FieldName;
4302 // Handle nested closure invocation. For example:
4303 //
4304 // void (^myImportedBlock)(void);
4305 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004306 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 // void (^anotherBlock)(void);
4308 // anotherBlock = ^(void) {
4309 // myImportedBlock(); // import and invoke the closure
4310 // };
4311 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004312 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 S += "struct __block_impl *";
4314 Constructor += ", void *" + ArgName;
4315 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004316 std::string TypeString;
4317 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004318 TypeString += " *";
4319 FieldName = TypeString + FieldName;
4320 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 Constructor += ", " + ArgName;
4322 }
4323 S += FieldName + "; // by ref\n";
4324 }
4325 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004326 Constructor += ", int flags=0)";
4327 // Initialize all "by copy" arguments.
4328 bool firsTime = true;
4329 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4330 E = BlockByCopyDecls.end(); I != E; ++I) {
4331 std::string Name = (*I)->getNameAsString();
4332 if (firsTime) {
4333 Constructor += " : ";
4334 firsTime = false;
4335 }
4336 else
4337 Constructor += ", ";
4338 if (isTopLevelBlockPointerType((*I)->getType()))
4339 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4340 else
4341 Constructor += Name + "(_" + Name + ")";
4342 }
4343 // Initialize all "by ref" arguments.
4344 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4345 E = BlockByRefDecls.end(); I != E; ++I) {
4346 std::string Name = (*I)->getNameAsString();
4347 if (firsTime) {
4348 Constructor += " : ";
4349 firsTime = false;
4350 }
4351 else
4352 Constructor += ", ";
4353 if (isTopLevelBlockPointerType((*I)->getType()))
4354 Constructor += Name + "((struct __block_impl *)_"
4355 + Name + "->__forwarding)";
4356 else
4357 Constructor += Name + "(_" + Name + "->__forwarding)";
4358 }
4359
4360 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004361 if (GlobalVarDecl)
4362 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4363 else
4364 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004365 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004366
Steve Naroff30484702009-12-06 21:14:13 +00004367 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004368 } else {
4369 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004370 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004371 if (GlobalVarDecl)
4372 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4373 else
4374 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004375 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4376 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004377 }
4378 Constructor += " ";
4379 Constructor += "}\n";
4380 S += Constructor;
4381 S += "};\n";
4382 return S;
4383}
4384
Steve Naroff30484702009-12-06 21:14:13 +00004385std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4386 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004387 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004388 unsigned hasCopy) {
4389 std::string S = "\nstatic struct " + DescTag;
4390
4391 S += " {\n unsigned long reserved;\n";
4392 S += " unsigned long Block_size;\n";
4393 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004394 S += " void (*copy)(struct ";
4395 S += ImplTag; S += "*, struct ";
4396 S += ImplTag; S += "*);\n";
4397
4398 S += " void (*dispose)(struct ";
4399 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004400 }
4401 S += "} ";
4402
4403 S += DescTag + "_DATA = { 0, sizeof(struct ";
4404 S += ImplTag + ")";
4405 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004406 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4407 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004408 }
4409 S += "};\n";
4410 return S;
4411}
4412
Steve Naroff677ab3a2008-10-27 17:20:55 +00004413void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004414 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004415 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004416 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004417 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004418 bool RewriteSC = (GlobalVarDecl &&
4419 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004420 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004421 GlobalVarDecl->getType().getCVRQualifiers());
4422 if (RewriteSC) {
4423 std::string SC(" void __");
4424 SC += GlobalVarDecl->getNameAsString();
4425 SC += "() {}";
4426 InsertText(FunLocStart, SC);
4427 }
4428
Steve Naroff677ab3a2008-10-27 17:20:55 +00004429 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004430 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4431 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004432 // Need to copy-in the inner copied-in variables not actually used in this
4433 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004434 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4435 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4436 ValueDecl *VD = Exp->getDecl();
4437 BlockDeclRefs.push_back(Exp);
4438 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4439 BlockByCopyDeclsPtrSet.insert(VD);
4440 BlockByCopyDecls.push_back(VD);
4441 }
4442 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4443 BlockByRefDeclsPtrSet.insert(VD);
4444 BlockByRefDecls.push_back(VD);
4445 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004446 // imported objects in the inner blocks not used in the outer
4447 // blocks must be copied/disposed in the outer block as well.
4448 if (Exp->isByRef() ||
4449 VD->getType()->isObjCObjectPointerType() ||
4450 VD->getType()->isBlockPointerType())
4451 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004452 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004453
Daniel Dunbar56df9772010-08-17 22:39:59 +00004454 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4455 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004456
Steve Naroff30484702009-12-06 21:14:13 +00004457 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004459 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004460
Steve Naroff30484702009-12-06 21:14:13 +00004461 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004462
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004463 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004464
4465 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004466 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004467 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004468 }
Steve Naroff30484702009-12-06 21:14:13 +00004469 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4470 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004471 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004472
Steve Naroff677ab3a2008-10-27 17:20:55 +00004473 BlockDeclRefs.clear();
4474 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004475 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004476 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004477 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004478 ImportedBlockDecls.clear();
4479 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004480 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004481 // Must insert any 'const/volatile/static here. Since it has been
4482 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004483 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004484 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004485 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004486 if (GlobalVarDecl->getType().isConstQualified())
4487 SC += "const ";
4488 if (GlobalVarDecl->getType().isVolatileQualified())
4489 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004490 if (GlobalVarDecl->getType().isRestrictQualified())
4491 SC += "restrict ";
4492 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004493 }
4494
Steve Naroff677ab3a2008-10-27 17:20:55 +00004495 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004496 InnerDeclRefsCount.clear();
4497 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004498 RewrittenBlockExprs.clear();
4499}
4500
4501void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4502 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004503 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004504
Steve Naroff677ab3a2008-10-27 17:20:55 +00004505 SynthesizeBlockLiterals(FunLocStart, FuncName);
4506}
4507
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004508static void BuildUniqueMethodName(std::string &Name,
4509 ObjCMethodDecl *MD) {
4510 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004511 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004512 Name += "__" + MD->getSelector().getAsString();
4513 // Convert colons to underscores.
4514 std::string::size_type loc = 0;
4515 while ((loc = Name.find(":", loc)) != std::string::npos)
4516 Name.replace(loc, 1, "_");
4517}
4518
Steve Naroff677ab3a2008-10-27 17:20:55 +00004519void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004520 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4521 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004522 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004523 std::string FuncName;
4524 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004525 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004526}
4527
4528void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4529 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4530 CI != E; ++CI)
4531 if (*CI) {
4532 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4533 GetBlockDeclRefExprs(CBE->getBody());
4534 else
4535 GetBlockDeclRefExprs(*CI);
4536 }
4537 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004538 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004539 // FIXME: Handle enums.
4540 if (!isa<FunctionDecl>(CDRE->getDecl()))
4541 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004542 }
4543 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4544 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4545 BlockDeclRefExpr *BDRE =
4546 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4547 DRE->getLocation(), false);
4548 BlockDeclRefs.push_back(BDRE);
4549 }
4550
Steve Naroff677ab3a2008-10-27 17:20:55 +00004551 return;
4552}
4553
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004554void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4555 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004556 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004557 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4558 CI != E; ++CI)
4559 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004560 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4561 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004562 GetInnerBlockDeclRefExprs(CBE->getBody(),
4563 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004564 InnerContexts);
4565 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004566 else
4567 GetInnerBlockDeclRefExprs(*CI,
4568 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004569 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004570
4571 }
4572 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004573 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004574 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004575 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004576 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004577 }
4578 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4579 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4580 if (Var->isFunctionOrMethodVarDecl())
4581 ImportedLocalExternalDecls.insert(Var);
4582 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004583
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004584 return;
4585}
4586
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004587/// convertFunctionTypeOfBlocks - This routine converts a function type
4588/// whose result type may be a block pointer or whose argument type(s)
4589/// might be block pointers to an equivalent funtion type replacing
4590/// all block pointers to function pointers.
4591QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4592 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593 // FTP will be null for closures that don't take arguments.
4594 // Generate a funky cast.
4595 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004596 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004597 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004598
4599 if (FTP) {
4600 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4601 E = FTP->arg_type_end(); I && (I != E); ++I) {
4602 QualType t = *I;
4603 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004604 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004605 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004606 ArgTypes.push_back(t);
4607 }
4608 }
4609 QualType FuncType;
4610 // FIXME. Does this work if block takes no argument but has a return type
4611 // which is of block type?
4612 if (HasBlockType)
4613 FuncType = Context->getFunctionType(Res,
4614 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4615 false, false, 0, 0, FunctionType::ExtInfo());
4616 else FuncType = QualType(FT, 0);
4617 return FuncType;
4618}
4619
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004620Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004621 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004622 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004623
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004624 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004625 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004626 } else if (const BlockDeclRefExpr *CDRE =
4627 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004628 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004629 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004630 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004631 }
4632 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4633 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4634 }
4635 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4636 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4637 else if (const ConditionalOperator *CEXPR =
4638 dyn_cast<ConditionalOperator>(BlockExp)) {
4639 Expr *LHSExp = CEXPR->getLHS();
4640 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4641 Expr *RHSExp = CEXPR->getRHS();
4642 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4643 Expr *CONDExp = CEXPR->getCond();
4644 ConditionalOperator *CondExpr =
4645 new (Context) ConditionalOperator(CONDExp,
4646 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004647 SourceLocation(), cast<Expr>(RHSStmt),
4648 (Expr*)0,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004649 Exp->getType());
4650 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004651 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4652 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004653 } else {
4654 assert(1 && "RewriteBlockClass: Bad type");
4655 }
4656 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004657 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004658 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004659 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004660 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004661
Abramo Bagnara6150c882010-05-11 21:36:43 +00004662 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004663 SourceLocation(),
4664 &Context->Idents.get("__block_impl"));
4665 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004666
Steve Naroff350b6652008-10-30 10:07:53 +00004667 // Generate a funky cast.
4668 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004669
Steve Naroff350b6652008-10-30 10:07:53 +00004670 // Push the block argument type.
4671 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004672 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004673 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004674 E = FTP->arg_type_end(); I && (I != E); ++I) {
4675 QualType t = *I;
4676 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004677 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004678 ArgTypes.push_back(t);
4679 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680 }
Steve Naroff350b6652008-10-30 10:07:53 +00004681 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004682 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004683 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4684 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004685 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Naroff350b6652008-10-30 10:07:53 +00004687 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004688
John McCall97513962010-01-15 18:39:57 +00004689 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalle3027922010-08-25 11:45:40 +00004690 CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00004691 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004692 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004693 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4694 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004695 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004696
Douglas Gregor91f84212008-12-11 16:49:14 +00004697 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004698 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004699 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004700 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4701 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004702
John McCall97513962010-01-15 18:39:57 +00004703 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalle3027922010-08-25 11:45:40 +00004704 CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004705 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004706
Steve Naroff350b6652008-10-30 10:07:53 +00004707 llvm::SmallVector<Expr*, 8> BlkExprs;
4708 // Add the implicit argument.
4709 BlkExprs.push_back(BlkCast);
4710 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004711 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004712 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004713 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004714 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004715 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4716 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004717 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004718 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004719}
4720
Steve Naroffd9803712009-04-29 16:37:50 +00004721// We need to return the rewritten expression to handle cases where the
4722// BlockDeclRefExpr is embedded in another expression being rewritten.
4723// For example:
4724//
4725// int main() {
4726// __block Foo *f;
4727// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004728//
Steve Naroffd9803712009-04-29 16:37:50 +00004729// void (^myblock)() = ^() {
4730// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4731// i = 77;
4732// };
4733//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004734Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004735 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004736 // for each DeclRefExp where BYREFVAR is name of the variable.
4737 ValueDecl *VD;
4738 bool isArrow = true;
4739 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4740 VD = BDRE->getDecl();
4741 else {
4742 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4743 isArrow = false;
4744 }
4745
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004746 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4747 &Context->Idents.get("__forwarding"),
4748 Context->VoidPtrTy, 0,
4749 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004750 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4751 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004752 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004753
Daniel Dunbar56df9772010-08-17 22:39:59 +00004754 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004755 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4756 &Context->Idents.get(Name),
4757 Context->VoidPtrTy, 0,
4758 /*BitWidth=*/0, /*Mutable=*/true);
4759 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004760 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004761
4762
4763
Steve Narofff26a1d42009-02-02 17:19:26 +00004764 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004765 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4766 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004767 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004768 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004769}
4770
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004771// Rewrites the imported local variable V with external storage
4772// (static, extern, etc.) as *V
4773//
4774Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4775 ValueDecl *VD = DRE->getDecl();
4776 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4777 if (!ImportedLocalExternalDecls.count(Var))
4778 return DRE;
John McCalle3027922010-08-25 11:45:40 +00004779 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004780 DRE->getType(), DRE->getLocation());
4781 // Need parens to enforce precedence.
4782 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4783 Exp);
4784 ReplaceStmt(DRE, PE);
4785 return PE;
4786}
4787
Steve Naroffc989a7b2008-11-03 23:29:32 +00004788void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4789 SourceLocation LocStart = CE->getLParenLoc();
4790 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004791
4792 // Need to avoid trying to rewrite synthesized casts.
4793 if (LocStart.isInvalid())
4794 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004795 // Need to avoid trying to rewrite casts contained in macros.
4796 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4797 return;
Mike Stump11289f42009-09-09 15:08:12 +00004798
Steve Naroff677ab3a2008-10-27 17:20:55 +00004799 const char *startBuf = SM->getCharacterData(LocStart);
4800 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004801 QualType QT = CE->getType();
4802 const Type* TypePtr = QT->getAs<Type>();
4803 if (isa<TypeOfExprType>(TypePtr)) {
4804 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4805 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4806 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004807 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004808 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004809 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004810 return;
4811 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004812 // advance the location to startArgList.
4813 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004814
Steve Naroff677ab3a2008-10-27 17:20:55 +00004815 while (*argPtr++ && (argPtr < endBuf)) {
4816 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004817 case '^':
4818 // Replace the '^' with '*'.
4819 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004820 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004821 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004822 }
4823 }
4824 return;
4825}
4826
4827void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4828 SourceLocation DeclLoc = FD->getLocation();
4829 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004830
Steve Naroff677ab3a2008-10-27 17:20:55 +00004831 // We have 1 or more arguments that have closure pointers.
4832 const char *startBuf = SM->getCharacterData(DeclLoc);
4833 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004834
Steve Naroff677ab3a2008-10-27 17:20:55 +00004835 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004836
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 parenCount++;
4838 // advance the location to startArgList.
4839 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4840 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004841
Steve Naroff677ab3a2008-10-27 17:20:55 +00004842 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004843
Steve Naroff677ab3a2008-10-27 17:20:55 +00004844 while (*argPtr++ && parenCount) {
4845 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004846 case '^':
4847 // Replace the '^' with '*'.
4848 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004849 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004850 break;
4851 case '(':
4852 parenCount++;
4853 break;
4854 case ')':
4855 parenCount--;
4856 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 }
4858 }
4859 return;
4860}
4861
4862bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004863 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004864 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004865 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004866 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004867 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004868 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004869 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004870 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004871 }
4872 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004873 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004874 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004875 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004876 return true;
4877 }
4878 return false;
4879}
4880
Ted Kremenek5a201952009-02-07 01:47:29 +00004881void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4882 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004883 const char *argPtr = strchr(Name, '(');
4884 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004885
Steve Naroff677ab3a2008-10-27 17:20:55 +00004886 LParen = argPtr; // output the start.
4887 argPtr++; // skip past the left paren.
4888 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004889
Steve Naroff677ab3a2008-10-27 17:20:55 +00004890 while (*argPtr && parenCount) {
4891 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004892 case '(': parenCount++; break;
4893 case ')': parenCount--; break;
4894 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004895 }
4896 if (parenCount) argPtr++;
4897 }
4898 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4899 RParen = argPtr; // output the end
4900}
4901
4902void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4903 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4904 RewriteBlockPointerFunctionArgs(FD);
4905 return;
Mike Stump11289f42009-09-09 15:08:12 +00004906 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004907 // Handle Variables and Typedefs.
4908 SourceLocation DeclLoc = ND->getLocation();
4909 QualType DeclT;
4910 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4911 DeclT = VD->getType();
4912 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4913 DeclT = TDD->getUnderlyingType();
4914 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4915 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004916 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004917 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004918
Steve Naroff677ab3a2008-10-27 17:20:55 +00004919 const char *startBuf = SM->getCharacterData(DeclLoc);
4920 const char *endBuf = startBuf;
4921 // scan backward (from the decl location) for the end of the previous decl.
4922 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4923 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004924
Steve Naroff677ab3a2008-10-27 17:20:55 +00004925 // *startBuf != '^' if we are dealing with a pointer to function that
4926 // may take block argument types (which will be handled below).
4927 if (*startBuf == '^') {
4928 // Replace the '^' with '*', computing a negative offset.
4929 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004930 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004931 }
4932 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4933 // Replace the '^' with '*' for arguments.
4934 DeclLoc = ND->getLocation();
4935 startBuf = SM->getCharacterData(DeclLoc);
4936 const char *argListBegin, *argListEnd;
4937 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4938 while (argListBegin < argListEnd) {
4939 if (*argListBegin == '^') {
4940 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004941 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004942 }
4943 argListBegin++;
4944 }
4945 }
4946 return;
4947}
4948
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004949
4950/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4951/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4952/// struct Block_byref_id_object *src) {
4953/// _Block_object_assign (&_dest->object, _src->object,
4954/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4955/// [|BLOCK_FIELD_IS_WEAK]) // object
4956/// _Block_object_assign(&_dest->object, _src->object,
4957/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4958/// [|BLOCK_FIELD_IS_WEAK]) // block
4959/// }
4960/// And:
4961/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4962/// _Block_object_dispose(_src->object,
4963/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4964/// [|BLOCK_FIELD_IS_WEAK]) // object
4965/// _Block_object_dispose(_src->object,
4966/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4967/// [|BLOCK_FIELD_IS_WEAK]) // block
4968/// }
4969
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004970std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4971 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004972 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004973 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004974 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004975 CopyDestroyCache.insert(flag);
4976 S = "static void __Block_byref_id_object_copy_";
4977 S += utostr(flag);
4978 S += "(void *dst, void *src) {\n";
4979
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004980 // offset into the object pointer is computed as:
4981 // void * + void* + int + int + void* + void *
4982 unsigned IntSize =
4983 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4984 unsigned VoidPtrSize =
4985 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4986
4987 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4988 S += " _Block_object_assign((char*)dst + ";
4989 S += utostr(offset);
4990 S += ", *(void * *) ((char*)src + ";
4991 S += utostr(offset);
4992 S += "), ";
4993 S += utostr(flag);
4994 S += ");\n}\n";
4995
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004996 S += "static void __Block_byref_id_object_dispose_";
4997 S += utostr(flag);
4998 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004999 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5000 S += utostr(offset);
5001 S += "), ";
5002 S += utostr(flag);
5003 S += ");\n}\n";
5004 return S;
5005}
5006
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005007/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5008/// the declaration into:
5009/// struct __Block_byref_ND {
5010/// void *__isa; // NULL for everything except __weak pointers
5011/// struct __Block_byref_ND *__forwarding;
5012/// int32_t __flags;
5013/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005014/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5015/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005016/// typex ND;
5017/// };
5018///
5019/// It then replaces declaration of ND variable with:
5020/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5021/// __size=sizeof(struct __Block_byref_ND),
5022/// ND=initializer-if-any};
5023///
5024///
5025void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005026 // Insert declaration for the function in which block literal is
5027 // used.
5028 if (CurFunctionDeclToDeclareForBlock)
5029 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005030 int flag = 0;
5031 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005032 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005033 if (DeclLoc.isInvalid())
5034 // If type location is missing, it is because of missing type (a warning).
5035 // Use variable's location which is good for this case.
5036 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005037 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005038 SourceLocation X = ND->getLocEnd();
5039 X = SM->getInstantiationLoc(X);
5040 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005041 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005042 std::string ByrefType;
5043 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005044 ByrefType += " {\n";
5045 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005046 RewriteByRefString(ByrefType, Name, ND);
5047 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005048 ByrefType += " int __flags;\n";
5049 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005050 // Add void *__Block_byref_id_object_copy;
5051 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005052 QualType Ty = ND->getType();
5053 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5054 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005055 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5056 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005057 }
5058
5059 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005060 ByrefType += " " + Name + ";\n";
5061 ByrefType += "};\n";
5062 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005063 SourceLocation FunLocStart;
5064 if (CurFunctionDef)
5065 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5066 else {
5067 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5068 FunLocStart = CurMethodDef->getLocStart();
5069 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005070 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005071 if (Ty.isObjCGCWeak()) {
5072 flag |= BLOCK_FIELD_IS_WEAK;
5073 isa = 1;
5074 }
5075
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005076 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005077 flag = BLOCK_BYREF_CALLER;
5078 QualType Ty = ND->getType();
5079 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5080 if (Ty->isBlockPointerType())
5081 flag |= BLOCK_FIELD_IS_BLOCK;
5082 else
5083 flag |= BLOCK_FIELD_IS_OBJECT;
5084 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005085 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005086 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005087 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005088
5089 // struct __Block_byref_ND ND =
5090 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5091 // initializer-if-any};
5092 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005093 unsigned flags = 0;
5094 if (HasCopyAndDispose)
5095 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005096 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005097 ByrefType.clear();
5098 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005099 std::string ForwardingCastType("(");
5100 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005101 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005102 ByrefType += " " + Name + " = {(void*)";
5103 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005104 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005105 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005106 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005107 ByrefType += "sizeof(";
5108 RewriteByRefString(ByrefType, Name, ND);
5109 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005110 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005111 ByrefType += ", __Block_byref_id_object_copy_";
5112 ByrefType += utostr(flag);
5113 ByrefType += ", __Block_byref_id_object_dispose_";
5114 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005115 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005116 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005117 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005118 }
5119 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005120 SourceLocation startLoc;
5121 Expr *E = ND->getInit();
5122 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5123 startLoc = ECE->getLParenLoc();
5124 else
5125 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005126 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005127 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005128 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005129 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005130 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005131 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005132 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005133 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005134 ByrefType += "sizeof(";
5135 RewriteByRefString(ByrefType, Name, ND);
5136 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005137 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005138 ByrefType += "__Block_byref_id_object_copy_";
5139 ByrefType += utostr(flag);
5140 ByrefType += ", __Block_byref_id_object_dispose_";
5141 ByrefType += utostr(flag);
5142 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005143 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005144 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005145
5146 // Complete the newly synthesized compound expression by inserting a right
5147 // curly brace before the end of the declaration.
5148 // FIXME: This approach avoids rewriting the initializer expression. It
5149 // also assumes there is only one declarator. For example, the following
5150 // isn't currently supported by this routine (in general):
5151 //
5152 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5153 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005154 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5155 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005156 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5157 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005158 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005159
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005160 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005161 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005162 return;
5163}
5164
Mike Stump11289f42009-09-09 15:08:12 +00005165void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005166 // Add initializers for any closure decl refs.
5167 GetBlockDeclRefExprs(Exp->getBody());
5168 if (BlockDeclRefs.size()) {
5169 // Unique all "by copy" declarations.
5170 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005171 if (!BlockDeclRefs[i]->isByRef()) {
5172 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5173 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5174 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5175 }
5176 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005177 // Unique all "by ref" declarations.
5178 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5179 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005180 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5181 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5182 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5183 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005184 }
5185 // Find any imported blocks...they will need special attention.
5186 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005187 if (BlockDeclRefs[i]->isByRef() ||
5188 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005189 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005190 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005191 }
5192}
5193
Daniel Dunbar56df9772010-08-17 22:39:59 +00005194FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005195 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005196 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005197 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005198 ID, FType, 0, SC_Extern,
5199 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005200}
5201
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005202Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5203 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005204 Blocks.push_back(Exp);
5205
5206 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005207
5208 // Add inner imported variables now used in current block.
5209 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005210 if (!InnerBlockDeclRefs.empty()) {
5211 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5212 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5213 ValueDecl *VD = Exp->getDecl();
5214 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005215 // We need to save the copied-in variables in nested
5216 // blocks because it is needed at the end for some of the API generations.
5217 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005218 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5219 BlockDeclRefs.push_back(Exp);
5220 BlockByCopyDeclsPtrSet.insert(VD);
5221 BlockByCopyDecls.push_back(VD);
5222 }
5223 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5224 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5225 BlockDeclRefs.push_back(Exp);
5226 BlockByRefDeclsPtrSet.insert(VD);
5227 BlockByRefDecls.push_back(VD);
5228 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005229 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005230 // Find any imported blocks...they will need special attention.
5231 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5232 if (InnerBlockDeclRefs[i]->isByRef() ||
5233 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5234 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5235 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005236 }
5237 InnerDeclRefsCount.push_back(countOfInnerDecls);
5238
Steve Narofff4b992a2008-10-28 20:29:00 +00005239 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005240
Steve Narofff4b992a2008-10-28 20:29:00 +00005241 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005242 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005243 else if (CurMethodDef)
5244 BuildUniqueMethodName(FuncName, CurMethodDef);
5245 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005246 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005247
Steve Narofff4b992a2008-10-28 20:29:00 +00005248 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005249
Steve Narofff4b992a2008-10-28 20:29:00 +00005250 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5251 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005252
Steve Narofff4b992a2008-10-28 20:29:00 +00005253 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005254 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5255 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005256
5257 FunctionDecl *FD;
5258 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005259
Steve Narofff4b992a2008-10-28 20:29:00 +00005260 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005261 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek5a201952009-02-07 01:47:29 +00005262 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005263
Steve Narofff4b992a2008-10-28 20:29:00 +00005264 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005265
Steve Naroffe2514232008-10-29 21:23:59 +00005266 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005267 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek5a201952009-02-07 01:47:29 +00005268 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5269 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005270 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005271 CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005272 InitExprs.push_back(castExpr);
5273
Steve Naroff30484702009-12-06 21:14:13 +00005274 // Initialize the block descriptor.
5275 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005276
Steve Naroff30484702009-12-06 21:14:13 +00005277 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5278 &Context->Idents.get(DescData.c_str()),
5279 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005280 SC_Static, SC_None);
Steve Naroff30484702009-12-06 21:14:13 +00005281 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5282 new (Context) DeclRefExpr(NewVD,
5283 Context->VoidPtrTy, SourceLocation()),
John McCalle3027922010-08-25 11:45:40 +00005284 UO_AddrOf,
Steve Naroff30484702009-12-06 21:14:13 +00005285 Context->getPointerType(Context->VoidPtrTy),
5286 SourceLocation());
5287 InitExprs.push_back(DescRefExpr);
5288
Steve Narofff4b992a2008-10-28 20:29:00 +00005289 // Add initializers for any closure decl refs.
5290 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005291 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005292 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005293 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005295 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005296 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005297 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005298 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005299 if (HasLocalVariableExternalStorage(*I)) {
5300 QualType QT = (*I)->getType();
5301 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005302 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005303 SourceLocation());
5304 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005305 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005306 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005307 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005308 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalle3027922010-08-25 11:45:40 +00005309 CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005310 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005311 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005312 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005313 if (HasLocalVariableExternalStorage(*I)) {
5314 QualType QT = (*I)->getType();
5315 QT = Context->getPointerType(QT);
John McCalle3027922010-08-25 11:45:40 +00005316 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005317 SourceLocation());
5318 }
5319
Steve Narofff4b992a2008-10-28 20:29:00 +00005320 }
Mike Stump11289f42009-09-09 15:08:12 +00005321 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005322 }
5323 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005324 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005325 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005326 ValueDecl *ND = (*I);
5327 std::string Name(ND->getNameAsString());
5328 std::string RecName;
5329 RewriteByRefString(RecName, Name, ND);
5330 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5331 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005332 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005333 SourceLocation(), II);
5334 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5335 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5336
Daniel Dunbar56df9772010-08-17 22:39:59 +00005337 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek5a201952009-02-07 01:47:29 +00005338 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005339 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005340 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005341 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005342 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005343 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005344 }
5345 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005346 if (ImportedBlockDecls.size()) {
5347 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5348 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005349 unsigned IntSize =
5350 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005351 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5352 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005353 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005354 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005355 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5356 FType, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005357 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005358 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005359 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005360 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall97513962010-01-15 18:39:57 +00005361 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005362 BlockDeclRefs.clear();
5363 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005364 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005365 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005366 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005367 ImportedBlockDecls.clear();
5368 return NewRep;
5369}
5370
5371//===----------------------------------------------------------------------===//
5372// Function Body / Expression rewriting
5373//===----------------------------------------------------------------------===//
5374
Steve Naroff4588d0f2008-12-04 16:24:46 +00005375// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5376// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5377// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5378// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5379// Since the rewriter isn't capable of rewriting rewritten code, it's important
5380// we get this right.
5381void RewriteObjC::CollectPropertySetters(Stmt *S) {
5382 // Perform a bottom up traversal of all children.
5383 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5384 CI != E; ++CI)
5385 if (*CI)
5386 CollectPropertySetters(*CI);
5387
5388 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5389 if (BinOp->isAssignmentOp()) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005390 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5391 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5392 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005393 }
5394 }
5395}
5396
Steve Narofff4b992a2008-10-28 20:29:00 +00005397Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005398 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005399 isa<DoStmt>(S) || isa<ForStmt>(S))
5400 Stmts.push_back(S);
5401 else if (isa<ObjCForCollectionStmt>(S)) {
5402 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005403 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005404 }
Mike Stump11289f42009-09-09 15:08:12 +00005405
Steve Narofff4b992a2008-10-28 20:29:00 +00005406 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005407
Steve Narofff4b992a2008-10-28 20:29:00 +00005408 // Perform a bottom up rewrite of all children.
5409 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5410 CI != E; ++CI)
5411 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005412 Stmt *newStmt;
5413 Stmt *S = (*CI);
5414 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5415 Expr *OldBase = IvarRefExpr->getBase();
5416 bool replaced = false;
5417 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5418 if (replaced) {
5419 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5420 ReplaceStmt(OldBase, IRE->getBase());
5421 else
5422 ReplaceStmt(S, newStmt);
5423 }
5424 }
5425 else
5426 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005427 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005428 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005429 // If dealing with an assignment with LHS being a property reference
5430 // expression, the entire assignment tree is rewritten into a property
5431 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5432 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005433 if (Expr *Exp = dyn_cast<Expr>(S))
5434 if (isa<ObjCPropertyRefExpr>(Exp) ||
5435 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5436 if (PropSetters[Exp]) {
5437 ++CI;
5438 continue;
5439 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005440 }
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005441 }
Mike Stump11289f42009-09-09 15:08:12 +00005442
Steve Narofff4b992a2008-10-28 20:29:00 +00005443 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005444 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005445 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5446 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005447 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005448 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005449 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005450 // Rewrite the block body in place.
5451 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005452 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005453 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005454 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005455 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005456
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005457 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5458
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005460 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005461 return blockTranscribed;
5462 }
5463 // Handle specific things.
5464 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5465 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005466
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005467 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5468 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5469 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5470
5471 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005472 if (BinOp) {
5473 // Because the rewriter doesn't allow us to rewrite rewritten code,
5474 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005475 DisableReplaceStmt = true;
5476 // Save the source range. Even if we disable the replacement, the
5477 // rewritten node will have been inserted into the tree. If the synthesized
5478 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005479 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005480 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5481 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005482 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005483 // Need to rewrite the ivar access expression if need be.
5484 if (isa<ObjCIvarRefExpr>(newStmt)) {
5485 bool replaced = false;
5486 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5487 }
5488
Steve Naroff08628db2008-12-09 12:56:34 +00005489 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005490 //
5491 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5492 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5493 // to see the original expression). Consider this example:
5494 //
5495 // Foo *obj1, *obj2;
5496 //
5497 // obj1.i = [obj2 rrrr];
5498 //
5499 // 'BinOp' for the previous expression looks like:
5500 //
5501 // (BinaryOperator 0x231ccf0 'int' '='
5502 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5503 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5504 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5505 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5506 //
5507 // 'newStmt' represents the rewritten message expression. For example:
5508 //
5509 // (CallExpr 0x231d300 'id':'struct objc_object *'
5510 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5511 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5512 // (CStyleCastExpr 0x231d220 'void *'
5513 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5514 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005515 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005516 // can be used as the setter argument. ReplaceStmt() will still 'see'
5517 // the original RHS (since we haven't altered BinOp).
5518 //
Mike Stump11289f42009-09-09 15:08:12 +00005519 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005520 // node. As a result, we now leak the original AST nodes.
5521 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005522 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005523 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005524 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005525 }
5526 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005527
Steve Narofff4b992a2008-10-28 20:29:00 +00005528 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5529 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005530
Steve Narofff4b992a2008-10-28 20:29:00 +00005531 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5532 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005533
Steve Narofff4b992a2008-10-28 20:29:00 +00005534 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005535#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005536 // Before we rewrite it, put the original message expression in a comment.
5537 SourceLocation startLoc = MessExpr->getLocStart();
5538 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005539
Steve Narofff4b992a2008-10-28 20:29:00 +00005540 const char *startBuf = SM->getCharacterData(startLoc);
5541 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005542
Steve Narofff4b992a2008-10-28 20:29:00 +00005543 std::string messString;
5544 messString += "// ";
5545 messString.append(startBuf, endBuf-startBuf+1);
5546 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005547
5548 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005549 // InsertText(clang::SourceLocation, char const*, unsigned int).
5550 // InsertText(startLoc, messString.c_str(), messString.size());
5551 // Tried this, but it didn't work either...
5552 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005553#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005554 return RewriteMessageExpr(MessExpr);
5555 }
Mike Stump11289f42009-09-09 15:08:12 +00005556
Steve Narofff4b992a2008-10-28 20:29:00 +00005557 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5558 return RewriteObjCTryStmt(StmtTry);
5559
5560 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5561 return RewriteObjCSynchronizedStmt(StmtTry);
5562
5563 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5564 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005565
Steve Narofff4b992a2008-10-28 20:29:00 +00005566 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5567 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005568
5569 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005570 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005571 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005572 OrigStmtRange.getEnd());
5573 if (BreakStmt *StmtBreakStmt =
5574 dyn_cast<BreakStmt>(S))
5575 return RewriteBreakStmt(StmtBreakStmt);
5576 if (ContinueStmt *StmtContinueStmt =
5577 dyn_cast<ContinueStmt>(S))
5578 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005579
5580 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005581 // and cast exprs.
5582 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5583 // FIXME: What we're doing here is modifying the type-specifier that
5584 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005585 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005586 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5587 // the context of an ObjCForCollectionStmt. For example:
5588 // NSArray *someArray;
5589 // for (id <FooProtocol> index in someArray) ;
5590 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5591 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005592 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005593 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005594
Steve Narofff4b992a2008-10-28 20:29:00 +00005595 // Blocks rewrite rules.
5596 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5597 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005598 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005599 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005600 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005601 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005602 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005603 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005604 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005605 if (VD->hasAttr<BlocksAttr>()) {
5606 static unsigned uniqueByrefDeclCount = 0;
5607 assert(!BlockByRefDeclNo.count(ND) &&
5608 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5609 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005610 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005611 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005612 else
5613 RewriteTypeOfDecl(VD);
5614 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005615 }
5616 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005617 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005618 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005619 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005620 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5621 }
5622 }
5623 }
Mike Stump11289f42009-09-09 15:08:12 +00005624
Steve Narofff4b992a2008-10-28 20:29:00 +00005625 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5626 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005627
5628 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005629 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5630 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005631 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5632 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005633 && "Statement stack mismatch");
5634 Stmts.pop_back();
5635 }
5636 // Handle blocks rewriting.
5637 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5638 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005639 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005641 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5642 ValueDecl *VD = DRE->getDecl();
5643 if (VD->hasAttr<BlocksAttr>())
5644 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005645 if (HasLocalVariableExternalStorage(VD))
5646 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005647 }
5648
Steve Narofff4b992a2008-10-28 20:29:00 +00005649 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005650 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005651 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005652 ReplaceStmt(S, BlockCall);
5653 return BlockCall;
5654 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005655 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005656 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005657 RewriteCastExpr(CE);
5658 }
5659#if 0
5660 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005661 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5662 ICE->getSubExpr(),
5663 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005664 // Get the new text.
5665 std::string SStr;
5666 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005667 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005668 const std::string &Str = Buf.str();
5669
5670 printf("CAST = %s\n", &Str[0]);
5671 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5672 delete S;
5673 return Replacement;
5674 }
5675#endif
5676 // Return this stmt unmodified.
5677 return S;
5678}
5679
Steve Naroffe70a52a2009-12-05 15:55:59 +00005680void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5681 for (RecordDecl::field_iterator i = RD->field_begin(),
5682 e = RD->field_end(); i != e; ++i) {
5683 FieldDecl *FD = *i;
5684 if (isTopLevelBlockPointerType(FD->getType()))
5685 RewriteBlockPointerDecl(FD);
5686 if (FD->getType()->isObjCQualifiedIdType() ||
5687 FD->getType()->isObjCQualifiedInterfaceType())
5688 RewriteObjCQualifiedInterfaceTypes(FD);
5689 }
5690}
5691
Steve Narofff4b992a2008-10-28 20:29:00 +00005692/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5693/// main file of the input.
5694void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005696 if (FD->isOverloadedOperator())
5697 return;
Mike Stump11289f42009-09-09 15:08:12 +00005698
Steve Narofff4b992a2008-10-28 20:29:00 +00005699 // Since function prototypes don't have ParmDecl's, we check the function
5700 // prototype. This enables us to rewrite function declarations and
5701 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005702 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005703
Sebastian Redla7b98a72009-04-26 20:35:05 +00005704 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005705 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005706 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005707 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005708 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005709 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005710 Body =
5711 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5712 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005713 CurrentBody = 0;
5714 if (PropParentMap) {
5715 delete PropParentMap;
5716 PropParentMap = 0;
5717 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005718 // This synthesizes and inserts the block "impl" struct, invoke function,
5719 // and any copy/dispose helper functions.
5720 InsertBlockLiteralsWithinFunction(FD);
5721 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005722 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005723 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005724 return;
5725 }
5726 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005727 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005728 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005729 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005730 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005731 Body =
5732 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5733 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005734 CurrentBody = 0;
5735 if (PropParentMap) {
5736 delete PropParentMap;
5737 PropParentMap = 0;
5738 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005739 InsertBlockLiteralsWithinMethod(MD);
5740 CurMethodDef = 0;
5741 }
5742 }
5743 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5744 ClassImplementation.push_back(CI);
5745 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5746 CategoryImplementation.push_back(CI);
5747 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5748 RewriteForwardClassDecl(CD);
5749 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5750 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005751 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005752 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005753 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005754 CheckFunctionPointerDecl(VD->getType(), VD);
5755 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005756 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005757 RewriteCastExpr(CE);
5758 }
5759 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005760 } else if (VD->getType()->isRecordType()) {
5761 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5762 if (RD->isDefinition())
5763 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005764 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005765 if (VD->getInit()) {
5766 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005767 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005768 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005769 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005770 CurrentBody = 0;
5771 if (PropParentMap) {
5772 delete PropParentMap;
5773 PropParentMap = 0;
5774 }
Mike Stump11289f42009-09-09 15:08:12 +00005775 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005776 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005777 GlobalVarDecl = 0;
5778
5779 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005780 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005781 RewriteCastExpr(CE);
5782 }
5783 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005784 return;
5785 }
5786 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005787 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005788 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005789 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005790 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5791 return;
5792 }
5793 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005794 if (RD->isDefinition())
5795 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005796 return;
5797 }
5798 // Nothing yet.
5799}
5800
Chris Lattnercf169832009-03-28 04:11:33 +00005801void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005802 if (Diags.hasErrorOccurred())
5803 return;
Mike Stump11289f42009-09-09 15:08:12 +00005804
Steve Narofff4b992a2008-10-28 20:29:00 +00005805 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005806
Steve Naroffd9803712009-04-29 16:37:50 +00005807 // Here's a great place to add any extra declarations that may be needed.
5808 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005809 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005810 E = ProtocolExprDecls.end(); I != E; ++I)
5811 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5812
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005813 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005814 if (ClassImplementation.size() || CategoryImplementation.size())
5815 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005816
Steve Narofff4b992a2008-10-28 20:29:00 +00005817 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5818 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005819 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005820 Rewrite.getRewriteBufferFor(MainFileID)) {
5821 //printf("Changed:\n");
5822 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5823 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005824 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005825 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005826
Steve Naroffd9803712009-04-29 16:37:50 +00005827 if (ClassImplementation.size() || CategoryImplementation.size() ||
5828 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005829 // Rewrite Objective-c meta data*
5830 std::string ResultStr;
5831 SynthesizeMetaDataIntoBuffer(ResultStr);
5832 // Emit metadata.
5833 *OutFile << ResultStr;
5834 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005835 OutFile->flush();
5836}