blob: 0d3881197bbe92b593a75422649e35b77b51fddf [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 {
Nico Weber1879bca2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000037 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 */
Nico Weber1879bca2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000042 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000044 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
Nick Lewycky508ef2c2010-10-31 21:07:24 +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) {
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000198 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000199 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
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000407 void convertToUnqualifiedObjCType(QualType &T) {
408 if (T->isObjCQualifiedIdType())
409 T = Context->getObjCIdType();
410 else if (T->isObjCQualifiedClassType())
411 T = Context->getObjCClassType();
412 else if (T->isObjCObjectPointerType() &&
413 T->getPointeeType()->isObjCQualifiedInterfaceType())
414 T = Context->getObjCIdType();
415 }
416
Steve Naroff677ab3a2008-10-27 17:20:55 +0000417 // FIXME: This predicate seems like it would be useful to add to ASTContext.
418 bool isObjCType(QualType T) {
419 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
420 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Steve Naroff677ab3a2008-10-27 17:20:55 +0000422 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Steve Naroff677ab3a2008-10-27 17:20:55 +0000424 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
425 OCT == Context->getCanonicalType(Context->getObjCClassType()))
426 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000427
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000428 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000429 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000430 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000431 return true;
432 }
433 return false;
434 }
435 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000436 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000437 void GetExtentOfArgList(const char *Name, const char *&LParen,
438 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000439 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000440
Daniel Dunbar56df9772010-08-17 22:39:59 +0000441 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000442 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
443 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Steve Naroffd9803712009-04-29 16:37:50 +0000445 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000446 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000447 if (From[i] == '"')
448 To += "\\\"";
449 else
450 To += From[i];
451 }
452 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000453 };
John McCall97513962010-01-15 18:39:57 +0000454
455 // Helper function: create a CStyleCastExpr with trivial type source info.
456 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000457 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000458 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +0000459 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallcf142162010-08-07 06:22:56 +0000460 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000461 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000462}
463
Mike Stump11289f42009-09-09 15:08:12 +0000464void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
465 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000466 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000467 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000468 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000469 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000470 // All the args are checked/rewritten. Don't call twice!
471 RewriteBlockPointerDecl(D);
472 break;
473 }
474 }
475}
476
477void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000478 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000479 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000480 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000481}
482
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000483static bool IsHeaderFile(const std::string &Filename) {
484 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000485
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000486 if (DotPos == std::string::npos) {
487 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000488 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000489 }
Mike Stump11289f42009-09-09 15:08:12 +0000490
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000491 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
492 // C header: .h
493 // C++ header: .hh or .H;
494 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000495}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000496
Eli Friedman94cf21e2009-05-18 22:20:00 +0000497RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000498 Diagnostic &D, const LangOptions &LOpts,
499 bool silenceMacroWarn)
500 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
501 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000502 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000503 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000504 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000505 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000506 "rewriter doesn't support user-specified control flow semantics "
507 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000508}
509
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000510ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
511 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000512 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000513 const LangOptions &LOpts,
514 bool SilenceRewriteMacroWarning) {
515 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000516}
Chris Lattnere99c8322007-10-11 00:43:27 +0000517
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000518void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000519 Context = &context;
520 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000521 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000522 MsgSendFunctionDecl = 0;
523 MsgSendSuperFunctionDecl = 0;
524 MsgSendStretFunctionDecl = 0;
525 MsgSendSuperStretFunctionDecl = 0;
526 MsgSendFpretFunctionDecl = 0;
527 GetClassFunctionDecl = 0;
528 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000529 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000530 SelGetUidFunctionDecl = 0;
531 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000532 ConstantStringClassReference = 0;
533 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000534 CurMethodDef = 0;
535 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000536 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000537 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000538 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000539 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000540 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000541 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000542 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000543 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000544 PropParentMap = 0;
545 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000546 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000547 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000548
Chris Lattner187f6262008-01-31 19:38:44 +0000549 // Get the ID and start/end of the main file.
550 MainFileID = SM->getMainFileID();
551 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
552 MainFileStart = MainBuf->getBufferStart();
553 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattner184e65d2009-04-14 23:22:57 +0000555 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner187f6262008-01-31 19:38:44 +0000557 // declaring objc_selector outside the parameter list removes a silly
558 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000559 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000560 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000561 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000562 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000563 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000564 if (LangOpts.Microsoft) {
565 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000566 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
567 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000569 }
Steve Naroff00a31762008-03-27 22:29:16 +0000570 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
572 Preamble += "typedef struct objc_object Protocol;\n";
573 Preamble += "#define _REWRITER_typedef_Protocol\n";
574 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000575 if (LangOpts.Microsoft) {
576 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
577 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
578 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000579 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000583 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000585 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000586 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000587 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000588 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000589 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000591 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
593 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
597 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
599 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000601 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000602 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000603 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
604 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
605 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000606 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
607 Preamble += "struct __objcFastEnumerationState {\n\t";
608 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000609 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000610 Preamble += "unsigned long *mutationsPtr;\n\t";
611 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000613 Preamble += "#define __FASTENUMERATIONSTATE\n";
614 Preamble += "#endif\n";
615 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "struct __NSConstantStringImpl {\n";
617 Preamble += " int *isa;\n";
618 Preamble += " int flags;\n";
619 Preamble += " char *str;\n";
620 Preamble += " long length;\n";
621 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000622 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
623 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
624 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000626 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000627 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
628 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000629 // Blocks preamble.
630 Preamble += "#ifndef BLOCK_IMPL\n";
631 Preamble += "#define BLOCK_IMPL\n";
632 Preamble += "struct __block_impl {\n";
633 Preamble += " void *isa;\n";
634 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000635 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000636 Preamble += " void *FuncPtr;\n";
637 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000638 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000639 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000640 Preamble += "extern \"C\" __declspec(dllexport) "
641 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000642 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
643 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
644 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
645 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000646 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
647 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000648 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
649 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
650 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000651 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000652 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000653 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
654 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000655 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000656 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000657 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000658 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000659 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000660 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000661 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000662 Preamble += "#define __weak\n";
663 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000664 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
665 // as this avoids warning in any 64bit/32bit compilation model.
666 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000667}
668
669
Chris Lattner3c799d72007-10-24 17:06:59 +0000670//===----------------------------------------------------------------------===//
671// Top Level Driver Code
672//===----------------------------------------------------------------------===//
673
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000674void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000675 if (Diags.hasErrorOccurred())
676 return;
677
Chris Lattner0bd1c972007-10-16 21:07:07 +0000678 // Two cases: either the decl could be in the main file, or it could be in a
679 // #included file. If the former, rewrite it now. If the later, check to see
680 // if we rewrote the #include/#import.
681 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000682 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner0bd1c972007-10-16 21:07:07 +0000684 // If this is for a builtin, ignore it.
685 if (Loc.isInvalid()) return;
686
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000687 // Look for built-in declarations that we need to refer during the rewrite.
688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000689 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000690 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000691 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000692 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000693 ConstantStringClassReference = FVD;
694 return;
695 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000696 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000697 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000698 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000699 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000700 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000701 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000702 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000703 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000704 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000705 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
706 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000707 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
708 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000709 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000710 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000711 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000712 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000713 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000714 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000715}
716
Chris Lattner3c799d72007-10-24 17:06:59 +0000717//===----------------------------------------------------------------------===//
718// Syntactic (non-AST) Rewriting Code
719//===----------------------------------------------------------------------===//
720
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000721void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000722 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000723 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
724 const char *MainBufStart = MainBuf.begin();
725 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000726 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000727
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000728 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000729 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
730 if (*BufPtr == '#') {
731 if (++BufPtr == MainBufEnd)
732 return;
733 while (*BufPtr == ' ' || *BufPtr == '\t')
734 if (++BufPtr == MainBufEnd)
735 return;
736 if (!strncmp(BufPtr, "import", ImportLen)) {
737 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000738 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000739 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000740 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000741 BufPtr += ImportLen;
742 }
743 }
744 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000745}
746
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000747static std::string getIvarAccessString(ObjCIvarDecl *OID) {
748 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000749 std::string S;
750 S = "((struct ";
751 S += ClassDecl->getIdentifier()->getName();
752 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000753 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000754 return S;
755}
756
Steve Naroffc038b3a2008-12-02 17:36:43 +0000757void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
758 ObjCImplementationDecl *IMD,
759 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000760 static bool objcGetPropertyDefined = false;
761 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000762 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000763 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000764 const char *startBuf = SM->getCharacterData(startLoc);
765 assert((*startBuf == '@') && "bogus @synthesize location");
766 const char *semiBuf = strchr(startBuf, ';');
767 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000768 SourceLocation onePastSemiLoc =
769 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000770
771 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
772 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000773
Steve Naroff9af94912008-12-02 15:48:25 +0000774 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000775 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000776 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000777
Steve Naroff003d00e2008-12-02 16:05:55 +0000778 if (!OID)
779 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000780 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000781 if (!PD->getGetterMethodDecl()->isDefined()) {
782 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
783 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
784 ObjCPropertyDecl::OBJC_PR_copy));
785 std::string Getr;
786 if (GenGetProperty && !objcGetPropertyDefined) {
787 objcGetPropertyDefined = true;
788 // FIXME. Is this attribute correct in all cases?
789 Getr = "\nextern \"C\" __declspec(dllimport) "
790 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000791 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000792 RewriteObjCMethodDecl(OID->getContainingInterface(),
793 PD->getGetterMethodDecl(), Getr);
794 Getr += "{ ";
795 // Synthesize an explicit cast to gain access to the ivar.
796 // See objc-act.c:objc_synthesize_new_getter() for details.
797 if (GenGetProperty) {
798 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
799 Getr += "typedef ";
800 const FunctionType *FPRetType = 0;
801 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
802 FPRetType);
803 Getr += " _TYPE";
804 if (FPRetType) {
805 Getr += ")"; // close the precedence "scope" for "*".
806
807 // Now, emit the argument types (if any).
808 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
809 Getr += "(";
810 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
811 if (i) Getr += ", ";
812 std::string ParamStr = FT->getArgType(i).getAsString(
813 Context->PrintingPolicy);
814 Getr += ParamStr;
815 }
816 if (FT->isVariadic()) {
817 if (FT->getNumArgs()) Getr += ", ";
818 Getr += "...";
819 }
820 Getr += ")";
821 } else
822 Getr += "()";
823 }
824 Getr += ";\n";
825 Getr += "return (_TYPE)";
826 Getr += "objc_getProperty(self, _cmd, ";
827 SynthesizeIvarOffsetComputation(OID, Getr);
828 Getr += ", 1)";
829 }
830 else
831 Getr += "return " + getIvarAccessString(OID);
832 Getr += "; }";
833 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000834 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000835
836 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000837 return;
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroff9af94912008-12-02 15:48:25 +0000839 // Generate the 'setter' function.
840 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000841 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
842 ObjCPropertyDecl::OBJC_PR_copy);
843 if (GenSetProperty && !objcSetPropertyDefined) {
844 objcSetPropertyDefined = true;
845 // FIXME. Is this attribute correct in all cases?
846 Setr = "\nextern \"C\" __declspec(dllimport) "
847 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
848 }
849
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000850 RewriteObjCMethodDecl(OID->getContainingInterface(),
851 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000852 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000853 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000854 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 if (GenSetProperty) {
856 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000857 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000858 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000859 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000860 Setr += ", ";
861 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
862 Setr += "0, ";
863 else
864 Setr += "1, ";
865 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
866 Setr += "1)";
867 else
868 Setr += "0)";
869 }
870 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000871 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000872 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000873 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000874 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000875 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000876}
Chris Lattner16a0de42007-10-11 18:38:32 +0000877
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000878void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000879 // Get the start location and compute the semi location.
880 SourceLocation startLoc = ClassDecl->getLocation();
881 const char *startBuf = SM->getCharacterData(startLoc);
882 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner3c799d72007-10-24 17:06:59 +0000884 // Translate to typedef's that forward reference structs with the same name
885 // as the class. As a convenience, we include the original declaration
886 // as a comment.
887 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000888 typedefString += "// @class ";
889 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
890 I != E; ++I) {
891 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
892 typedefString += ForwardDecl->getNameAsString();
893 if (I+1 != E)
894 typedefString += ", ";
895 else
896 typedefString += ";\n";
897 }
898
Chris Lattner9ee23b72009-02-20 18:04:31 +0000899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000902 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000903 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000904 typedefString += "\n";
905 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000906 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000907 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000908 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000909 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000910 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Steve Naroff574440f2007-10-24 22:48:43 +0000913 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000914 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000915}
916
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000917void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000918 // When method is a synthesized one, such as a getter/setter there is
919 // nothing to rewrite.
920 if (Method->isSynthesized())
921 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000922 SourceLocation LocStart = Method->getLocStart();
923 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner88ea93e2009-02-04 01:06:56 +0000925 if (SM->getInstantiationLineNumber(LocEnd) >
926 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000927 InsertText(LocStart, "#if 0\n");
928 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000929 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000930 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000931 }
932}
933
Mike Stump11289f42009-09-09 15:08:12 +0000934void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000935 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000936
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000937 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000938 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000939}
940
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000941void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000942 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000943
Steve Naroff5448cf62007-10-30 13:30:57 +0000944 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000945 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000946
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000947 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
948 E = CatDecl->prop_end(); I != E; ++I)
949 RewriteProperty(*I);
950
Mike Stump11289f42009-09-09 15:08:12 +0000951 for (ObjCCategoryDecl::instmeth_iterator
952 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000953 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000954 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000956 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
959
Steve Naroff5448cf62007-10-30 13:30:57 +0000960 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000961 ReplaceText(CatDecl->getAtEndRange().getBegin(),
962 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000963}
964
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000966 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000967
Steve Narofff921385f2007-10-30 16:42:30 +0000968 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000969 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000970
971 for (ObjCProtocolDecl::instmeth_iterator
972 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000973 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000974 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000975 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000976 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
979
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000980 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
981 E = PDecl->prop_end(); I != E; ++I)
982 RewriteProperty(*I);
983
Steve Narofff921385f2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000986 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000987
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000993 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000995
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000998 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001000
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001001 }
1002 }
Steve Narofff921385f2007-10-30 16:42:30 +00001003}
1004
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
1008 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001028 ResultStr += FPRetType->getResultType().getAsString(
1029 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001030 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001031 }
1032 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001033 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001034}
1035
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001036void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001043 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001044
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001045 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001046 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregorffca3a22009-01-09 17:18:27 +00001048 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001052
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001053 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001054 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001055
1056 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001058 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001059 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001062 {
1063 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001068 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 // Rewrite arguments
1075 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001076
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001078 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001081 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001086 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001087 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 }
1089 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001090 ResultStr += Context->getObjCClassType().getAsString(
1091 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001092
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001094 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001095 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001101 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001104 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001105 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
1110 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1111 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001112 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001113 ResultStr += Name;
1114 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001115 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001118 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001119
Steve Naroffb067bbd2008-07-16 14:40:40 +00001120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001122
Steve Naroffb067bbd2008-07-16 14:40:40 +00001123 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001128 std::string ParamStr = FT->getArgType(i).getAsString(
1129 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001141}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001142void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001147
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001148 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001151 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001152 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001153 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001155 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001157
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001163 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001166 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001167 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001168 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001170 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001172
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001176 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001177 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001180 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001181 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001182 }
1183
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185}
1186
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001187void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001188 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001189 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001190 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001191 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001196 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001197 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001199 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001200 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001201 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001202 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001203 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001207 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001208 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001210 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001211 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001214 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001215 RewriteMethodDeclaration(*I);
1216
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001217 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001220}
1221
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001222Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001223 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001224 ObjCMethodDecl *OMD = 0;
1225 QualType Ty;
1226 Selector Sel;
Duncan Sands3a02f3e2010-10-20 08:21:16 +00001227 Stmt *Receiver = 0;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001228 bool Super = false;
1229 QualType SuperTy;
1230 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001231 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001232 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001233 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCallb7bd14f2010-12-02 01:19:52 +00001234 if (ObjCPropertyRefExpr *PropRefExpr =
1235 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001236 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001237 if (PropRefExpr->isExplicitProperty()) {
1238 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1239 OMD = PDecl->getSetterMethodDecl();
1240 Ty = PDecl->getType();
1241 Sel = PDecl->getSetterName();
1242 } else {
1243 OMD = PropRefExpr->getImplicitPropertySetter();
1244 Sel = OMD->getSelector();
1245 Ty = PropRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001246 }
John McCallb7bd14f2010-12-02 01:19:52 +00001247 Super = PropRefExpr->isSuperReceiver();
1248 if (!Super) {
1249 Receiver = PropRefExpr->getBase();
1250 } else {
1251 SuperTy = PropRefExpr->getSuperReceiverType();
1252 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001253 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001254 }
1255
1256 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001257 llvm::SmallVector<Expr *, 1> ExprVec;
1258 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001259
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001260 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001261 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001262 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001263 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001264 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001265 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001266 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001267 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001268 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001269 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001270 &ExprVec[0], 1,
1271 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001272 else {
1273 // FIXME. Refactor this into common code with that in
1274 // RewritePropertyOrImplicitGetter
1275 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1276 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1277 if (PropGetters[Exp])
1278 // This allows us to handle chain/nested property/implicit getters.
1279 Receiver = PropGetters[Exp];
1280
Douglas Gregor9a129192010-04-21 00:45:42 +00001281 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001282 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001283 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001284 /*FIXME: */SourceLocation(),
1285 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001286 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001287 &ExprVec[0], 1,
1288 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001289 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001290 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001291
Steve Naroff4588d0f2008-12-04 16:24:46 +00001292 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001293 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001294 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001295 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1296 // to things that stay around.
1297 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001298 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001299}
1300
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001301Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1302 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001303 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001304 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001305 ObjCMethodDecl *OMD = 0;
1306 QualType Ty;
1307 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001308 bool Super = false;
1309 QualType SuperTy;
1310 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001311 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001312 if (ObjCPropertyRefExpr *PropRefExpr =
1313 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001314 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001315 if (PropRefExpr->isExplicitProperty()) {
1316 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1317 OMD = PDecl->getGetterMethodDecl();
1318 Ty = PDecl->getType();
1319 Sel = PDecl->getGetterName();
1320 } else {
1321 OMD = PropRefExpr->getImplicitPropertyGetter();
1322 Sel = OMD->getSelector();
1323 Ty = PropRefExpr->getType();
1324 }
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001325 Super = PropRefExpr->isSuperReceiver();
1326 if (!Super)
1327 Receiver = PropRefExpr->getBase();
1328 else {
John McCallb7bd14f2010-12-02 01:19:52 +00001329 SuperTy = PropRefExpr->getSuperReceiverType();
1330 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001331 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001332 }
1333
1334 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1335
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001336 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001337 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001338 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001339 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001340 Expr::getValueKindForType(Ty),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001341 /*FIXME?*/SourceLocation(),
1342 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001343 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001344 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001345 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001346 0, 0,
1347 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001348 else {
1349 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1350 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1351 if (PropGetters[Exp])
1352 // This allows us to handle chain/nested property/implicit getters.
1353 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001354 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001355 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001356 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001357 /*FIXME:*/SourceLocation(),
1358 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001359 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001360 0, 0,
1361 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001362 }
Steve Narofff326f402008-12-03 00:56:33 +00001363
Steve Naroff22216db2008-12-04 23:50:32 +00001364 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001365
1366 if (!PropParentMap)
1367 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001368 bool NestedPropertyRef = false;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001369 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001370 ImplicitCastExpr*ICE=0;
1371 if (Parent)
1372 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1373 assert((ICE->getCastKind() == CK_GetObjCProperty)
1374 && "RewritePropertyOrImplicitGetter");
1375 Parent = PropParentMap->getParent(Parent);
1376 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1377 }
1378 if (NestedPropertyRef) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001379 // We stash away the ReplacingStmt since actually doing the
1380 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001381 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001382 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1383 // to things that stay around.
1384 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001385 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001386 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001387 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001388 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001389 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1390 // to things that stay around.
1391 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001392 return ReplacingStmt;
1393 }
Steve Narofff326f402008-12-03 00:56:33 +00001394}
1395
Mike Stump11289f42009-09-09 15:08:12 +00001396Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001397 SourceLocation OrigStart,
1398 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001399 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001400 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001401 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001402 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001403 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001404 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001405 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001406 // lookup which class implements the instance variable.
1407 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001408 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001409 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001410 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001411
Steve Naroffb1c02372008-05-08 17:52:16 +00001412 // Synthesize an explicit cast to gain access to the ivar.
1413 std::string RecName = clsDeclared->getIdentifier()->getName();
1414 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001415 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001416 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001417 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001418 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1419 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001420 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001421 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001422 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001423 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001424 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001425 IV->getBase()->getLocEnd(),
1426 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001427 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001428 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001429 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001430 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001431 IV->getLocation(),
1432 D->getType(),
1433 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001434 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001435 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001436 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001437 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001438 // Cannot delete IV->getBase(), since PE points to it.
1439 // Replace the old base with the cast. This is important when doing
1440 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001441 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001442 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001443 }
Steve Naroff24840f62008-04-18 21:55:08 +00001444 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001445 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001446
Steve Naroff29ce4e52008-05-06 23:20:07 +00001447 // Explicit ivar refs need to have a cast inserted.
1448 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001449 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001450 ObjCInterfaceType *iFaceDecl =
1451 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001452 // lookup which class implements the instance variable.
1453 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001454 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001455 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001456 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001457
Steve Naroff29ce4e52008-05-06 23:20:07 +00001458 // Synthesize an explicit cast to gain access to the ivar.
1459 std::string RecName = clsDeclared->getIdentifier()->getName();
1460 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001461 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001462 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001463 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001464 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1465 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001466 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001467 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001468 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001469 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001470 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001471 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001472 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001473 // Cannot delete IV->getBase(), since PE points to it.
1474 // Replace the old base with the cast. This is important when doing
1475 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001476 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001477 return IV;
1478 }
Steve Naroff05caa482007-11-15 11:33:00 +00001479 }
Steve Naroff24840f62008-04-18 21:55:08 +00001480 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001481}
1482
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001483Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1484 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1485 CI != E; ++CI) {
1486 if (*CI) {
1487 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1488 if (newStmt)
1489 *CI = newStmt;
1490 }
1491 }
1492 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1493 SourceRange OrigStmtRange = S->getSourceRange();
1494 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1495 replaced);
1496 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001497 }
1498 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1499 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1500 return newStmt;
1501 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001502 return S;
1503}
1504
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505/// SynthCountByEnumWithState - To print:
1506/// ((unsigned int (*)
1507/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001508/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001510/// "countByEnumeratingWithState:objects:count:"),
1511/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512/// (id *)items, (unsigned int)16)
1513///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001514void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1516 "id *, unsigned int))(void *)objc_msgSend)";
1517 buf += "\n\t\t";
1518 buf += "((id)l_collection,\n\t\t";
1519 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1520 buf += "\n\t\t";
1521 buf += "&enumState, "
1522 "(id *)items, (unsigned int)16)";
1523}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001524
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001525/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1526/// statement to exit to its outer synthesized loop.
1527///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001528Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001529 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1530 return S;
1531 // replace break with goto __break_label
1532 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534 SourceLocation startLoc = S->getLocStart();
1535 buf = "goto __break_label_";
1536 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001537 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001538
1539 return 0;
1540}
1541
1542/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1543/// statement to continue with its inner synthesized loop.
1544///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001545Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001546 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1547 return S;
1548 // replace continue with goto __continue_label
1549 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001550
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001551 SourceLocation startLoc = S->getLocStart();
1552 buf = "goto __continue_label_";
1553 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001554 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001555
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001556 return 0;
1557}
1558
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001560/// It rewrites:
1561/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001562
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001563/// Into:
1564/// {
Mike Stump11289f42009-09-09 15:08:12 +00001565/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001566/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001567/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001568/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001569/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001570/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001571/// if (limit) {
1572/// unsigned long startMutations = *enumState.mutationsPtr;
1573/// do {
1574/// unsigned long counter = 0;
1575/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001576/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001578/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001579/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001580/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001581/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001582/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001583/// objects:items count:16]);
1584/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001585/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001586/// }
1587/// else
1588/// elem = nil;
1589/// }
1590///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001591Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001592 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001593 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001594 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001595 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001596 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001597 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001598
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001599 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001600 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001601 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001602 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 std::string buf;
1604 buf = "\n{\n\t";
1605 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1606 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001607 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001608 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001609 if (ElementType->isObjCQualifiedIdType() ||
1610 ElementType->isObjCQualifiedInterfaceType())
1611 // Simply use 'id' for all qualified types.
1612 elementTypeAsString = "id";
1613 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001614 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001615 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001616 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001617 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001618 buf += elementName;
1619 buf += ";\n\t";
1620 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001621 else {
1622 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001623 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001624 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1625 if (VD->getType()->isObjCQualifiedIdType() ||
1626 VD->getType()->isObjCQualifiedInterfaceType())
1627 // Simply use 'id' for all qualified types.
1628 elementTypeAsString = "id";
1629 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001630 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001631 }
Mike Stump11289f42009-09-09 15:08:12 +00001632
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001633 // struct __objcFastEnumerationState enumState = { 0 };
1634 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1635 // id items[16];
1636 buf += "id items[16];\n\t";
1637 // id l_collection = (id)
1638 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001639 // Find start location of 'collection' the hard way!
1640 const char *startCollectionBuf = startBuf;
1641 startCollectionBuf += 3; // skip 'for'
1642 startCollectionBuf = strchr(startCollectionBuf, '(');
1643 startCollectionBuf++; // skip '('
1644 // find 'in' and skip it.
1645 while (*startCollectionBuf != ' ' ||
1646 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1647 (*(startCollectionBuf+3) != ' ' &&
1648 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1649 startCollectionBuf++;
1650 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001651
1652 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001653 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001654 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001655 SourceLocation rightParenLoc = S->getRParenLoc();
1656 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1657 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001658 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001659
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001660 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1661 // objects:items count:16];
1662 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001663 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001664 // ((unsigned int (*)
1665 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001666 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001667 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001668 // "countByEnumeratingWithState:objects:count:"),
1669 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001670 // (id *)items, (unsigned int)16);
1671 buf += "unsigned long limit =\n\t\t";
1672 SynthCountByEnumWithState(buf);
1673 buf += ";\n\t";
1674 /// if (limit) {
1675 /// unsigned long startMutations = *enumState.mutationsPtr;
1676 /// do {
1677 /// unsigned long counter = 0;
1678 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001679 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001681 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001682 buf += "if (limit) {\n\t";
1683 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1684 buf += "do {\n\t\t";
1685 buf += "unsigned long counter = 0;\n\t\t";
1686 buf += "do {\n\t\t\t";
1687 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1688 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1689 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001690 buf += " = (";
1691 buf += elementTypeAsString;
1692 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001693 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001694 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001695
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001696 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001697 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001698 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001699 /// objects:items count:16]);
1700 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001701 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001702 /// }
1703 /// else
1704 /// elem = nil;
1705 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001706 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001707 buf = ";\n\t";
1708 buf += "__continue_label_";
1709 buf += utostr(ObjCBcLabelNo.back());
1710 buf += ": ;";
1711 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001712 buf += "} while (counter < limit);\n\t";
1713 buf += "} while (limit = ";
1714 SynthCountByEnumWithState(buf);
1715 buf += ");\n\t";
1716 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001717 buf += " = ((";
1718 buf += elementTypeAsString;
1719 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001720 buf += "__break_label_";
1721 buf += utostr(ObjCBcLabelNo.back());
1722 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001723 buf += "}\n\t";
1724 buf += "else\n\t\t";
1725 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001726 buf += " = ((";
1727 buf += elementTypeAsString;
1728 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001729 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001730
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001731 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001732 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001733 if (isa<CompoundStmt>(S->getBody())) {
1734 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001735 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001736 } else {
1737 /* Need to treat single statements specially. For example:
1738 *
1739 * for (A *a in b) if (stuff()) break;
1740 * for (A *a in b) xxxyy;
1741 *
1742 * The following code simply scans ahead to the semi to find the actual end.
1743 */
1744 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1745 const char *semiBuf = strchr(stmtBuf, ';');
1746 assert(semiBuf && "Can't find ';'");
1747 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001748 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001749 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001750 Stmts.pop_back();
1751 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001752 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001753}
1754
Mike Stump11289f42009-09-09 15:08:12 +00001755/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001756/// This routine rewrites @synchronized(expr) stmt;
1757/// into:
1758/// objc_sync_enter(expr);
1759/// @try stmt @finally { objc_sync_exit(expr); }
1760///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001761Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001762 // Get the start location and compute the semi location.
1763 SourceLocation startLoc = S->getLocStart();
1764 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001765
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001766 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001767
1768 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001769 buf = "objc_sync_enter((id)";
1770 const char *lparenBuf = startBuf;
1771 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001772 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001773 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1774 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001775 // been rewritten! (which implies the SourceLocation's are invalid).
1776 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001777 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001778 while (*endBuf != ')') endBuf--;
1779 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001780 buf = ");\n";
1781 // declare a new scope with two variables, _stack and _rethrow.
1782 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1783 buf += "int buf[18/*32-bit i386*/];\n";
1784 buf += "char *pointers[4];} _stack;\n";
1785 buf += "id volatile _rethrow = 0;\n";
1786 buf += "objc_exception_try_enter(&_stack);\n";
1787 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001788 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001789 startLoc = S->getSynchBody()->getLocEnd();
1790 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001791
Steve Naroffad7013b2008-08-19 13:04:19 +00001792 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001793 SourceLocation lastCurlyLoc = startLoc;
1794 buf = "}\nelse {\n";
1795 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001796 buf += "}\n";
1797 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001798 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001799
1800 std::string syncBuf;
1801 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001802 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001803 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001804 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001805 std::string syncExprBufS;
1806 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001807 syncExpr->printPretty(syncExprBuf, *Context, 0,
1808 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001809 syncBuf += syncExprBuf.str();
1810 syncBuf += ");";
1811
1812 buf += syncBuf;
1813 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001814 buf += "}\n";
1815 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001816
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001817 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001818
1819 bool hasReturns = false;
1820 HasReturnStmts(S->getSynchBody(), hasReturns);
1821 if (hasReturns)
1822 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1823
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001824 return 0;
1825}
1826
Steve Naroffec60b432009-12-05 21:43:12 +00001827void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1828{
Steve Naroff6d6da252008-12-05 17:03:39 +00001829 // Perform a bottom up traversal of all children.
1830 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1831 CI != E; ++CI)
1832 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001833 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001834
Steve Naroffec60b432009-12-05 21:43:12 +00001835 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001836 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001837 TryFinallyContainsReturnDiag);
1838 }
1839 return;
1840}
1841
Steve Naroffec60b432009-12-05 21:43:12 +00001842void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1843{
1844 // Perform a bottom up traversal of all children.
1845 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1846 CI != E; ++CI)
1847 if (*CI)
1848 HasReturnStmts(*CI, hasReturns);
1849
1850 if (isa<ReturnStmt>(S))
1851 hasReturns = true;
1852 return;
1853}
1854
1855void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1856 // Perform a bottom up traversal of all children.
1857 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1858 CI != E; ++CI)
1859 if (*CI) {
1860 RewriteTryReturnStmts(*CI);
1861 }
1862 if (isa<ReturnStmt>(S)) {
1863 SourceLocation startLoc = S->getLocStart();
1864 const char *startBuf = SM->getCharacterData(startLoc);
1865
1866 const char *semiBuf = strchr(startBuf, ';');
1867 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1868 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1869
1870 std::string buf;
1871 buf = "{ objc_exception_try_exit(&_stack); return";
1872
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001873 ReplaceText(startLoc, 6, buf);
1874 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001875 }
1876 return;
1877}
1878
1879void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1880 // Perform a bottom up traversal of all children.
1881 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1882 CI != E; ++CI)
1883 if (*CI) {
1884 RewriteSyncReturnStmts(*CI, syncExitBuf);
1885 }
1886 if (isa<ReturnStmt>(S)) {
1887 SourceLocation startLoc = S->getLocStart();
1888 const char *startBuf = SM->getCharacterData(startLoc);
1889
1890 const char *semiBuf = strchr(startBuf, ';');
1891 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1892 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1893
1894 std::string buf;
1895 buf = "{ objc_exception_try_exit(&_stack);";
1896 buf += syncExitBuf;
1897 buf += " return";
1898
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001899 ReplaceText(startLoc, 6, buf);
1900 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001901 }
1902 return;
1903}
1904
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001905Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001906 // Get the start location and compute the semi location.
1907 SourceLocation startLoc = S->getLocStart();
1908 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001909
Steve Naroffbf478ec2007-11-07 04:08:17 +00001910 assert((*startBuf == '@') && "bogus @try location");
1911
1912 std::string buf;
1913 // declare a new scope with two variables, _stack and _rethrow.
1914 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1915 buf += "int buf[18/*32-bit i386*/];\n";
1916 buf += "char *pointers[4];} _stack;\n";
1917 buf += "id volatile _rethrow = 0;\n";
1918 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001919 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001920
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001922
Steve Naroffbf478ec2007-11-07 04:08:17 +00001923 startLoc = S->getTryBody()->getLocEnd();
1924 startBuf = SM->getCharacterData(startLoc);
1925
1926 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001927
Steve Naroffbf478ec2007-11-07 04:08:17 +00001928 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001929 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001930 startLoc = startLoc.getFileLocWithOffset(1);
1931 buf = " /* @catch begin */ else {\n";
1932 buf += " id _caught = objc_exception_extract(&_stack);\n";
1933 buf += " objc_exception_try_enter (&_stack);\n";
1934 buf += " if (_setjmp(_stack.buf))\n";
1935 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1936 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001937
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001938 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001939 } else { /* no catch list */
1940 buf = "}\nelse {\n";
1941 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1942 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001943 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001944 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001945 bool sawIdTypedCatch = false;
1946 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001947 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1948 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001949 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001950
Douglas Gregor96c79492010-04-23 22:50:49 +00001951 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001952 buf = "if ("; // we are generating code for the first catch clause
1953 else
1954 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001955 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001956 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001957
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001959
Steve Naroffbf478ec2007-11-07 04:08:17 +00001960 const char *lParenLoc = strchr(startBuf, '(');
1961
Douglas Gregor96c79492010-04-23 22:50:49 +00001962 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001963 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001964 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001965 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1966 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001967 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001968 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001969 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001970
Steve Naroffedb5bc62008-02-01 20:02:07 +00001971 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001972 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001973 } else if (catchDecl) {
1974 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001975 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001976 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001977 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001978 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001979 } else if (const ObjCObjectPointerType *Ptr =
1980 t->getAs<ObjCObjectPointerType>()) {
1981 // Should be a pointer to a class.
1982 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1983 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001984 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001985 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001986 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001987 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001988 }
1989 }
1990 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001991 lastCatchBody = Catch->getCatchBody();
1992 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001993 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1994 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1995 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1996 assert((*rParenBuf == ')') && "bogus @catch paren location");
1997 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001998
Mike Stump11289f42009-09-09 15:08:12 +00001999 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00002000 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002001 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00002002 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002003 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002004 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00002005 }
2006 // Complete the catch list...
2007 if (lastCatchBody) {
2008 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002009 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2010 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002011
Steve Naroff4adbe312008-09-11 15:29:03 +00002012 // Insert the last (implicit) else clause *before* the right curly brace.
2013 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2014 buf = "} /* last catch end */\n";
2015 buf += "else {\n";
2016 buf += " _rethrow = _caught;\n";
2017 buf += " objc_exception_try_exit(&_stack);\n";
2018 buf += "} } /* @catch end */\n";
2019 if (!S->getFinallyStmt())
2020 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002021 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroffbf478ec2007-11-07 04:08:17 +00002023 // Set lastCurlyLoc
2024 lastCurlyLoc = lastCatchBody->getLocEnd();
2025 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002026 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002027 startLoc = finalStmt->getLocStart();
2028 startBuf = SM->getCharacterData(startLoc);
2029 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002030
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002031 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002032
Steve Naroffbf478ec2007-11-07 04:08:17 +00002033 Stmt *body = finalStmt->getFinallyBody();
2034 SourceLocation startLoc = body->getLocStart();
2035 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002036 assert(*SM->getCharacterData(startLoc) == '{' &&
2037 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002038 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002039 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002040
Steve Naroffbf478ec2007-11-07 04:08:17 +00002041 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002042 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002043 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002044 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroffbf478ec2007-11-07 04:08:17 +00002046 // Set lastCurlyLoc
2047 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002048
Steve Naroff6d6da252008-12-05 17:03:39 +00002049 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002050 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002051 } else { /* no finally clause - make sure we synthesize an implicit one */
2052 buf = "{ /* implicit finally clause */\n";
2053 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2054 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2055 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002056 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002057
2058 // Now check for any return/continue/go statements within the @try.
2059 // The implicit finally clause won't called if the @try contains any
2060 // jump statements.
2061 bool hasReturns = false;
2062 HasReturnStmts(S->getTryBody(), hasReturns);
2063 if (hasReturns)
2064 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002065 }
2066 // Now emit the final closing curly brace...
2067 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002068 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002069 return 0;
2070}
2071
Mike Stump11289f42009-09-09 15:08:12 +00002072// This can't be done with ReplaceStmt(S, ThrowExpr), since
2073// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002074// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002075Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002076 // Get the start location and compute the semi location.
2077 SourceLocation startLoc = S->getLocStart();
2078 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Steve Naroffa733c7f2007-11-07 15:32:26 +00002080 assert((*startBuf == '@') && "bogus @throw location");
2081
2082 std::string buf;
2083 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002084 if (S->getThrowExpr())
2085 buf = "objc_exception_throw(";
2086 else // add an implicit argument
2087 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002088
Steve Naroff29788342008-07-25 15:41:30 +00002089 // handle "@ throw" correctly.
2090 const char *wBuf = strchr(startBuf, 'w');
2091 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002092 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002093
Steve Naroffa733c7f2007-11-07 15:32:26 +00002094 const char *semiBuf = strchr(startBuf, ';');
2095 assert((*semiBuf == ';') && "@throw: can't find ';'");
2096 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002097 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002098 return 0;
2099}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002100
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002101Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002102 // Create a new string expression.
2103 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002104 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002105 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002106 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2107 StrEncoding.length(), false,StrType,
2108 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002109 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattner4431a1b2007-11-30 22:53:43 +00002111 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002112 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002113 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002114}
2115
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002116Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002117 if (!SelGetUidFunctionDecl)
2118 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002119 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2120 // Create a call to sel_registerName("selName").
2121 llvm::SmallVector<Expr*, 8> SelExprs;
2122 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002123 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002124 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002125 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002126 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002127 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2128 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002129 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002130 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002131 return SelExp;
2132}
2133
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002134CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002135 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2136 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002137 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002138 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002139
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002140 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002141 DeclRefExpr *DRE =
2142 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002143
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002144 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002145 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002146 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002147 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002148 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002149
John McCall9dd450b2009-09-21 23:43:11 +00002150 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002151
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002152 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002153 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002154 FT->getCallResultType(*Context),
2155 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002156 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002157}
2158
Steve Naroff50d42052007-11-01 13:24:47 +00002159static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2160 const char *&startRef, const char *&endRef) {
2161 while (startBuf < endBuf) {
2162 if (*startBuf == '<')
2163 startRef = startBuf; // mark the start.
2164 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002165 if (startRef && *startRef == '<') {
2166 endRef = startBuf; // mark the end.
2167 return true;
2168 }
2169 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002170 }
2171 startBuf++;
2172 }
2173 return false;
2174}
2175
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002176static void scanToNextArgument(const char *&argRef) {
2177 int angle = 0;
2178 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2179 if (*argRef == '<')
2180 angle++;
2181 else if (*argRef == '>')
2182 angle--;
2183 argRef++;
2184 }
2185 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2186}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002187
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002188bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002189 if (T->isObjCQualifiedIdType())
2190 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002191 if (const PointerType *PT = T->getAs<PointerType>()) {
2192 if (PT->getPointeeType()->isObjCQualifiedIdType())
2193 return true;
2194 }
2195 if (T->isObjCObjectPointerType()) {
2196 T = T->getPointeeType();
2197 return T->isObjCQualifiedInterfaceType();
2198 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002199 if (T->isArrayType()) {
2200 QualType ElemTy = Context->getBaseElementType(T);
2201 return needToScanForQualifiers(ElemTy);
2202 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002203 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002204}
2205
Steve Naroff873bd842008-07-29 18:15:38 +00002206void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2207 QualType Type = E->getType();
2208 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002209 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002210
Steve Naroffdbfc6932008-11-19 21:15:47 +00002211 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2212 Loc = ECE->getLParenLoc();
2213 EndLoc = ECE->getRParenLoc();
2214 } else {
2215 Loc = E->getLocStart();
2216 EndLoc = E->getLocEnd();
2217 }
2218 // This will defend against trying to rewrite synthesized expressions.
2219 if (Loc.isInvalid() || EndLoc.isInvalid())
2220 return;
2221
Steve Naroff873bd842008-07-29 18:15:38 +00002222 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002223 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002224 const char *startRef = 0, *endRef = 0;
2225 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2226 // Get the locations of the startRef, endRef.
2227 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2228 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2229 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002230 InsertText(LessLoc, "/*");
2231 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002232 }
2233 }
2234}
2235
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002236void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002237 SourceLocation Loc;
2238 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002239 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002240 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2241 Loc = VD->getLocation();
2242 Type = VD->getType();
2243 }
2244 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2245 Loc = FD->getLocation();
2246 // Check for ObjC 'id' and class types that have been adorned with protocol
2247 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002248 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002249 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002250 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002251 if (!proto)
2252 return;
2253 Type = proto->getResultType();
2254 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002255 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2256 Loc = FD->getLocation();
2257 Type = FD->getType();
2258 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002259 else
2260 return;
Mike Stump11289f42009-09-09 15:08:12 +00002261
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002262 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002263 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002264
Steve Naroff50d42052007-11-01 13:24:47 +00002265 const char *endBuf = SM->getCharacterData(Loc);
2266 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002267 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002268 startBuf--; // scan backward (from the decl location) for return type.
2269 const char *startRef = 0, *endRef = 0;
2270 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2271 // Get the locations of the startRef, endRef.
2272 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2273 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2274 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002275 InsertText(LessLoc, "/*");
2276 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002277 }
2278 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002279 if (!proto)
2280 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002281 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002282 const char *startBuf = SM->getCharacterData(Loc);
2283 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002284 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2285 if (needToScanForQualifiers(proto->getArgType(i))) {
2286 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002287
Steve Naroff50d42052007-11-01 13:24:47 +00002288 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002289 // scan forward (from the decl location) for argument types.
2290 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002291 const char *startRef = 0, *endRef = 0;
2292 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2293 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002294 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002295 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002296 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002297 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002298 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002299 InsertText(LessLoc, "/*");
2300 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002301 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002302 startBuf = ++endBuf;
2303 }
2304 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002305 // If the function name is derived from a macro expansion, then the
2306 // argument buffer will not follow the name. Need to speak with Chris.
2307 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002308 startBuf++; // scan forward (from the decl location) for argument types.
2309 startBuf++;
2310 }
Steve Naroff50d42052007-11-01 13:24:47 +00002311 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002312}
2313
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002314void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2315 QualType QT = ND->getType();
2316 const Type* TypePtr = QT->getAs<Type>();
2317 if (!isa<TypeOfExprType>(TypePtr))
2318 return;
2319 while (isa<TypeOfExprType>(TypePtr)) {
2320 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2321 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2322 TypePtr = QT->getAs<Type>();
2323 }
2324 // FIXME. This will not work for multiple declarators; as in:
2325 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002326 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002327 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2328 const char *startBuf = SM->getCharacterData(DeclLoc);
2329 if (ND->getInit()) {
2330 std::string Name(ND->getNameAsString());
2331 TypeAsString += " " + Name + " = ";
2332 Expr *E = ND->getInit();
2333 SourceLocation startLoc;
2334 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2335 startLoc = ECE->getLParenLoc();
2336 else
2337 startLoc = E->getLocStart();
2338 startLoc = SM->getInstantiationLoc(startLoc);
2339 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002340 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002341 }
2342 else {
2343 SourceLocation X = ND->getLocEnd();
2344 X = SM->getInstantiationLoc(X);
2345 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002346 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002347 }
2348}
2349
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002350// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002351void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002352 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2353 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002354 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002355 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002356 &ArgTys[0], ArgTys.size(),
2357 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002358 false, false, 0, 0,
2359 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002360 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002361 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002362 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002363 SC_Extern,
2364 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002365}
2366
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002367void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002368 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002369 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002370 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002371 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002372 return;
2373 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002374 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002375}
2376
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002377void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2378 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002379 const char *argPtr = TypeString.c_str();
2380 if (!strchr(argPtr, '^')) {
2381 Str += TypeString;
2382 return;
2383 }
2384 while (*argPtr) {
2385 Str += (*argPtr == '^' ? '*' : *argPtr);
2386 argPtr++;
2387 }
2388}
2389
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002390// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002391void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2392 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002393 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002394 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002395 const char *argPtr = TypeString.c_str();
2396 int paren = 0;
2397 while (*argPtr) {
2398 switch (*argPtr) {
2399 case '(':
2400 Str += *argPtr;
2401 paren++;
2402 break;
2403 case ')':
2404 Str += *argPtr;
2405 paren--;
2406 break;
2407 case '^':
2408 Str += '*';
2409 if (paren == 1)
2410 Str += VD->getNameAsString();
2411 break;
2412 default:
2413 Str += *argPtr;
2414 break;
2415 }
2416 argPtr++;
2417 }
2418}
2419
2420
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002421void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2422 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2423 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2424 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2425 if (!proto)
2426 return;
2427 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002428 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002429 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002430 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002431 FdStr += "(";
2432 unsigned numArgs = proto->getNumArgs();
2433 for (unsigned i = 0; i < numArgs; i++) {
2434 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002435 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002436 if (i+1 < numArgs)
2437 FdStr += ", ";
2438 }
2439 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002440 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002441 CurFunctionDeclToDeclareForBlock = 0;
2442}
2443
Steve Naroff17978c42008-03-11 17:37:02 +00002444// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002445void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002446 if (SuperContructorFunctionDecl)
2447 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002448 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002449 llvm::SmallVector<QualType, 16> ArgTys;
2450 QualType argT = Context->getObjCIdType();
2451 assert(!argT.isNull() && "Can't find 'id' type");
2452 ArgTys.push_back(argT);
2453 ArgTys.push_back(argT);
2454 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2455 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002456 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002457 false, false, 0, 0,
2458 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002459 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002460 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002461 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002462 SC_Extern,
2463 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002464}
2465
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002466// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002467void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002468 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2469 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002470 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002471 assert(!argT.isNull() && "Can't find 'id' type");
2472 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002473 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002474 assert(!argT.isNull() && "Can't find 'SEL' type");
2475 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002476 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002477 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002478 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002479 false, false, 0, 0,
2480 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002481 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002482 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002483 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002484 SC_Extern,
2485 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002486}
2487
Steve Naroff7fa2f042007-11-15 10:28:18 +00002488// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002489void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2491 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002492 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002493 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002494 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002495 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2496 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2497 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002498 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 assert(!argT.isNull() && "Can't find 'SEL' type");
2500 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002501 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002502 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002503 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002504 false, false, 0, 0,
2505 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002506 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002507 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002508 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002509 SC_Extern,
2510 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002511}
2512
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002513// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002514void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002515 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2516 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002517 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002518 assert(!argT.isNull() && "Can't find 'id' type");
2519 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002520 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002521 assert(!argT.isNull() && "Can't find 'SEL' type");
2522 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002523 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002524 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002525 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002526 false, false, 0, 0,
2527 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002528 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002529 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002530 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002531 SC_Extern,
2532 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002533}
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002536// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002537void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002538 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002539 &Context->Idents.get("objc_msgSendSuper_stret");
2540 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002541 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002542 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002543 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002544 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2545 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2546 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002547 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002548 assert(!argT.isNull() && "Can't find 'SEL' type");
2549 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002550 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002551 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002552 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002553 false, false, 0, 0,
2554 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002555 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002556 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002557 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002558 SC_Extern,
2559 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002560}
2561
Steve Naroff2e4e3852008-05-08 22:02:18 +00002562// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002563void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002564 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2565 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002566 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002567 assert(!argT.isNull() && "Can't find 'id' type");
2568 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002569 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002570 assert(!argT.isNull() && "Can't find 'SEL' type");
2571 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002572 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002573 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002574 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002575 false, false, 0, 0,
2576 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002577 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002578 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002579 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002580 SC_Extern,
2581 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002582}
2583
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002584// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002585void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002586 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2587 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002588 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002589 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002590 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002591 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002592 false, false, 0, 0,
2593 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002594 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002595 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002596 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002597 SC_Extern,
2598 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002599}
2600
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002601// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2602void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2603 IdentifierInfo *getSuperClassIdent =
2604 &Context->Idents.get("class_getSuperclass");
2605 llvm::SmallVector<QualType, 16> ArgTys;
2606 ArgTys.push_back(Context->getObjCClassType());
2607 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2608 &ArgTys[0], ArgTys.size(),
2609 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002610 false, false, 0, 0,
2611 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002612 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002613 SourceLocation(),
2614 getSuperClassIdent,
2615 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002616 SC_Extern,
2617 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002618 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002619}
2620
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002621// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002622void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002623 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2624 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002625 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002626 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002627 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002628 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002629 false, false, 0, 0,
2630 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002631 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002632 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002633 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002634 SC_Extern,
2635 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002636}
2637
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002638Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002639 QualType strType = getConstantStringStructType();
2640
2641 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002642
2643 std::string tmpName = InFileName;
2644 unsigned i;
2645 for (i=0; i < tmpName.length(); i++) {
2646 char c = tmpName.at(i);
2647 // replace any non alphanumeric characters with '_'.
2648 if (!isalpha(c) && (c < '0' || c > '9'))
2649 tmpName[i] = '_';
2650 }
2651 S += tmpName;
2652 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002653 S += utostr(NumObjCStringLiterals++);
2654
Steve Naroff00a31762008-03-27 22:29:16 +00002655 Preamble += "static __NSConstantStringImpl " + S;
2656 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2657 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002658 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002659 std::string prettyBufS;
2660 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002661 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2662 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002663 Preamble += prettyBuf.str();
2664 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002665 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002666
2667 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002668 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002669 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002670 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2671 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002672 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002673 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002674 VK_RValue, OK_Ordinary,
2675 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002676 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002677 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002678 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002679 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002680 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002681 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002682}
2683
Steve Naroff7fa2f042007-11-15 10:28:18 +00002684// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002685QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002686 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002687 SuperStructDecl = 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("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002690 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroff7fa2f042007-11-15 10:28:18 +00002692 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002693 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002694 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002695 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002696
Steve Naroff7fa2f042007-11-15 10:28:18 +00002697 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002698 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002699 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2700 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002701 FieldTypes[i], 0,
2702 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002703 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
Douglas Gregord5058122010-02-11 01:19:42 +00002706 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002707 }
2708 return Context->getTagDeclType(SuperStructDecl);
2709}
2710
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002711QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002712 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002713 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002714 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002715 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002716 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002717
Steve Naroffce8e8862008-03-15 00:55:56 +00002718 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002719 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002720 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002721 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002722 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002723 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002724 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002725 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002726
Steve Naroffce8e8862008-03-15 00:55:56 +00002727 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002728 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002729 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2730 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002731 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002732 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002733 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002734 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002735 }
2736
Douglas Gregord5058122010-02-11 01:19:42 +00002737 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002738 }
2739 return Context->getTagDeclType(ConstantStringDecl);
2740}
2741
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002742Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2743 SourceLocation StartLoc,
2744 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002745 if (!SelGetUidFunctionDecl)
2746 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002747 if (!MsgSendFunctionDecl)
2748 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002749 if (!MsgSendSuperFunctionDecl)
2750 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002751 if (!MsgSendStretFunctionDecl)
2752 SynthMsgSendStretFunctionDecl();
2753 if (!MsgSendSuperStretFunctionDecl)
2754 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002755 if (!MsgSendFpretFunctionDecl)
2756 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002757 if (!GetClassFunctionDecl)
2758 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002759 if (!GetSuperClassFunctionDecl)
2760 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002761 if (!GetMetaClassFunctionDecl)
2762 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002763
Steve Naroff7fa2f042007-11-15 10:28:18 +00002764 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002765 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2766 // May need to use objc_msgSend_stret() as well.
2767 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002768 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2769 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002770 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002771 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002772 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002773 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002774 }
Mike Stump11289f42009-09-09 15:08:12 +00002775
Steve Naroff574440f2007-10-24 22:48:43 +00002776 // Synthesize a call to objc_msgSend().
2777 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002778 switch (Exp->getReceiverKind()) {
2779 case ObjCMessageExpr::SuperClass: {
2780 MsgSendFlavor = MsgSendSuperFunctionDecl;
2781 if (MsgSendStretFlavor)
2782 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2783 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002784
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002788
Douglas Gregor9a129192010-04-21 00:45:42 +00002789 // set the receiver to self, the first argument to all methods.
2790 InitExprs.push_back(
2791 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002792 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002793 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002794 Context->getObjCIdType(),
2795 VK_RValue,
2796 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002797 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002798
Douglas Gregor9a129192010-04-21 00:45:42 +00002799 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2800 llvm::SmallVector<Expr*, 8> ClsExprs;
2801 QualType argType = Context->getPointerType(Context->CharTy);
2802 ClsExprs.push_back(StringLiteral::Create(*Context,
2803 ClassDecl->getIdentifier()->getNameStart(),
2804 ClassDecl->getIdentifier()->getLength(),
2805 false, argType, SourceLocation()));
2806 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2807 &ClsExprs[0],
2808 ClsExprs.size(),
2809 StartLoc,
2810 EndLoc);
2811 // (Class)objc_getClass("CurrentClass")
2812 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2813 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002814 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002815 ClsExprs.clear();
2816 ClsExprs.push_back(ArgExpr);
2817 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2818 &ClsExprs[0], ClsExprs.size(),
2819 StartLoc, EndLoc);
2820
2821 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2822 // To turn off a warning, type-cast to 'id'
2823 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2824 NoTypeInfoCStyleCastExpr(Context,
2825 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002826 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002827 // struct objc_super
2828 QualType superType = getSuperStructType();
2829 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002830
Douglas Gregor9a129192010-04-21 00:45:42 +00002831 if (LangOpts.Microsoft) {
2832 SynthSuperContructorFunctionDecl();
2833 // Simulate a contructor call...
2834 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002835 superType, VK_LValue,
2836 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002837 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2838 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002839 superType, VK_LValue,
2840 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002841 // The code for super is a little tricky to prevent collision with
2842 // the structure definition in the header. The rewriter has it's own
2843 // internal definition (__rw_objc_super) that is uses. This is why
2844 // we need the cast below. For example:
2845 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2846 //
John McCalle3027922010-08-25 11:45:40 +00002847 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002848 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002849 VK_RValue, OK_Ordinary,
2850 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002851 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2852 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002853 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002854 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002855 // (struct objc_super) { <exprs from above> }
2856 InitListExpr *ILE =
2857 new (Context) InitListExpr(*Context, SourceLocation(),
2858 &InitExprs[0], InitExprs.size(),
2859 SourceLocation());
2860 TypeSourceInfo *superTInfo
2861 = Context->getTrivialTypeSourceInfo(superType);
2862 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002863 superType, VK_LValue,
2864 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002865 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002866 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002867 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002868 VK_RValue, OK_Ordinary,
2869 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002870 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002871 MsgExprs.push_back(SuperRep);
2872 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002873 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002874
2875 case ObjCMessageExpr::Class: {
2876 llvm::SmallVector<Expr*, 8> ClsExprs;
2877 QualType argType = Context->getPointerType(Context->CharTy);
2878 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002879 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002880 IdentifierInfo *clsName = Class->getIdentifier();
2881 ClsExprs.push_back(StringLiteral::Create(*Context,
2882 clsName->getNameStart(),
2883 clsName->getLength(),
2884 false, argType,
2885 SourceLocation()));
2886 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2887 &ClsExprs[0],
2888 ClsExprs.size(),
2889 StartLoc, EndLoc);
2890 MsgExprs.push_back(Cls);
2891 break;
2892 }
2893
2894 case ObjCMessageExpr::SuperInstance:{
2895 MsgSendFlavor = MsgSendSuperFunctionDecl;
2896 if (MsgSendStretFlavor)
2897 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2898 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2899 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2900 llvm::SmallVector<Expr*, 4> InitExprs;
2901
2902 InitExprs.push_back(
2903 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002904 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002905 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002906 Context->getObjCIdType(),
2907 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002908 ); // set the 'receiver'.
2909
2910 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2911 llvm::SmallVector<Expr*, 8> ClsExprs;
2912 QualType argType = Context->getPointerType(Context->CharTy);
2913 ClsExprs.push_back(StringLiteral::Create(*Context,
2914 ClassDecl->getIdentifier()->getNameStart(),
2915 ClassDecl->getIdentifier()->getLength(),
2916 false, argType, SourceLocation()));
2917 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2918 &ClsExprs[0],
2919 ClsExprs.size(),
2920 StartLoc, EndLoc);
2921 // (Class)objc_getClass("CurrentClass")
2922 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2923 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002924 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002925 ClsExprs.clear();
2926 ClsExprs.push_back(ArgExpr);
2927 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2928 &ClsExprs[0], ClsExprs.size(),
2929 StartLoc, EndLoc);
2930
2931 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2932 // To turn off a warning, type-cast to 'id'
2933 InitExprs.push_back(
2934 // set 'super class', using class_getSuperclass().
2935 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002936 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002937 // struct objc_super
2938 QualType superType = getSuperStructType();
2939 Expr *SuperRep;
2940
2941 if (LangOpts.Microsoft) {
2942 SynthSuperContructorFunctionDecl();
2943 // Simulate a contructor call...
2944 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002945 superType, VK_LValue,
2946 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002947 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2948 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002949 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002950 // The code for super is a little tricky to prevent collision with
2951 // the structure definition in the header. The rewriter has it's own
2952 // internal definition (__rw_objc_super) that is uses. This is why
2953 // we need the cast below. For example:
2954 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2955 //
John McCalle3027922010-08-25 11:45:40 +00002956 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002957 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002958 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002959 SourceLocation());
2960 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2961 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002962 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002963 } else {
2964 // (struct objc_super) { <exprs from above> }
2965 InitListExpr *ILE =
2966 new (Context) InitListExpr(*Context, SourceLocation(),
2967 &InitExprs[0], InitExprs.size(),
2968 SourceLocation());
2969 TypeSourceInfo *superTInfo
2970 = Context->getTrivialTypeSourceInfo(superType);
2971 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002972 superType, VK_RValue, ILE,
2973 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002974 }
2975 MsgExprs.push_back(SuperRep);
2976 break;
2977 }
2978
2979 case ObjCMessageExpr::Instance: {
2980 // Remove all type-casts because it may contain objc-style types; e.g.
2981 // Foo<Proto> *.
2982 Expr *recExpr = Exp->getInstanceReceiver();
2983 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2984 recExpr = CE->getSubExpr();
2985 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002986 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002987 MsgExprs.push_back(recExpr);
2988 break;
2989 }
2990 }
2991
Steve Naroffa397efd2007-11-03 11:27:19 +00002992 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002993 llvm::SmallVector<Expr*, 8> SelExprs;
2994 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002995 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002996 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002997 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002998 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003000 &SelExprs[0], SelExprs.size(),
3001 StartLoc,
3002 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00003003 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00003004
Steve Naroff574440f2007-10-24 22:48:43 +00003005 // Now push any user supplied arguments.
3006 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00003007 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00003008 // Make all implicit casts explicit...ICE comes in handy:-)
3009 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3010 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00003011 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003012 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00003013 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003014 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003015 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00003016 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003017 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003018 }
3019 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00003020 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003021 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003022 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003023 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003024 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003025 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003026 }
Mike Stump11289f42009-09-09 15:08:12 +00003027 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003028 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003029 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3030 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003031 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003032 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003033 }
Steve Narofff36987c2007-11-04 22:37:50 +00003034 // Generate the funky cast.
3035 CastExpr *cast;
3036 llvm::SmallVector<QualType, 8> ArgTypes;
3037 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003038
Steve Narofff36987c2007-11-04 22:37:50 +00003039 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003040 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3041 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3042 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003043 ArgTypes.push_back(Context->getObjCIdType());
3044 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003045 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003046 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003047 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3048 E = OMD->param_end(); PI != E; ++PI) {
3049 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003050 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003051 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003052 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003053 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003054 ArgTypes.push_back(t);
3055 }
Chris Lattnera4997152009-02-20 18:43:26 +00003056 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3057 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003058 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003059 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003060 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003061 }
3062 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003063 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003064
Steve Narofff36987c2007-11-04 22:37:50 +00003065 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003066 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003067 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003068
Mike Stump11289f42009-09-09 15:08:12 +00003069 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003070 // If we don't do this cast, we get the following bizarre warning/note:
3071 // xx.m:13: warning: function called through a non-compatible type
3072 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003073 cast = NoTypeInfoCStyleCastExpr(Context,
3074 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003075 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003076
Steve Narofff36987c2007-11-04 22:37:50 +00003077 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003078 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003079 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003080 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003081 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003082 false, false, 0, 0,
3083 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003084 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003085 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003086 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003087
3088 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003089 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003090
John McCall9dd450b2009-09-21 23:43:11 +00003091 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003092 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003093 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003094 FT->getResultType(), VK_RValue,
3095 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003096 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003097 if (MsgSendStretFlavor) {
3098 // We have the method which returns a struct/union. Must also generate
3099 // call to objc_msgSend_stret and hang both varieties on a conditional
3100 // expression which dictate which one to envoke depending on size of
3101 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003102
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003103 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003104 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003105 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003106 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003107 cast = NoTypeInfoCStyleCastExpr(Context,
3108 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003109 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003110 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003111 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003112 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003113 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003114 false, false, 0, 0,
3115 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003116 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003117 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003118 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003119
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003120 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003121 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003122
John McCall9dd450b2009-09-21 23:43:11 +00003123 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003124 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003125 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003126 FT->getResultType(), VK_RValue,
3127 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003128
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003129 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003130 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003131 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003132 Context->getSizeType(),
3133 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003134 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3135 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3136 // For X86 it is more complicated and some kind of target specific routine
3137 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003138 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003139 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003140 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3141 llvm::APInt(IntSize, 8),
3142 Context->IntTy,
3143 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003144 BinaryOperator *lessThanExpr =
3145 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3146 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003147 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003148 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003149 new (Context) ConditionalOperator(lessThanExpr,
3150 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003151 SourceLocation(), STCE, (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00003152 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003153 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3154 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003155 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003156 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003157 return ReplacingStmt;
3158}
3159
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003160Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003161 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3162 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003163
Steve Naroff574440f2007-10-24 22:48:43 +00003164 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003165 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003166
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003167 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003168 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003169}
3170
Steve Naroffd9803712009-04-29 16:37:50 +00003171// typedef struct objc_object Protocol;
3172QualType RewriteObjC::getProtocolType() {
3173 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003174 TypeSourceInfo *TInfo
3175 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003176 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003177 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003178 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003179 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003180 }
3181 return Context->getTypeDeclType(ProtocolTypeDecl);
3182}
3183
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003184/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003185/// a synthesized/forward data reference (to the protocol's metadata).
3186/// The forward references (and metadata) are generated in
3187/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003188Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003189 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3190 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003191 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003192 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003193 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003194 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3195 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003196 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003197 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003198 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003199 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003200 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003201 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003202 ReplaceStmt(Exp, castExpr);
3203 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003204 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003205 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003206
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003207}
3208
Mike Stump11289f42009-09-09 15:08:12 +00003209bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003210 const char *endBuf) {
3211 while (startBuf < endBuf) {
3212 if (*startBuf == '#') {
3213 // Skip whitespace.
3214 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3215 ;
3216 if (!strncmp(startBuf, "if", strlen("if")) ||
3217 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3218 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3219 !strncmp(startBuf, "define", strlen("define")) ||
3220 !strncmp(startBuf, "undef", strlen("undef")) ||
3221 !strncmp(startBuf, "else", strlen("else")) ||
3222 !strncmp(startBuf, "elif", strlen("elif")) ||
3223 !strncmp(startBuf, "endif", strlen("endif")) ||
3224 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3225 !strncmp(startBuf, "include", strlen("include")) ||
3226 !strncmp(startBuf, "import", strlen("import")) ||
3227 !strncmp(startBuf, "include_next", strlen("include_next")))
3228 return true;
3229 }
3230 startBuf++;
3231 }
3232 return false;
3233}
3234
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003235/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003236/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003237void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003238 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003239 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003240 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003241 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003242 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003243 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003244 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003245 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003246 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003247 SourceLocation LocStart = CDecl->getLocStart();
3248 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003249
Steve Naroffdde78982007-11-14 19:25:57 +00003250 const char *startBuf = SM->getCharacterData(LocStart);
3251 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003252
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003253 // If no ivars and no root or if its root, directly or indirectly,
3254 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003255 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3256 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003257 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003258 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003259 return;
3260 }
Mike Stump11289f42009-09-09 15:08:12 +00003261
3262 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003263 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003264 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003265 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003266 if (LangOpts.Microsoft)
3267 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003268
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003269 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003270 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003271 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003272 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003273 // If the buffer contains preprocessor directives, we do more fine-grained
3274 // rewrites. This is intended to fix code that looks like (which occurs in
3275 // NSURL.h, for example):
3276 //
3277 // #ifdef XYZ
3278 // @interface Foo : NSObject
3279 // #else
3280 // @interface FooBar : NSObject
3281 // #endif
3282 // {
3283 // int i;
3284 // }
3285 // @end
3286 //
3287 // This clause is segregated to avoid breaking the common case.
3288 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003289 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003290 CDecl->getClassLoc();
3291 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003292 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003293
Chris Lattnerf5b77512009-02-20 18:18:36 +00003294 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003295 // advance to the end of the referenced protocols.
3296 while (endHeader < cursor && *endHeader != '>') endHeader++;
3297 endHeader++;
3298 }
3299 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003300 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003301 } else {
3302 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003303 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003304 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003305 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003306 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003307 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003308 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003309 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003310 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003311
Steve Naroffdde78982007-11-14 19:25:57 +00003312 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003313 SourceLocation OnePastCurly =
3314 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003315 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003316 }
3317 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003318
Steve Naroffdde78982007-11-14 19:25:57 +00003319 // Now comment out any visibility specifiers.
3320 while (cursor < endBuf) {
3321 if (*cursor == '@') {
3322 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003323 // Skip whitespace.
3324 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3325 /*scan*/;
3326
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003327 // FIXME: presence of @public, etc. inside comment results in
3328 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003329 if (!strncmp(cursor, "public", strlen("public")) ||
3330 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003331 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003332 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003333 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003334 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003335 // FIXME: If there are cases where '<' is used in ivar declaration part
3336 // of user code, then scan the ivar list and use needToScanForQualifiers
3337 // for type checking.
3338 else if (*cursor == '<') {
3339 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003340 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003341 cursor = strchr(cursor, '>');
3342 cursor++;
3343 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003344 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003345 } else if (*cursor == '^') { // rewrite block specifier.
3346 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003347 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003348 }
Steve Naroffdde78982007-11-14 19:25:57 +00003349 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003350 }
Steve Naroffdde78982007-11-14 19:25:57 +00003351 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003352 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003353 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003354 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003355 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003356 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003357 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003358 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003359 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003360 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003361 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003362 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003363 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003364 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003365}
3366
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003367// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003368/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003369template<typename MethodIterator>
3370void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3371 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003372 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003373 llvm::StringRef prefix,
3374 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003375 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003376 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003377
Chris Lattner31bc07e2007-12-12 07:46:12 +00003378 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003379 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003380 SEL _cmd;
3381 char *method_types;
3382 void *_imp;
3383 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003384 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003385 Result += "\nstruct _objc_method {\n";
3386 Result += "\tSEL _cmd;\n";
3387 Result += "\tchar *method_types;\n";
3388 Result += "\tvoid *_imp;\n";
3389 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003390
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003391 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003392 }
Mike Stump11289f42009-09-09 15:08:12 +00003393
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003395
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003396 /* struct {
3397 struct _objc_method_list *next_method;
3398 int method_count;
3399 struct _objc_method method_list[];
3400 }
3401 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003402 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003403 Result += "\nstatic struct {\n";
3404 Result += "\tstruct _objc_method_list *next_method;\n";
3405 Result += "\tint method_count;\n";
3406 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003407 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003408 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003409 Result += prefix;
3410 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3411 Result += "_METHODS_";
3412 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003413 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003414 Result += IsInstanceMethod ? "inst" : "cls";
3415 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003416 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003417
Chris Lattner31bc07e2007-12-12 07:46:12 +00003418 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003419 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003420 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003421 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003422 Result += "\", \"";
3423 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003424 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003425 Result += MethodInternalNames[*MethodBegin];
3426 Result += "}\n";
3427 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3428 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003429 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003430 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003431 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003432 Result += "\", \"";
3433 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003434 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003435 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003436 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003437 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003438 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003439}
3440
Steve Naroffd9803712009-04-29 16:37:50 +00003441/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003442void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003443RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3444 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003445 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003446
3447 // Output struct protocol_methods holder of method selector and type.
3448 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3449 /* struct protocol_methods {
3450 SEL _cmd;
3451 char *method_types;
3452 }
3453 */
3454 Result += "\nstruct _protocol_methods {\n";
3455 Result += "\tstruct objc_selector *_cmd;\n";
3456 Result += "\tchar *method_types;\n";
3457 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003458
Steve Naroffd9803712009-04-29 16:37:50 +00003459 objc_protocol_methods = true;
3460 }
3461 // Do not synthesize the protocol more than once.
3462 if (ObjCSynthesizedProtocols.count(PDecl))
3463 return;
Mike Stump11289f42009-09-09 15:08:12 +00003464
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003465 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3466 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3467 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003468 /* struct _objc_protocol_method_list {
3469 int protocol_method_count;
3470 struct protocol_methods protocols[];
3471 }
Steve Naroff251084d2008-03-12 01:06:30 +00003472 */
Steve Naroffd9803712009-04-29 16:37:50 +00003473 Result += "\nstatic struct {\n";
3474 Result += "\tint protocol_method_count;\n";
3475 Result += "\tstruct _protocol_methods protocol_methods[";
3476 Result += utostr(NumMethods);
3477 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3478 Result += PDecl->getNameAsString();
3479 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3480 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003481
Steve Naroffd9803712009-04-29 16:37:50 +00003482 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003483 for (ObjCProtocolDecl::instmeth_iterator
3484 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003485 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003486 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003487 Result += "\t ,{{(struct objc_selector *)\"";
3488 else
3489 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003490 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003491 std::string MethodTypeString;
3492 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3493 Result += "\", \"";
3494 Result += MethodTypeString;
3495 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003496 }
Steve Naroffd9803712009-04-29 16:37:50 +00003497 Result += "\t }\n};\n";
3498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Steve Naroffd9803712009-04-29 16:37:50 +00003500 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003501 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3502 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003503 if (NumMethods > 0) {
3504 /* struct _objc_protocol_method_list {
3505 int protocol_method_count;
3506 struct protocol_methods protocols[];
3507 }
3508 */
3509 Result += "\nstatic struct {\n";
3510 Result += "\tint protocol_method_count;\n";
3511 Result += "\tstruct _protocol_methods protocol_methods[";
3512 Result += utostr(NumMethods);
3513 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3514 Result += PDecl->getNameAsString();
3515 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3516 "{\n\t";
3517 Result += utostr(NumMethods);
3518 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003519
Steve Naroffd9803712009-04-29 16:37:50 +00003520 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003521 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003522 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003523 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003524 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003525 Result += "\t ,{{(struct objc_selector *)\"";
3526 else
3527 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003528 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003529 std::string MethodTypeString;
3530 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3531 Result += "\", \"";
3532 Result += MethodTypeString;
3533 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003534 }
Steve Naroffd9803712009-04-29 16:37:50 +00003535 Result += "\t }\n};\n";
3536 }
3537
3538 // Output:
3539 /* struct _objc_protocol {
3540 // Objective-C 1.0 extensions
3541 struct _objc_protocol_extension *isa;
3542 char *protocol_name;
3543 struct _objc_protocol **protocol_list;
3544 struct _objc_protocol_method_list *instance_methods;
3545 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003546 };
Steve Naroffd9803712009-04-29 16:37:50 +00003547 */
3548 static bool objc_protocol = false;
3549 if (!objc_protocol) {
3550 Result += "\nstruct _objc_protocol {\n";
3551 Result += "\tstruct _objc_protocol_extension *isa;\n";
3552 Result += "\tchar *protocol_name;\n";
3553 Result += "\tstruct _objc_protocol **protocol_list;\n";
3554 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3555 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003556 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003557
Steve Naroffd9803712009-04-29 16:37:50 +00003558 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003559 }
Mike Stump11289f42009-09-09 15:08:12 +00003560
Steve Naroffd9803712009-04-29 16:37:50 +00003561 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3562 Result += PDecl->getNameAsString();
3563 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3564 "{\n\t0, \"";
3565 Result += PDecl->getNameAsString();
3566 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003567 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003568 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3569 Result += PDecl->getNameAsString();
3570 Result += ", ";
3571 }
3572 else
3573 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003574 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003575 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3576 Result += PDecl->getNameAsString();
3577 Result += "\n";
3578 }
3579 else
3580 Result += "0\n";
3581 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003582
Steve Naroffd9803712009-04-29 16:37:50 +00003583 // Mark this protocol as having been generated.
3584 if (!ObjCSynthesizedProtocols.insert(PDecl))
3585 assert(false && "protocol already synthesized");
3586
3587}
3588
3589void RewriteObjC::
3590RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003591 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003592 std::string &Result) {
3593 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003594
Steve Naroffd9803712009-04-29 16:37:50 +00003595 for (unsigned i = 0; i != Protocols.size(); i++)
3596 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3597
Chris Lattner388f6e92008-07-21 21:33:21 +00003598 // Output the top lovel protocol meta-data for the class.
3599 /* struct _objc_protocol_list {
3600 struct _objc_protocol_list *next;
3601 int protocol_count;
3602 struct _objc_protocol *class_protocols[];
3603 }
3604 */
3605 Result += "\nstatic struct {\n";
3606 Result += "\tstruct _objc_protocol_list *next;\n";
3607 Result += "\tint protocol_count;\n";
3608 Result += "\tstruct _objc_protocol *class_protocols[";
3609 Result += utostr(Protocols.size());
3610 Result += "];\n} _OBJC_";
3611 Result += prefix;
3612 Result += "_PROTOCOLS_";
3613 Result += ClassName;
3614 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3615 "{\n\t0, ";
3616 Result += utostr(Protocols.size());
3617 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003618
Chris Lattner388f6e92008-07-21 21:33:21 +00003619 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003620 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003621 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003622
Chris Lattner388f6e92008-07-21 21:33:21 +00003623 for (unsigned i = 1; i != Protocols.size(); i++) {
3624 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003625 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003626 Result += "\n";
3627 }
3628 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003629}
3630
Steve Naroffd9803712009-04-29 16:37:50 +00003631
Mike Stump11289f42009-09-09 15:08:12 +00003632/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003633/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003634void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003636 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003637 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003638 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003639 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003640 CDecl = CDecl->getNextClassCategory())
3641 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3642 break;
Mike Stump11289f42009-09-09 15:08:12 +00003643
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003644 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003645 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003646 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003647
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003648 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003649 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003650 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003651
3652 // If any of our property implementations have associated getters or
3653 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003654 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3655 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003656 Prop != PropEnd; ++Prop) {
3657 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3658 continue;
3659 if (!(*Prop)->getPropertyIvarDecl())
3660 continue;
3661 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3662 if (!PD)
3663 continue;
3664 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3665 InstanceMethods.push_back(Getter);
3666 if (PD->isReadOnly())
3667 continue;
3668 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3669 InstanceMethods.push_back(Setter);
3670 }
3671 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003672 true, "CATEGORY_", FullCategoryName.c_str(),
3673 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003674
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003675 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003676 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003677 false, "CATEGORY_", FullCategoryName.c_str(),
3678 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003679
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003680 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003681 // Null CDecl is case of a category implementation with no category interface
3682 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003683 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003684 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003685 /* struct _objc_category {
3686 char *category_name;
3687 char *class_name;
3688 struct _objc_method_list *instance_methods;
3689 struct _objc_method_list *class_methods;
3690 struct _objc_protocol_list *protocols;
3691 // Objective-C 1.0 extensions
3692 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003693 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003694 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003695 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003696 */
Mike Stump11289f42009-09-09 15:08:12 +00003697
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003698 static bool objc_category = false;
3699 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003700 Result += "\nstruct _objc_category {\n";
3701 Result += "\tchar *category_name;\n";
3702 Result += "\tchar *class_name;\n";
3703 Result += "\tstruct _objc_method_list *instance_methods;\n";
3704 Result += "\tstruct _objc_method_list *class_methods;\n";
3705 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003706 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003707 Result += "\tstruct _objc_property_list *instance_properties;\n";
3708 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003709 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003710 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3712 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003713 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003714 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003716 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003717 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003718
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003719 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003720 Result += "\t, (struct _objc_method_list *)"
3721 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3722 Result += FullCategoryName;
3723 Result += "\n";
3724 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003725 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003726 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003727 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003728 Result += "\t, (struct _objc_method_list *)"
3729 "&_OBJC_CATEGORY_CLASS_METHODS_";
3730 Result += FullCategoryName;
3731 Result += "\n";
3732 }
3733 else
3734 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003735
Chris Lattnerf5b77512009-02-20 18:18:36 +00003736 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003737 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003738 Result += FullCategoryName;
3739 Result += "\n";
3740 }
3741 else
3742 Result += "\t, 0\n";
3743 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003744}
3745
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003746/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3747/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003748void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003749 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003750 if (ivar->isBitField()) {
3751 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3752 // place all bitfields at offset 0.
3753 Result += "0";
3754 } else {
3755 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003756 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003757 if (LangOpts.Microsoft)
3758 Result += "_IMPL";
3759 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003760 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003761 Result += ")";
3762 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003763}
3764
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003765//===----------------------------------------------------------------------===//
3766// Meta Data Emission
3767//===----------------------------------------------------------------------===//
3768
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003769void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003770 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003771 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003772
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003773 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003774 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003775 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003776 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003777 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
Chris Lattner30d23e82007-12-12 07:56:42 +00003780 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003781 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003782 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003783 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003784 if (NumIvars > 0) {
3785 static bool objc_ivar = false;
3786 if (!objc_ivar) {
3787 /* struct _objc_ivar {
3788 char *ivar_name;
3789 char *ivar_type;
3790 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003791 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003792 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003793 Result += "\nstruct _objc_ivar {\n";
3794 Result += "\tchar *ivar_name;\n";
3795 Result += "\tchar *ivar_type;\n";
3796 Result += "\tint ivar_offset;\n";
3797 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003798
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003799 objc_ivar = true;
3800 }
3801
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003802 /* struct {
3803 int ivar_count;
3804 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003805 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003806 */
Mike Stump11289f42009-09-09 15:08:12 +00003807 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003808 Result += "\tint ivar_count;\n";
3809 Result += "\tstruct _objc_ivar ivar_list[";
3810 Result += utostr(NumIvars);
3811 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003812 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003813 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003814 "{\n\t";
3815 Result += utostr(NumIvars);
3816 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003817
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003818 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003819 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003820 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003821 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003822 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003823 IV != IVEnd; ++IV)
3824 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003825 IVI = IDecl->ivar_begin();
3826 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003827 } else {
3828 IVI = CDecl->ivar_begin();
3829 IVE = CDecl->ivar_end();
3830 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003831 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003832 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003833 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003834 std::string TmpString, StrEncoding;
3835 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3836 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003837 Result += StrEncoding;
3838 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003839 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003840 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003841 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003842 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003843 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003844 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003845 std::string TmpString, StrEncoding;
3846 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3847 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003848 Result += StrEncoding;
3849 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003850 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003851 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003852 }
Mike Stump11289f42009-09-09 15:08:12 +00003853
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003854 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003855 }
Mike Stump11289f42009-09-09 15:08:12 +00003856
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003857 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003858 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003859 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003860
3861 // If any of our property implementations have associated getters or
3862 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003863 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3864 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003865 Prop != PropEnd; ++Prop) {
3866 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3867 continue;
3868 if (!(*Prop)->getPropertyIvarDecl())
3869 continue;
3870 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3871 if (!PD)
3872 continue;
3873 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003874 if (!Getter->isDefined())
3875 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003876 if (PD->isReadOnly())
3877 continue;
3878 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003879 if (!Setter->isDefined())
3880 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003881 }
3882 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003883 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003884
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003885 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003886 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003887 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003888
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003889 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003890 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003891 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003892
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003893 // Declaration of class/meta-class metadata
3894 /* struct _objc_class {
3895 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003896 const char *super_class_name;
3897 char *name;
3898 long version;
3899 long info;
3900 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003901 struct _objc_ivar_list *ivars;
3902 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003903 struct objc_cache *cache;
3904 struct objc_protocol_list *protocols;
3905 const char *ivar_layout;
3906 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003907 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003908 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003909 static bool objc_class = false;
3910 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003911 Result += "\nstruct _objc_class {\n";
3912 Result += "\tstruct _objc_class *isa;\n";
3913 Result += "\tconst char *super_class_name;\n";
3914 Result += "\tchar *name;\n";
3915 Result += "\tlong version;\n";
3916 Result += "\tlong info;\n";
3917 Result += "\tlong instance_size;\n";
3918 Result += "\tstruct _objc_ivar_list *ivars;\n";
3919 Result += "\tstruct _objc_method_list *methods;\n";
3920 Result += "\tstruct objc_cache *cache;\n";
3921 Result += "\tstruct _objc_protocol_list *protocols;\n";
3922 Result += "\tconst char *ivar_layout;\n";
3923 Result += "\tstruct _objc_class_ext *ext;\n";
3924 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003925 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003926 }
Mike Stump11289f42009-09-09 15:08:12 +00003927
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003928 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003929 ObjCInterfaceDecl *RootClass = 0;
3930 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003931 while (SuperClass) {
3932 RootClass = SuperClass;
3933 SuperClass = SuperClass->getSuperClass();
3934 }
3935 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003936
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003937 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003938 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003939 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003940 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003941 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003942 Result += "\"";
3943
3944 if (SuperClass) {
3945 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003946 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003947 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003948 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003949 Result += "\"";
3950 }
3951 else {
3952 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003953 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003954 Result += "\"";
3955 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003956 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003957 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003958 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003959 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003960 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003961 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003962 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003963 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003964 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003965 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003966 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003967 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003969 Result += ",0,0\n";
3970 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003971 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003972 Result += "\t,0,0,0,0\n";
3973 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003974
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003975 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003976 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003977 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003978 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003979 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003980 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003981 if (SuperClass) {
3982 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003983 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003984 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003985 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003986 Result += "\"";
3987 }
3988 else {
3989 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003990 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003991 Result += "\"";
3992 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003993 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003994 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003995 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003996 Result += ",0";
3997 else {
3998 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003999 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004000 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00004001 if (LangOpts.Microsoft)
4002 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00004003 Result += ")";
4004 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004005 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00004006 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004007 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004008 Result += "\n\t";
4009 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004010 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004011 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004012 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00004013 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004014 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00004015 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004016 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004017 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004018 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00004019 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00004020 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004021 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004022 Result += ", 0,0\n";
4023 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004024 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004025 Result += ",0,0,0\n";
4026 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004027}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004028
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004029/// RewriteImplementations - This routine rewrites all method implementations
4030/// and emits meta-data.
4031
Steve Narofff8cfd162008-11-13 20:07:04 +00004032void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004033 int ClsDefCount = ClassImplementation.size();
4034 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004035
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004036 // Rewrite implemented methods
4037 for (int i = 0; i < ClsDefCount; i++)
4038 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004039
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004040 for (int i = 0; i < CatDefCount; i++)
4041 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004042}
Mike Stump11289f42009-09-09 15:08:12 +00004043
Steve Narofff8cfd162008-11-13 20:07:04 +00004044void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4045 int ClsDefCount = ClassImplementation.size();
4046 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004047
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004048 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004049 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004050 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004051
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004052 // For each implemented category, write out all its meta data.
4053 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004054 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004055
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004056 // Write objc_symtab metadata
4057 /*
4058 struct _objc_symtab
4059 {
4060 long sel_ref_cnt;
4061 SEL *refs;
4062 short cls_def_cnt;
4063 short cat_def_cnt;
4064 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004065 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004066 */
Mike Stump11289f42009-09-09 15:08:12 +00004067
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004068 Result += "\nstruct _objc_symtab {\n";
4069 Result += "\tlong sel_ref_cnt;\n";
4070 Result += "\tSEL *refs;\n";
4071 Result += "\tshort cls_def_cnt;\n";
4072 Result += "\tshort cat_def_cnt;\n";
4073 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4074 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004075
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004076 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004077 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004078 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004079 + ", " + utostr(CatDefCount) + "\n";
4080 for (int i = 0; i < ClsDefCount; i++) {
4081 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004082 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004083 Result += "\n";
4084 }
Mike Stump11289f42009-09-09 15:08:12 +00004085
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004086 for (int i = 0; i < CatDefCount; i++) {
4087 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004088 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004089 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004090 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004091 Result += "\n";
4092 }
Mike Stump11289f42009-09-09 15:08:12 +00004093
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004094 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004095
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004096 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004097
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004098 /*
4099 struct _objc_module {
4100 long version;
4101 long size;
4102 const char *name;
4103 struct _objc_symtab *symtab;
4104 }
4105 */
Mike Stump11289f42009-09-09 15:08:12 +00004106
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004107 Result += "\nstruct _objc_module {\n";
4108 Result += "\tlong version;\n";
4109 Result += "\tlong size;\n";
4110 Result += "\tconst char *name;\n";
4111 Result += "\tstruct _objc_symtab *symtab;\n";
4112 Result += "};\n\n";
4113 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004114 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004115 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004116 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004117 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004118
4119 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004120 if (ProtocolExprDecls.size()) {
4121 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4122 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004123 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004124 E = ProtocolExprDecls.end(); I != E; ++I) {
4125 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4126 Result += (*I)->getNameAsString();
4127 Result += " = &_OBJC_PROTOCOL_";
4128 Result += (*I)->getNameAsString();
4129 Result += ";\n";
4130 }
4131 Result += "#pragma data_seg(pop)\n\n";
4132 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004133 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004134 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004135 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4136 Result += "&_OBJC_MODULES;\n";
4137 Result += "#pragma data_seg(pop)\n\n";
4138 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004139}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004140
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004141void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4142 const std::string &Name,
4143 ValueDecl *VD) {
4144 assert(BlockByRefDeclNo.count(VD) &&
4145 "RewriteByRefString: ByRef decl missing");
4146 ResultStr += "struct __Block_byref_" + Name +
4147 "_" + utostr(BlockByRefDeclNo[VD]) ;
4148}
4149
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004150static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4151 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4152 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4153 return false;
4154}
4155
Steve Naroff677ab3a2008-10-27 17:20:55 +00004156std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004157 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158 std::string Tag) {
4159 const FunctionType *AFT = CE->getFunctionType();
4160 QualType RT = AFT->getResultType();
4161 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004162 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004163 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004164
Steve Naroff677ab3a2008-10-27 17:20:55 +00004165 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004166
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004167 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004168 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004169 // block (to reference imported block decl refs).
4170 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 } else if (BD->param_empty()) {
4172 S += "(" + StructRef + " *__cself)";
4173 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004174 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 assert(FT && "SynthesizeBlockFunc: No function proto");
4176 S += '(';
4177 // first add the implicit argument.
4178 S += StructRef + " *__cself, ";
4179 std::string ParamStr;
4180 for (BlockDecl::param_iterator AI = BD->param_begin(),
4181 E = BD->param_end(); AI != E; ++AI) {
4182 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004183 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004184 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004185 if (convertBlockPointerToFunctionPointer(QT))
4186 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004187 else
4188 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 S += ParamStr;
4190 }
4191 if (FT->isVariadic()) {
4192 if (!BD->param_empty()) S += ", ";
4193 S += "...";
4194 }
4195 S += ')';
4196 }
4197 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004198
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 // Create local declarations to avoid rewriting all closure decl ref exprs.
4200 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004201 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 E = BlockByRefDecls.end(); I != E; ++I) {
4203 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004204 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004205 std::string TypeString;
4206 RewriteByRefString(TypeString, Name, (*I));
4207 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004208 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004209 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004210 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004212 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 E = BlockByCopyDecls.end(); I != E; ++I) {
4214 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 // Handle nested closure invocation. For example:
4216 //
4217 // void (^myImportedClosure)(void);
4218 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004219 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 // void (^anotherClosure)(void);
4221 // anotherClosure = ^(void) {
4222 // myImportedClosure(); // import and invoke the closure
4223 // };
4224 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004225 if (isTopLevelBlockPointerType((*I)->getType())) {
4226 RewriteBlockPointerTypeVariable(S, (*I));
4227 S += " = (";
4228 RewriteBlockPointerType(S, (*I)->getType());
4229 S += ")";
4230 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4231 }
4232 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004233 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004234 QualType QT = (*I)->getType();
4235 if (HasLocalVariableExternalStorage(*I))
4236 QT = Context->getPointerType(QT);
4237 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004238 S += Name + " = __cself->" +
4239 (*I)->getNameAsString() + "; // bound by copy\n";
4240 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 }
4242 std::string RewrittenStr = RewrittenBlockExprs[CE];
4243 const char *cstr = RewrittenStr.c_str();
4244 while (*cstr++ != '{') ;
4245 S += cstr;
4246 S += "\n";
4247 return S;
4248}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004249
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004251 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252 std::string Tag) {
4253 std::string StructRef = "struct " + Tag;
4254 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004255
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 S += funcName;
4257 S += "_block_copy_" + utostr(i);
4258 S += "(" + StructRef;
4259 S += "*dst, " + StructRef;
4260 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004261 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004262 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004263 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004264 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004265 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004266 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004267 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004268 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004269 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004270 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004272 S += "}\n";
4273
Steve Naroff677ab3a2008-10-27 17:20:55 +00004274 S += "\nstatic void __";
4275 S += funcName;
4276 S += "_block_dispose_" + utostr(i);
4277 S += "(" + StructRef;
4278 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004279 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004280 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004281 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004282 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004283 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004284 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004285 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004286 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004289 return S;
4290}
4291
Steve Naroff30484702009-12-06 21:14:13 +00004292std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4293 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004294 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004296
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004298 S += " struct " + Desc;
4299 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004300
Steve Naroff30484702009-12-06 21:14:13 +00004301 Constructor += "(void *fp, "; // Invoke function pointer.
4302 Constructor += "struct " + Desc; // Descriptor pointer.
4303 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004304
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 if (BlockDeclRefs.size()) {
4306 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004307 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004308 E = BlockByCopyDecls.end(); I != E; ++I) {
4309 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004310 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 std::string ArgName = "_" + FieldName;
4312 // Handle nested closure invocation. For example:
4313 //
4314 // void (^myImportedBlock)(void);
4315 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004316 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 // void (^anotherBlock)(void);
4318 // anotherBlock = ^(void) {
4319 // myImportedBlock(); // import and invoke the closure
4320 // };
4321 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004322 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 S += "struct __block_impl *";
4324 Constructor += ", void *" + ArgName;
4325 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004326 QualType QT = (*I)->getType();
4327 if (HasLocalVariableExternalStorage(*I))
4328 QT = Context->getPointerType(QT);
4329 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4330 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004331 Constructor += ", " + ArgName;
4332 }
4333 S += FieldName + ";\n";
4334 }
4335 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004336 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 E = BlockByRefDecls.end(); I != E; ++I) {
4338 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004339 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004340 std::string ArgName = "_" + FieldName;
4341 // Handle nested closure invocation. For example:
4342 //
4343 // void (^myImportedBlock)(void);
4344 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004345 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004346 // void (^anotherBlock)(void);
4347 // anotherBlock = ^(void) {
4348 // myImportedBlock(); // import and invoke the closure
4349 // };
4350 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004351 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004352 S += "struct __block_impl *";
4353 Constructor += ", void *" + ArgName;
4354 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004355 std::string TypeString;
4356 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004357 TypeString += " *";
4358 FieldName = TypeString + FieldName;
4359 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004360 Constructor += ", " + ArgName;
4361 }
4362 S += FieldName + "; // by ref\n";
4363 }
4364 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004365 Constructor += ", int flags=0)";
4366 // Initialize all "by copy" arguments.
4367 bool firsTime = true;
4368 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4369 E = BlockByCopyDecls.end(); I != E; ++I) {
4370 std::string Name = (*I)->getNameAsString();
4371 if (firsTime) {
4372 Constructor += " : ";
4373 firsTime = false;
4374 }
4375 else
4376 Constructor += ", ";
4377 if (isTopLevelBlockPointerType((*I)->getType()))
4378 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4379 else
4380 Constructor += Name + "(_" + Name + ")";
4381 }
4382 // Initialize all "by ref" arguments.
4383 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4384 E = BlockByRefDecls.end(); I != E; ++I) {
4385 std::string Name = (*I)->getNameAsString();
4386 if (firsTime) {
4387 Constructor += " : ";
4388 firsTime = false;
4389 }
4390 else
4391 Constructor += ", ";
4392 if (isTopLevelBlockPointerType((*I)->getType()))
4393 Constructor += Name + "((struct __block_impl *)_"
4394 + Name + "->__forwarding)";
4395 else
4396 Constructor += Name + "(_" + Name + "->__forwarding)";
4397 }
4398
4399 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004400 if (GlobalVarDecl)
4401 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4402 else
4403 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004404 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004405
Steve Naroff30484702009-12-06 21:14:13 +00004406 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004407 } else {
4408 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004409 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004410 if (GlobalVarDecl)
4411 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4412 else
4413 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004414 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4415 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004416 }
4417 Constructor += " ";
4418 Constructor += "}\n";
4419 S += Constructor;
4420 S += "};\n";
4421 return S;
4422}
4423
Steve Naroff30484702009-12-06 21:14:13 +00004424std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4425 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004426 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004427 unsigned hasCopy) {
4428 std::string S = "\nstatic struct " + DescTag;
4429
4430 S += " {\n unsigned long reserved;\n";
4431 S += " unsigned long Block_size;\n";
4432 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004433 S += " void (*copy)(struct ";
4434 S += ImplTag; S += "*, struct ";
4435 S += ImplTag; S += "*);\n";
4436
4437 S += " void (*dispose)(struct ";
4438 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004439 }
4440 S += "} ";
4441
4442 S += DescTag + "_DATA = { 0, sizeof(struct ";
4443 S += ImplTag + ")";
4444 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004445 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4446 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004447 }
4448 S += "};\n";
4449 return S;
4450}
4451
Steve Naroff677ab3a2008-10-27 17:20:55 +00004452void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004453 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004454 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004455 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004456 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004457 bool RewriteSC = (GlobalVarDecl &&
4458 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004459 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004460 GlobalVarDecl->getType().getCVRQualifiers());
4461 if (RewriteSC) {
4462 std::string SC(" void __");
4463 SC += GlobalVarDecl->getNameAsString();
4464 SC += "() {}";
4465 InsertText(FunLocStart, SC);
4466 }
4467
Steve Naroff677ab3a2008-10-27 17:20:55 +00004468 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004469 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4470 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004471 // Need to copy-in the inner copied-in variables not actually used in this
4472 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004473 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4474 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4475 ValueDecl *VD = Exp->getDecl();
4476 BlockDeclRefs.push_back(Exp);
4477 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4478 BlockByCopyDeclsPtrSet.insert(VD);
4479 BlockByCopyDecls.push_back(VD);
4480 }
4481 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4482 BlockByRefDeclsPtrSet.insert(VD);
4483 BlockByRefDecls.push_back(VD);
4484 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004485 // imported objects in the inner blocks not used in the outer
4486 // blocks must be copied/disposed in the outer block as well.
4487 if (Exp->isByRef() ||
4488 VD->getType()->isObjCObjectPointerType() ||
4489 VD->getType()->isBlockPointerType())
4490 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004491 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004492
Daniel Dunbar56df9772010-08-17 22:39:59 +00004493 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4494 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004495
Steve Naroff30484702009-12-06 21:14:13 +00004496 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004497
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004498 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004499
Steve Naroff30484702009-12-06 21:14:13 +00004500 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004501
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004502 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004503
4504 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004505 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004506 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004507 }
Steve Naroff30484702009-12-06 21:14:13 +00004508 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4509 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004510 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004511
Steve Naroff677ab3a2008-10-27 17:20:55 +00004512 BlockDeclRefs.clear();
4513 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004514 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004515 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004516 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004517 ImportedBlockDecls.clear();
4518 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004519 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004520 // Must insert any 'const/volatile/static here. Since it has been
4521 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004522 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004523 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004524 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004525 if (GlobalVarDecl->getType().isConstQualified())
4526 SC += "const ";
4527 if (GlobalVarDecl->getType().isVolatileQualified())
4528 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004529 if (GlobalVarDecl->getType().isRestrictQualified())
4530 SC += "restrict ";
4531 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004532 }
4533
Steve Naroff677ab3a2008-10-27 17:20:55 +00004534 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004535 InnerDeclRefsCount.clear();
4536 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004537 RewrittenBlockExprs.clear();
4538}
4539
4540void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4541 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004542 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004543
Steve Naroff677ab3a2008-10-27 17:20:55 +00004544 SynthesizeBlockLiterals(FunLocStart, FuncName);
4545}
4546
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004547static void BuildUniqueMethodName(std::string &Name,
4548 ObjCMethodDecl *MD) {
4549 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004550 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004551 Name += "__" + MD->getSelector().getAsString();
4552 // Convert colons to underscores.
4553 std::string::size_type loc = 0;
4554 while ((loc = Name.find(":", loc)) != std::string::npos)
4555 Name.replace(loc, 1, "_");
4556}
4557
Steve Naroff677ab3a2008-10-27 17:20:55 +00004558void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004559 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4560 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004561 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004562 std::string FuncName;
4563 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004564 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004565}
4566
4567void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4568 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4569 CI != E; ++CI)
4570 if (*CI) {
4571 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4572 GetBlockDeclRefExprs(CBE->getBody());
4573 else
4574 GetBlockDeclRefExprs(*CI);
4575 }
4576 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004577 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004578 // FIXME: Handle enums.
4579 if (!isa<FunctionDecl>(CDRE->getDecl()))
4580 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004581 }
4582 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4583 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4584 BlockDeclRefExpr *BDRE =
4585 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004586 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004587 BlockDeclRefs.push_back(BDRE);
4588 }
4589
Steve Naroff677ab3a2008-10-27 17:20:55 +00004590 return;
4591}
4592
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004593void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4594 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004595 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004596 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4597 CI != E; ++CI)
4598 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004599 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4600 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004601 GetInnerBlockDeclRefExprs(CBE->getBody(),
4602 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004603 InnerContexts);
4604 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004605 else
4606 GetInnerBlockDeclRefExprs(*CI,
4607 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004608 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004609
4610 }
4611 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004612 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004613 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004614 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004615 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004616 }
4617 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4618 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4619 if (Var->isFunctionOrMethodVarDecl())
4620 ImportedLocalExternalDecls.insert(Var);
4621 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004622
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004623 return;
4624}
4625
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004626/// convertFunctionTypeOfBlocks - This routine converts a function type
4627/// whose result type may be a block pointer or whose argument type(s)
4628/// might be block pointers to an equivalent funtion type replacing
4629/// all block pointers to function pointers.
4630QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4631 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4632 // FTP will be null for closures that don't take arguments.
4633 // Generate a funky cast.
4634 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004635 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004636 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004637
4638 if (FTP) {
4639 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4640 E = FTP->arg_type_end(); I && (I != E); ++I) {
4641 QualType t = *I;
4642 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004643 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004644 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004645 ArgTypes.push_back(t);
4646 }
4647 }
4648 QualType FuncType;
4649 // FIXME. Does this work if block takes no argument but has a return type
4650 // which is of block type?
4651 if (HasBlockType)
4652 FuncType = Context->getFunctionType(Res,
4653 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4654 false, false, 0, 0, FunctionType::ExtInfo());
4655 else FuncType = QualType(FT, 0);
4656 return FuncType;
4657}
4658
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004659Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004660 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004661 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004662
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004663 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004664 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004665 } else if (const BlockDeclRefExpr *CDRE =
4666 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004667 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004668 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004669 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004670 }
4671 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4672 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4673 }
4674 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4675 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4676 else if (const ConditionalOperator *CEXPR =
4677 dyn_cast<ConditionalOperator>(BlockExp)) {
4678 Expr *LHSExp = CEXPR->getLHS();
4679 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4680 Expr *RHSExp = CEXPR->getRHS();
4681 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4682 Expr *CONDExp = CEXPR->getCond();
4683 ConditionalOperator *CondExpr =
4684 new (Context) ConditionalOperator(CONDExp,
4685 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004686 SourceLocation(), cast<Expr>(RHSStmt),
4687 (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00004688 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004689 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004690 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4691 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004692 } else {
4693 assert(1 && "RewriteBlockClass: Bad type");
4694 }
4695 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004696 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004697 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004698 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004699 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004700
Abramo Bagnara6150c882010-05-11 21:36:43 +00004701 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004702 SourceLocation(),
4703 &Context->Idents.get("__block_impl"));
4704 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004705
Steve Naroff350b6652008-10-30 10:07:53 +00004706 // Generate a funky cast.
4707 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004708
Steve Naroff350b6652008-10-30 10:07:53 +00004709 // Push the block argument type.
4710 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004711 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004712 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004713 E = FTP->arg_type_end(); I && (I != E); ++I) {
4714 QualType t = *I;
4715 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004716 if (!convertBlockPointerToFunctionPointer(t))
4717 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004718 ArgTypes.push_back(t);
4719 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004720 }
Steve Naroff350b6652008-10-30 10:07:53 +00004721 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004722 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004723 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4724 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004725 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004726
Steve Naroff350b6652008-10-30 10:07:53 +00004727 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004728
John McCall97513962010-01-15 18:39:57 +00004729 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004730 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004731 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004732 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004733 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4734 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004735 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004736
Douglas Gregor91f84212008-12-11 16:49:14 +00004737 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004738 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004739 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004740 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004741 FD->getType(), VK_LValue,
4742 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004743
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004744
John McCall97513962010-01-15 18:39:57 +00004745 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004746 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004747 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004748
Steve Naroff350b6652008-10-30 10:07:53 +00004749 llvm::SmallVector<Expr*, 8> BlkExprs;
4750 // Add the implicit argument.
4751 BlkExprs.push_back(BlkCast);
4752 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004753 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004754 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004755 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004756 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004757 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4758 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004759 Exp->getType(), VK_RValue,
4760 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004761 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004762}
4763
Steve Naroffd9803712009-04-29 16:37:50 +00004764// We need to return the rewritten expression to handle cases where the
4765// BlockDeclRefExpr is embedded in another expression being rewritten.
4766// For example:
4767//
4768// int main() {
4769// __block Foo *f;
4770// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004771//
Steve Naroffd9803712009-04-29 16:37:50 +00004772// void (^myblock)() = ^() {
4773// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4774// i = 77;
4775// };
4776//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004777Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004778 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004779 // for each DeclRefExp where BYREFVAR is name of the variable.
4780 ValueDecl *VD;
4781 bool isArrow = true;
4782 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4783 VD = BDRE->getDecl();
4784 else {
4785 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4786 isArrow = false;
4787 }
4788
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004789 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4790 &Context->Idents.get("__forwarding"),
4791 Context->VoidPtrTy, 0,
4792 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004793 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4794 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004795 FD->getType(), VK_LValue,
4796 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004797
Daniel Dunbar56df9772010-08-17 22:39:59 +00004798 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004799 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4800 &Context->Idents.get(Name),
4801 Context->VoidPtrTy, 0,
4802 /*BitWidth=*/0, /*Mutable=*/true);
4803 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004804 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004805
4806
4807
Steve Narofff26a1d42009-02-02 17:19:26 +00004808 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004809 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4810 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004811 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004812 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004813}
4814
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004815// Rewrites the imported local variable V with external storage
4816// (static, extern, etc.) as *V
4817//
4818Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4819 ValueDecl *VD = DRE->getDecl();
4820 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4821 if (!ImportedLocalExternalDecls.count(Var))
4822 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004823 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4824 VK_LValue, OK_Ordinary,
4825 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004826 // Need parens to enforce precedence.
4827 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4828 Exp);
4829 ReplaceStmt(DRE, PE);
4830 return PE;
4831}
4832
Steve Naroffc989a7b2008-11-03 23:29:32 +00004833void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4834 SourceLocation LocStart = CE->getLParenLoc();
4835 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004836
4837 // Need to avoid trying to rewrite synthesized casts.
4838 if (LocStart.isInvalid())
4839 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004840 // Need to avoid trying to rewrite casts contained in macros.
4841 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4842 return;
Mike Stump11289f42009-09-09 15:08:12 +00004843
Steve Naroff677ab3a2008-10-27 17:20:55 +00004844 const char *startBuf = SM->getCharacterData(LocStart);
4845 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004846 QualType QT = CE->getType();
4847 const Type* TypePtr = QT->getAs<Type>();
4848 if (isa<TypeOfExprType>(TypePtr)) {
4849 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4850 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4851 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004852 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004853 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004854 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004855 return;
4856 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 // advance the location to startArgList.
4858 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004859
Steve Naroff677ab3a2008-10-27 17:20:55 +00004860 while (*argPtr++ && (argPtr < endBuf)) {
4861 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004862 case '^':
4863 // Replace the '^' with '*'.
4864 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004865 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004866 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004867 }
4868 }
4869 return;
4870}
4871
4872void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4873 SourceLocation DeclLoc = FD->getLocation();
4874 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004875
Steve Naroff677ab3a2008-10-27 17:20:55 +00004876 // We have 1 or more arguments that have closure pointers.
4877 const char *startBuf = SM->getCharacterData(DeclLoc);
4878 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004879
Steve Naroff677ab3a2008-10-27 17:20:55 +00004880 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004881
Steve Naroff677ab3a2008-10-27 17:20:55 +00004882 parenCount++;
4883 // advance the location to startArgList.
4884 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4885 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004886
Steve Naroff677ab3a2008-10-27 17:20:55 +00004887 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004888
Steve Naroff677ab3a2008-10-27 17:20:55 +00004889 while (*argPtr++ && parenCount) {
4890 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004891 case '^':
4892 // Replace the '^' with '*'.
4893 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004894 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004895 break;
4896 case '(':
4897 parenCount++;
4898 break;
4899 case ')':
4900 parenCount--;
4901 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004902 }
4903 }
4904 return;
4905}
4906
4907bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004908 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004909 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004910 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004911 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004912 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004913 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004914 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004915 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004916 }
4917 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004918 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004919 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004920 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004921 return true;
4922 }
4923 return false;
4924}
4925
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004926bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4927 const FunctionProtoType *FTP;
4928 const PointerType *PT = QT->getAs<PointerType>();
4929 if (PT) {
4930 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4931 } else {
4932 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4933 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4934 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4935 }
4936 if (FTP) {
4937 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004938 E = FTP->arg_type_end(); I != E; ++I) {
4939 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004940 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004941 if ((*I)->isObjCObjectPointerType() &&
4942 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4943 return true;
4944 }
4945
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004946 }
4947 return false;
4948}
4949
Ted Kremenek5a201952009-02-07 01:47:29 +00004950void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4951 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004952 const char *argPtr = strchr(Name, '(');
4953 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004954
Steve Naroff677ab3a2008-10-27 17:20:55 +00004955 LParen = argPtr; // output the start.
4956 argPtr++; // skip past the left paren.
4957 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004958
Steve Naroff677ab3a2008-10-27 17:20:55 +00004959 while (*argPtr && parenCount) {
4960 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004961 case '(': parenCount++; break;
4962 case ')': parenCount--; break;
4963 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004964 }
4965 if (parenCount) argPtr++;
4966 }
4967 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4968 RParen = argPtr; // output the end
4969}
4970
4971void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4972 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4973 RewriteBlockPointerFunctionArgs(FD);
4974 return;
Mike Stump11289f42009-09-09 15:08:12 +00004975 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004976 // Handle Variables and Typedefs.
4977 SourceLocation DeclLoc = ND->getLocation();
4978 QualType DeclT;
4979 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4980 DeclT = VD->getType();
4981 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4982 DeclT = TDD->getUnderlyingType();
4983 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4984 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004985 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004986 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004987
Steve Naroff677ab3a2008-10-27 17:20:55 +00004988 const char *startBuf = SM->getCharacterData(DeclLoc);
4989 const char *endBuf = startBuf;
4990 // scan backward (from the decl location) for the end of the previous decl.
4991 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4992 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004993 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4994 std::string buf;
4995 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004996 // *startBuf != '^' if we are dealing with a pointer to function that
4997 // may take block argument types (which will be handled below).
4998 if (*startBuf == '^') {
4999 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005000 buf = '*';
5001 startBuf++;
5002 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005003 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005004 while (*startBuf != ')') {
5005 buf += *startBuf;
5006 startBuf++;
5007 OrigLength++;
5008 }
5009 buf += ')';
5010 OrigLength++;
5011
5012 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5013 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005014 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005015 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00005016 DeclLoc = ND->getLocation();
5017 startBuf = SM->getCharacterData(DeclLoc);
5018 const char *argListBegin, *argListEnd;
5019 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5020 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005021 if (*argListBegin == '^')
5022 buf += '*';
5023 else if (*argListBegin == '<') {
5024 buf += "/*";
5025 buf += *argListBegin++;
5026 OrigLength++;;
5027 while (*argListBegin != '>') {
5028 buf += *argListBegin++;
5029 OrigLength++;
5030 }
5031 buf += *argListBegin;
5032 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005033 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005034 else
5035 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005036 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005037 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005038 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005039 buf += ')';
5040 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005041 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005042 ReplaceText(Start, OrigLength, buf);
5043
Steve Naroff677ab3a2008-10-27 17:20:55 +00005044 return;
5045}
5046
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005047
5048/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5049/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5050/// struct Block_byref_id_object *src) {
5051/// _Block_object_assign (&_dest->object, _src->object,
5052/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5053/// [|BLOCK_FIELD_IS_WEAK]) // object
5054/// _Block_object_assign(&_dest->object, _src->object,
5055/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5056/// [|BLOCK_FIELD_IS_WEAK]) // block
5057/// }
5058/// And:
5059/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5060/// _Block_object_dispose(_src->object,
5061/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5062/// [|BLOCK_FIELD_IS_WEAK]) // object
5063/// _Block_object_dispose(_src->object,
5064/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5065/// [|BLOCK_FIELD_IS_WEAK]) // block
5066/// }
5067
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005068std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5069 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005070 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005071 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005072 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005073 CopyDestroyCache.insert(flag);
5074 S = "static void __Block_byref_id_object_copy_";
5075 S += utostr(flag);
5076 S += "(void *dst, void *src) {\n";
5077
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005078 // offset into the object pointer is computed as:
5079 // void * + void* + int + int + void* + void *
5080 unsigned IntSize =
5081 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5082 unsigned VoidPtrSize =
5083 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5084
5085 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5086 S += " _Block_object_assign((char*)dst + ";
5087 S += utostr(offset);
5088 S += ", *(void * *) ((char*)src + ";
5089 S += utostr(offset);
5090 S += "), ";
5091 S += utostr(flag);
5092 S += ");\n}\n";
5093
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005094 S += "static void __Block_byref_id_object_dispose_";
5095 S += utostr(flag);
5096 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005097 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5098 S += utostr(offset);
5099 S += "), ";
5100 S += utostr(flag);
5101 S += ");\n}\n";
5102 return S;
5103}
5104
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005105/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5106/// the declaration into:
5107/// struct __Block_byref_ND {
5108/// void *__isa; // NULL for everything except __weak pointers
5109/// struct __Block_byref_ND *__forwarding;
5110/// int32_t __flags;
5111/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005112/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5113/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005114/// typex ND;
5115/// };
5116///
5117/// It then replaces declaration of ND variable with:
5118/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5119/// __size=sizeof(struct __Block_byref_ND),
5120/// ND=initializer-if-any};
5121///
5122///
5123void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005124 // Insert declaration for the function in which block literal is
5125 // used.
5126 if (CurFunctionDeclToDeclareForBlock)
5127 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005128 int flag = 0;
5129 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005130 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005131 if (DeclLoc.isInvalid())
5132 // If type location is missing, it is because of missing type (a warning).
5133 // Use variable's location which is good for this case.
5134 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005135 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005136 SourceLocation X = ND->getLocEnd();
5137 X = SM->getInstantiationLoc(X);
5138 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005139 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005140 std::string ByrefType;
5141 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005142 ByrefType += " {\n";
5143 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005144 RewriteByRefString(ByrefType, Name, ND);
5145 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005146 ByrefType += " int __flags;\n";
5147 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005148 // Add void *__Block_byref_id_object_copy;
5149 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005150 QualType Ty = ND->getType();
5151 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5152 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005153 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5154 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005155 }
5156
5157 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005158 ByrefType += " " + Name + ";\n";
5159 ByrefType += "};\n";
5160 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005161 SourceLocation FunLocStart;
5162 if (CurFunctionDef)
5163 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5164 else {
5165 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5166 FunLocStart = CurMethodDef->getLocStart();
5167 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005168 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005169 if (Ty.isObjCGCWeak()) {
5170 flag |= BLOCK_FIELD_IS_WEAK;
5171 isa = 1;
5172 }
5173
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005174 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005175 flag = BLOCK_BYREF_CALLER;
5176 QualType Ty = ND->getType();
5177 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5178 if (Ty->isBlockPointerType())
5179 flag |= BLOCK_FIELD_IS_BLOCK;
5180 else
5181 flag |= BLOCK_FIELD_IS_OBJECT;
5182 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005183 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005184 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005185 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005186
5187 // struct __Block_byref_ND ND =
5188 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5189 // initializer-if-any};
5190 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005191 unsigned flags = 0;
5192 if (HasCopyAndDispose)
5193 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005194 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005195 ByrefType.clear();
5196 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005197 std::string ForwardingCastType("(");
5198 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005199 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005200 ByrefType += " " + Name + " = {(void*)";
5201 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005202 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005203 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005204 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005205 ByrefType += "sizeof(";
5206 RewriteByRefString(ByrefType, Name, ND);
5207 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005208 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005209 ByrefType += ", __Block_byref_id_object_copy_";
5210 ByrefType += utostr(flag);
5211 ByrefType += ", __Block_byref_id_object_dispose_";
5212 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005213 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005214 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005215 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005216 }
5217 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005218 SourceLocation startLoc;
5219 Expr *E = ND->getInit();
5220 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5221 startLoc = ECE->getLParenLoc();
5222 else
5223 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005224 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005225 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005226 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005227 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005228 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005229 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005230 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005231 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005232 ByrefType += "sizeof(";
5233 RewriteByRefString(ByrefType, Name, ND);
5234 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005235 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005236 ByrefType += "__Block_byref_id_object_copy_";
5237 ByrefType += utostr(flag);
5238 ByrefType += ", __Block_byref_id_object_dispose_";
5239 ByrefType += utostr(flag);
5240 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005241 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005242 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005243
5244 // Complete the newly synthesized compound expression by inserting a right
5245 // curly brace before the end of the declaration.
5246 // FIXME: This approach avoids rewriting the initializer expression. It
5247 // also assumes there is only one declarator. For example, the following
5248 // isn't currently supported by this routine (in general):
5249 //
5250 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5251 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005252 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5253 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005254 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5255 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005256 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005257
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005258 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005259 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005260 return;
5261}
5262
Mike Stump11289f42009-09-09 15:08:12 +00005263void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005264 // Add initializers for any closure decl refs.
5265 GetBlockDeclRefExprs(Exp->getBody());
5266 if (BlockDeclRefs.size()) {
5267 // Unique all "by copy" declarations.
5268 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005269 if (!BlockDeclRefs[i]->isByRef()) {
5270 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5271 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5272 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5273 }
5274 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005275 // Unique all "by ref" declarations.
5276 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5277 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005278 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5279 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5280 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5281 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005282 }
5283 // Find any imported blocks...they will need special attention.
5284 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005285 if (BlockDeclRefs[i]->isByRef() ||
5286 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005287 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005288 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005289 }
5290}
5291
Daniel Dunbar56df9772010-08-17 22:39:59 +00005292FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005293 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005294 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005295 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005296 ID, FType, 0, SC_Extern,
5297 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005298}
5299
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005300Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5301 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005302 Blocks.push_back(Exp);
5303
5304 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005305
5306 // Add inner imported variables now used in current block.
5307 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005308 if (!InnerBlockDeclRefs.empty()) {
5309 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5310 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5311 ValueDecl *VD = Exp->getDecl();
5312 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005313 // We need to save the copied-in variables in nested
5314 // blocks because it is needed at the end for some of the API generations.
5315 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005316 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5317 BlockDeclRefs.push_back(Exp);
5318 BlockByCopyDeclsPtrSet.insert(VD);
5319 BlockByCopyDecls.push_back(VD);
5320 }
5321 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5322 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5323 BlockDeclRefs.push_back(Exp);
5324 BlockByRefDeclsPtrSet.insert(VD);
5325 BlockByRefDecls.push_back(VD);
5326 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005327 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005328 // Find any imported blocks...they will need special attention.
5329 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5330 if (InnerBlockDeclRefs[i]->isByRef() ||
5331 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5332 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5333 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005334 }
5335 InnerDeclRefsCount.push_back(countOfInnerDecls);
5336
Steve Narofff4b992a2008-10-28 20:29:00 +00005337 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005338
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005340 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005341 else if (CurMethodDef)
5342 BuildUniqueMethodName(FuncName, CurMethodDef);
5343 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005344 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005345
Steve Narofff4b992a2008-10-28 20:29:00 +00005346 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005347
Steve Narofff4b992a2008-10-28 20:29:00 +00005348 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5349 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005350
Steve Narofff4b992a2008-10-28 20:29:00 +00005351 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005352 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5353 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005354
5355 FunctionDecl *FD;
5356 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005357
Steve Narofff4b992a2008-10-28 20:29:00 +00005358 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005359 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005360 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5361 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005362
Steve Narofff4b992a2008-10-28 20:29:00 +00005363 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005364
Steve Naroffe2514232008-10-29 21:23:59 +00005365 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005366 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005367 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005368 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005369 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005370 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005371 InitExprs.push_back(castExpr);
5372
Steve Naroff30484702009-12-06 21:14:13 +00005373 // Initialize the block descriptor.
5374 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005375
Steve Naroff30484702009-12-06 21:14:13 +00005376 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5377 &Context->Idents.get(DescData.c_str()),
5378 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005379 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005380 UnaryOperator *DescRefExpr =
5381 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5382 Context->VoidPtrTy,
5383 VK_LValue,
5384 SourceLocation()),
5385 UO_AddrOf,
5386 Context->getPointerType(Context->VoidPtrTy),
5387 VK_RValue, OK_Ordinary,
5388 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005389 InitExprs.push_back(DescRefExpr);
5390
Steve Narofff4b992a2008-10-28 20:29:00 +00005391 // Add initializers for any closure decl refs.
5392 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005393 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005394 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005395 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005396 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005397 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005398 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005399 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005400 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5401 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005402 if (HasLocalVariableExternalStorage(*I)) {
5403 QualType QT = (*I)->getType();
5404 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005405 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5406 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005407 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005408 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005409 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005410 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5411 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005412 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005413 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005414 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005415 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005416 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5417 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005418 if (HasLocalVariableExternalStorage(*I)) {
5419 QualType QT = (*I)->getType();
5420 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005421 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5422 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005423 }
5424
Steve Narofff4b992a2008-10-28 20:29:00 +00005425 }
Mike Stump11289f42009-09-09 15:08:12 +00005426 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005427 }
5428 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005429 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005430 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005431 ValueDecl *ND = (*I);
5432 std::string Name(ND->getNameAsString());
5433 std::string RecName;
5434 RewriteByRefString(RecName, Name, ND);
5435 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5436 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005437 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005438 SourceLocation(), II);
5439 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5440 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5441
Daniel Dunbar56df9772010-08-17 22:39:59 +00005442 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005443 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5444 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005445 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005446 Context->getPointerType(Exp->getType()),
5447 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005448 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005449 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005450 }
5451 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005452 if (ImportedBlockDecls.size()) {
5453 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5454 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005455 unsigned IntSize =
5456 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005457 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5458 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005459 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005460 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005461 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005462 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005463 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005464 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005465 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005466 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005467 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005468 BlockDeclRefs.clear();
5469 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005470 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005471 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005472 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005473 ImportedBlockDecls.clear();
5474 return NewRep;
5475}
5476
5477//===----------------------------------------------------------------------===//
5478// Function Body / Expression rewriting
5479//===----------------------------------------------------------------------===//
5480
Steve Naroff4588d0f2008-12-04 16:24:46 +00005481// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5482// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5483// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5484// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5485// Since the rewriter isn't capable of rewriting rewritten code, it's important
5486// we get this right.
5487void RewriteObjC::CollectPropertySetters(Stmt *S) {
5488 // Perform a bottom up traversal of all children.
5489 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5490 CI != E; ++CI)
5491 if (*CI)
5492 CollectPropertySetters(*CI);
5493
5494 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5495 if (BinOp->isAssignmentOp()) {
John McCallb7bd14f2010-12-02 01:19:52 +00005496 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5497 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005498 }
5499 }
5500}
5501
Steve Narofff4b992a2008-10-28 20:29:00 +00005502Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005503 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005504 isa<DoStmt>(S) || isa<ForStmt>(S))
5505 Stmts.push_back(S);
5506 else if (isa<ObjCForCollectionStmt>(S)) {
5507 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005508 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005509 }
Mike Stump11289f42009-09-09 15:08:12 +00005510
Steve Narofff4b992a2008-10-28 20:29:00 +00005511 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005512
Steve Narofff4b992a2008-10-28 20:29:00 +00005513 // Perform a bottom up rewrite of all children.
5514 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5515 CI != E; ++CI)
5516 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005517 Stmt *newStmt;
5518 Stmt *S = (*CI);
5519 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5520 Expr *OldBase = IvarRefExpr->getBase();
5521 bool replaced = false;
5522 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5523 if (replaced) {
5524 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5525 ReplaceStmt(OldBase, IRE->getBase());
5526 else
5527 ReplaceStmt(S, newStmt);
5528 }
5529 }
5530 else
5531 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005532 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005533 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005534 // If dealing with an assignment with LHS being a property reference
5535 // expression, the entire assignment tree is rewritten into a property
5536 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5537 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005538 if (Expr *Exp = dyn_cast<Expr>(S))
John McCallb7bd14f2010-12-02 01:19:52 +00005539 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005540 if (PropSetters[Exp]) {
5541 ++CI;
5542 continue;
5543 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005544 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005545 }
Mike Stump11289f42009-09-09 15:08:12 +00005546
Steve Narofff4b992a2008-10-28 20:29:00 +00005547 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005548 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005549 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5550 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005551 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005552 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005553 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005554 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005555 Stmt *SaveCurrentBody = CurrentBody;
5556 CurrentBody = BE->getBody();
5557 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005558 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005559 CurrentBody = SaveCurrentBody;
5560 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005561 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005562 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005563 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005564 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005565
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005566 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5567
Steve Narofff4b992a2008-10-28 20:29:00 +00005568 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005569 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005570 return blockTranscribed;
5571 }
5572 // Handle specific things.
5573 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5574 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005575
John McCallb7bd14f2010-12-02 01:19:52 +00005576 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005577 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5578 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5579
5580 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005581 if (BinOp) {
5582 // Because the rewriter doesn't allow us to rewrite rewritten code,
5583 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005584 DisableReplaceStmt = true;
5585 // Save the source range. Even if we disable the replacement, the
5586 // rewritten node will have been inserted into the tree. If the synthesized
5587 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005588 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005589 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5590 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005591 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005592 // Need to rewrite the ivar access expression if need be.
5593 if (isa<ObjCIvarRefExpr>(newStmt)) {
5594 bool replaced = false;
5595 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5596 }
5597
Steve Naroff08628db2008-12-09 12:56:34 +00005598 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005599 //
5600 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5601 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5602 // to see the original expression). Consider this example:
5603 //
5604 // Foo *obj1, *obj2;
5605 //
5606 // obj1.i = [obj2 rrrr];
5607 //
5608 // 'BinOp' for the previous expression looks like:
5609 //
5610 // (BinaryOperator 0x231ccf0 'int' '='
5611 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5612 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5613 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5614 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5615 //
5616 // 'newStmt' represents the rewritten message expression. For example:
5617 //
5618 // (CallExpr 0x231d300 'id':'struct objc_object *'
5619 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5620 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5621 // (CStyleCastExpr 0x231d220 'void *'
5622 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5623 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005624 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005625 // can be used as the setter argument. ReplaceStmt() will still 'see'
5626 // the original RHS (since we haven't altered BinOp).
5627 //
Mike Stump11289f42009-09-09 15:08:12 +00005628 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005629 // node. As a result, we now leak the original AST nodes.
5630 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005631 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005632 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005633 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005634 }
5635 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005636
Steve Narofff4b992a2008-10-28 20:29:00 +00005637 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5638 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005639
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5641 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005642
Steve Narofff4b992a2008-10-28 20:29:00 +00005643 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005644#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005645 // Before we rewrite it, put the original message expression in a comment.
5646 SourceLocation startLoc = MessExpr->getLocStart();
5647 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005648
Steve Narofff4b992a2008-10-28 20:29:00 +00005649 const char *startBuf = SM->getCharacterData(startLoc);
5650 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005651
Steve Narofff4b992a2008-10-28 20:29:00 +00005652 std::string messString;
5653 messString += "// ";
5654 messString.append(startBuf, endBuf-startBuf+1);
5655 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005656
5657 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005658 // InsertText(clang::SourceLocation, char const*, unsigned int).
5659 // InsertText(startLoc, messString.c_str(), messString.size());
5660 // Tried this, but it didn't work either...
5661 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005662#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005663 return RewriteMessageExpr(MessExpr);
5664 }
Mike Stump11289f42009-09-09 15:08:12 +00005665
Steve Narofff4b992a2008-10-28 20:29:00 +00005666 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5667 return RewriteObjCTryStmt(StmtTry);
5668
5669 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5670 return RewriteObjCSynchronizedStmt(StmtTry);
5671
5672 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5673 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005674
Steve Narofff4b992a2008-10-28 20:29:00 +00005675 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5676 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005677
5678 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005679 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005680 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 OrigStmtRange.getEnd());
5682 if (BreakStmt *StmtBreakStmt =
5683 dyn_cast<BreakStmt>(S))
5684 return RewriteBreakStmt(StmtBreakStmt);
5685 if (ContinueStmt *StmtContinueStmt =
5686 dyn_cast<ContinueStmt>(S))
5687 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005688
5689 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005690 // and cast exprs.
5691 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5692 // FIXME: What we're doing here is modifying the type-specifier that
5693 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005694 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005695 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5696 // the context of an ObjCForCollectionStmt. For example:
5697 // NSArray *someArray;
5698 // for (id <FooProtocol> index in someArray) ;
5699 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5700 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005701 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005702 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005703
Steve Narofff4b992a2008-10-28 20:29:00 +00005704 // Blocks rewrite rules.
5705 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5706 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005707 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005708 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005709 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005710 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005711 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005712 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005713 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005714 if (VD->hasAttr<BlocksAttr>()) {
5715 static unsigned uniqueByrefDeclCount = 0;
5716 assert(!BlockByRefDeclNo.count(ND) &&
5717 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5718 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005719 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005720 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005721 else
5722 RewriteTypeOfDecl(VD);
5723 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005724 }
5725 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005726 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005727 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005728 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005729 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5730 }
5731 }
5732 }
Mike Stump11289f42009-09-09 15:08:12 +00005733
Steve Narofff4b992a2008-10-28 20:29:00 +00005734 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5735 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005736
5737 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005738 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5739 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005740 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5741 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005742 && "Statement stack mismatch");
5743 Stmts.pop_back();
5744 }
5745 // Handle blocks rewriting.
5746 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5747 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005748 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005749 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005750 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5751 ValueDecl *VD = DRE->getDecl();
5752 if (VD->hasAttr<BlocksAttr>())
5753 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005754 if (HasLocalVariableExternalStorage(VD))
5755 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005756 }
5757
Steve Narofff4b992a2008-10-28 20:29:00 +00005758 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005759 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005760 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005761 ReplaceStmt(S, BlockCall);
5762 return BlockCall;
5763 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005764 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005765 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005766 RewriteCastExpr(CE);
5767 }
5768#if 0
5769 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005770 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5771 ICE->getSubExpr(),
5772 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005773 // Get the new text.
5774 std::string SStr;
5775 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005776 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005777 const std::string &Str = Buf.str();
5778
5779 printf("CAST = %s\n", &Str[0]);
5780 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5781 delete S;
5782 return Replacement;
5783 }
5784#endif
5785 // Return this stmt unmodified.
5786 return S;
5787}
5788
Steve Naroffe70a52a2009-12-05 15:55:59 +00005789void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5790 for (RecordDecl::field_iterator i = RD->field_begin(),
5791 e = RD->field_end(); i != e; ++i) {
5792 FieldDecl *FD = *i;
5793 if (isTopLevelBlockPointerType(FD->getType()))
5794 RewriteBlockPointerDecl(FD);
5795 if (FD->getType()->isObjCQualifiedIdType() ||
5796 FD->getType()->isObjCQualifiedInterfaceType())
5797 RewriteObjCQualifiedInterfaceTypes(FD);
5798 }
5799}
5800
Steve Narofff4b992a2008-10-28 20:29:00 +00005801/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5802/// main file of the input.
5803void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5804 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005805 if (FD->isOverloadedOperator())
5806 return;
Mike Stump11289f42009-09-09 15:08:12 +00005807
Steve Narofff4b992a2008-10-28 20:29:00 +00005808 // Since function prototypes don't have ParmDecl's, we check the function
5809 // prototype. This enables us to rewrite function declarations and
5810 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005811 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005812
Sebastian Redla7b98a72009-04-26 20:35:05 +00005813 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005814 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005815 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005816 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005817 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005818 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005819 Body =
5820 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5821 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005822 CurrentBody = 0;
5823 if (PropParentMap) {
5824 delete PropParentMap;
5825 PropParentMap = 0;
5826 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005827 // This synthesizes and inserts the block "impl" struct, invoke function,
5828 // and any copy/dispose helper functions.
5829 InsertBlockLiteralsWithinFunction(FD);
5830 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005831 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005832 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005833 return;
5834 }
5835 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005836 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005837 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005838 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005839 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005840 Body =
5841 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5842 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005843 CurrentBody = 0;
5844 if (PropParentMap) {
5845 delete PropParentMap;
5846 PropParentMap = 0;
5847 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005848 InsertBlockLiteralsWithinMethod(MD);
5849 CurMethodDef = 0;
5850 }
5851 }
5852 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5853 ClassImplementation.push_back(CI);
5854 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5855 CategoryImplementation.push_back(CI);
5856 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5857 RewriteForwardClassDecl(CD);
5858 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5859 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005860 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005861 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005862 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005863 CheckFunctionPointerDecl(VD->getType(), VD);
5864 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005865 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005866 RewriteCastExpr(CE);
5867 }
5868 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005869 } else if (VD->getType()->isRecordType()) {
5870 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5871 if (RD->isDefinition())
5872 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005873 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005874 if (VD->getInit()) {
5875 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005876 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005877 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005878 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005879 CurrentBody = 0;
5880 if (PropParentMap) {
5881 delete PropParentMap;
5882 PropParentMap = 0;
5883 }
Mike Stump11289f42009-09-09 15:08:12 +00005884 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005885 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005886 GlobalVarDecl = 0;
5887
5888 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005889 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005890 RewriteCastExpr(CE);
5891 }
5892 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005893 return;
5894 }
5895 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005896 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005897 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005898 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005899 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5900 return;
5901 }
5902 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005903 if (RD->isDefinition())
5904 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005905 return;
5906 }
5907 // Nothing yet.
5908}
5909
Chris Lattnercf169832009-03-28 04:11:33 +00005910void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005911 if (Diags.hasErrorOccurred())
5912 return;
Mike Stump11289f42009-09-09 15:08:12 +00005913
Steve Narofff4b992a2008-10-28 20:29:00 +00005914 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005915
Steve Naroffd9803712009-04-29 16:37:50 +00005916 // Here's a great place to add any extra declarations that may be needed.
5917 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005918 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005919 E = ProtocolExprDecls.end(); I != E; ++I)
5920 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5921
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005922 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005923 if (ClassImplementation.size() || CategoryImplementation.size())
5924 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005925
Steve Narofff4b992a2008-10-28 20:29:00 +00005926 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5927 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005928 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005929 Rewrite.getRewriteBufferFor(MainFileID)) {
5930 //printf("Changed:\n");
5931 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5932 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005933 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005934 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005935
Steve Naroffd9803712009-04-29 16:37:50 +00005936 if (ClassImplementation.size() || CategoryImplementation.size() ||
5937 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005938 // Rewrite Objective-c meta data*
5939 std::string ResultStr;
5940 SynthesizeMetaDataIntoBuffer(ResultStr);
5941 // Emit metadata.
5942 *OutFile << ResultStr;
5943 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005944 OutFile->flush();
5945}