blob: 286ac0f63810a1129037ec18230c72191393b44e [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;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001231 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001232 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCallb7bd14f2010-12-02 01:19:52 +00001233 if (ObjCPropertyRefExpr *PropRefExpr =
1234 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1235 if (PropRefExpr->isExplicitProperty()) {
1236 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1237 OMD = PDecl->getSetterMethodDecl();
1238 Ty = PDecl->getType();
1239 Sel = PDecl->getSetterName();
1240 } else {
1241 OMD = PropRefExpr->getImplicitPropertySetter();
1242 Sel = OMD->getSelector();
1243 Ty = PropRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001244 }
John McCallb7bd14f2010-12-02 01:19:52 +00001245 Super = PropRefExpr->isSuperReceiver();
1246 if (!Super) {
1247 Receiver = PropRefExpr->getBase();
1248 } else {
1249 SuperTy = PropRefExpr->getSuperReceiverType();
1250 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001251 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001252 }
1253
1254 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001255 llvm::SmallVector<Expr *, 1> ExprVec;
1256 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001257
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001258 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001259 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001260 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001261 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001262 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001263 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001264 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001265 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001266 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001267 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001268 &ExprVec[0], 1,
1269 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001270 else {
1271 // FIXME. Refactor this into common code with that in
1272 // RewritePropertyOrImplicitGetter
1273 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1274 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1275 if (PropGetters[Exp])
1276 // This allows us to handle chain/nested property/implicit getters.
1277 Receiver = PropGetters[Exp];
1278
Douglas Gregor9a129192010-04-21 00:45:42 +00001279 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001280 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001281 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001282 /*FIXME: */SourceLocation(),
1283 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001284 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001285 &ExprVec[0], 1,
1286 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001287 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001288 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001289
Steve Naroff4588d0f2008-12-04 16:24:46 +00001290 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001291 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001292 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001293 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1294 // to things that stay around.
1295 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001296 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001297}
1298
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001299Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1300 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001301 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001302 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001303 ObjCMethodDecl *OMD = 0;
1304 QualType Ty;
1305 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001306 bool Super = false;
1307 QualType SuperTy;
1308 SourceLocation SuperLocation;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001309 if (ObjCPropertyRefExpr *PropRefExpr =
1310 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
John McCallb7bd14f2010-12-02 01:19:52 +00001311 if (PropRefExpr->isExplicitProperty()) {
1312 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1313 OMD = PDecl->getGetterMethodDecl();
1314 Ty = PDecl->getType();
1315 Sel = PDecl->getGetterName();
1316 } else {
1317 OMD = PropRefExpr->getImplicitPropertyGetter();
1318 Sel = OMD->getSelector();
1319 Ty = PropRefExpr->getType();
1320 }
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001321 Super = PropRefExpr->isSuperReceiver();
1322 if (!Super)
1323 Receiver = PropRefExpr->getBase();
1324 else {
John McCallb7bd14f2010-12-02 01:19:52 +00001325 SuperTy = PropRefExpr->getSuperReceiverType();
1326 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001327 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001328 }
1329
1330 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1331
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001332 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001333 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001334 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001335 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001336 Expr::getValueKindForType(Ty),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001337 /*FIXME?*/SourceLocation(),
1338 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001339 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001340 SuperTy,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001341 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001342 0, 0,
1343 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001344 else {
1345 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1346 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1347 if (PropGetters[Exp])
1348 // This allows us to handle chain/nested property/implicit getters.
1349 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001350 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001351 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001352 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001353 /*FIXME:*/SourceLocation(),
1354 cast<Expr>(Receiver),
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001355 Sel, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001356 0, 0,
1357 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001358 }
Steve Narofff326f402008-12-03 00:56:33 +00001359
Steve Naroff22216db2008-12-04 23:50:32 +00001360 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001361
1362 if (!PropParentMap)
1363 PropParentMap = new ParentMap(CurrentBody);
1364
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001365 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
John McCallb7bd14f2010-12-02 01:19:52 +00001366 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001367 // We stash away the ReplacingStmt since actually doing the
1368 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001369 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001370 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1371 // to things that stay around.
1372 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001373 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001374 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001375 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001376 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001377 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1378 // to things that stay around.
1379 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001380 return ReplacingStmt;
1381 }
Steve Narofff326f402008-12-03 00:56:33 +00001382}
1383
Mike Stump11289f42009-09-09 15:08:12 +00001384Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001385 SourceLocation OrigStart,
1386 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001387 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001388 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001389 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001390 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001391 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001392 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001393 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001394 // lookup which class implements the instance variable.
1395 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001396 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001397 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001398 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001399
Steve Naroffb1c02372008-05-08 17:52:16 +00001400 // Synthesize an explicit cast to gain access to the ivar.
1401 std::string RecName = clsDeclared->getIdentifier()->getName();
1402 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001403 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001404 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001405 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001406 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1407 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001408 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001409 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001410 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001411 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001412 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001413 IV->getBase()->getLocEnd(),
1414 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001415 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001416 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001417 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001418 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001419 IV->getLocation(),
1420 D->getType(),
1421 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001422 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001423 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001424 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001425 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001426 // Cannot delete IV->getBase(), since PE points to it.
1427 // Replace the old base with the cast. This is important when doing
1428 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001429 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001430 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001431 }
Steve Naroff24840f62008-04-18 21:55:08 +00001432 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001433 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001434
Steve Naroff29ce4e52008-05-06 23:20:07 +00001435 // Explicit ivar refs need to have a cast inserted.
1436 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001437 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001438 ObjCInterfaceType *iFaceDecl =
1439 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001440 // lookup which class implements the instance variable.
1441 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001442 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001443 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001444 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001445
Steve Naroff29ce4e52008-05-06 23:20:07 +00001446 // Synthesize an explicit cast to gain access to the ivar.
1447 std::string RecName = clsDeclared->getIdentifier()->getName();
1448 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001449 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001450 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001451 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001452 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1453 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001454 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001455 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001456 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001457 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001458 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001459 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001460 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001461 // Cannot delete IV->getBase(), since PE points to it.
1462 // Replace the old base with the cast. This is important when doing
1463 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001464 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001465 return IV;
1466 }
Steve Naroff05caa482007-11-15 11:33:00 +00001467 }
Steve Naroff24840f62008-04-18 21:55:08 +00001468 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001469}
1470
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001471Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1472 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1473 CI != E; ++CI) {
1474 if (*CI) {
1475 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1476 if (newStmt)
1477 *CI = newStmt;
1478 }
1479 }
1480 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1481 SourceRange OrigStmtRange = S->getSourceRange();
1482 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1483 replaced);
1484 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001485 }
1486 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1487 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1488 return newStmt;
1489 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001490 return S;
1491}
1492
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001493/// SynthCountByEnumWithState - To print:
1494/// ((unsigned int (*)
1495/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001496/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001498/// "countByEnumeratingWithState:objects:count:"),
1499/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001500/// (id *)items, (unsigned int)16)
1501///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001502void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001503 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1504 "id *, unsigned int))(void *)objc_msgSend)";
1505 buf += "\n\t\t";
1506 buf += "((id)l_collection,\n\t\t";
1507 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1508 buf += "\n\t\t";
1509 buf += "&enumState, "
1510 "(id *)items, (unsigned int)16)";
1511}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001512
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001513/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1514/// statement to exit to its outer synthesized loop.
1515///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001516Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001517 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1518 return S;
1519 // replace break with goto __break_label
1520 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001521
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001522 SourceLocation startLoc = S->getLocStart();
1523 buf = "goto __break_label_";
1524 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001525 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001526
1527 return 0;
1528}
1529
1530/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1531/// statement to continue with its inner synthesized loop.
1532///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001533Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1535 return S;
1536 // replace continue with goto __continue_label
1537 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001538
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001539 SourceLocation startLoc = S->getLocStart();
1540 buf = "goto __continue_label_";
1541 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001542 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001544 return 0;
1545}
1546
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001547/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001548/// It rewrites:
1549/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001551/// Into:
1552/// {
Mike Stump11289f42009-09-09 15:08:12 +00001553/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001555/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001557/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001558/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001559/// if (limit) {
1560/// unsigned long startMutations = *enumState.mutationsPtr;
1561/// do {
1562/// unsigned long counter = 0;
1563/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001564/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001565/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001566/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001567/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001568/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001569/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001570/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001571/// objects:items count:16]);
1572/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001573/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001574/// }
1575/// else
1576/// elem = nil;
1577/// }
1578///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001579Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001580 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001581 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001582 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001583 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001584 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001585 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001586
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001587 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001588 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001589 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001590 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001591 std::string buf;
1592 buf = "\n{\n\t";
1593 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1594 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001595 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001596 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001597 if (ElementType->isObjCQualifiedIdType() ||
1598 ElementType->isObjCQualifiedInterfaceType())
1599 // Simply use 'id' for all qualified types.
1600 elementTypeAsString = "id";
1601 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001602 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001603 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001604 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001605 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001606 buf += elementName;
1607 buf += ";\n\t";
1608 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001609 else {
1610 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001611 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001612 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1613 if (VD->getType()->isObjCQualifiedIdType() ||
1614 VD->getType()->isObjCQualifiedInterfaceType())
1615 // Simply use 'id' for all qualified types.
1616 elementTypeAsString = "id";
1617 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001618 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001621 // struct __objcFastEnumerationState enumState = { 0 };
1622 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1623 // id items[16];
1624 buf += "id items[16];\n\t";
1625 // id l_collection = (id)
1626 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001627 // Find start location of 'collection' the hard way!
1628 const char *startCollectionBuf = startBuf;
1629 startCollectionBuf += 3; // skip 'for'
1630 startCollectionBuf = strchr(startCollectionBuf, '(');
1631 startCollectionBuf++; // skip '('
1632 // find 'in' and skip it.
1633 while (*startCollectionBuf != ' ' ||
1634 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1635 (*(startCollectionBuf+3) != ' ' &&
1636 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1637 startCollectionBuf++;
1638 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001639
1640 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001641 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001642 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001643 SourceLocation rightParenLoc = S->getRParenLoc();
1644 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1645 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001646 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001647
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1649 // objects:items count:16];
1650 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001651 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001652 // ((unsigned int (*)
1653 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001654 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001655 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001656 // "countByEnumeratingWithState:objects:count:"),
1657 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001658 // (id *)items, (unsigned int)16);
1659 buf += "unsigned long limit =\n\t\t";
1660 SynthCountByEnumWithState(buf);
1661 buf += ";\n\t";
1662 /// if (limit) {
1663 /// unsigned long startMutations = *enumState.mutationsPtr;
1664 /// do {
1665 /// unsigned long counter = 0;
1666 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001667 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001668 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001669 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001670 buf += "if (limit) {\n\t";
1671 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1672 buf += "do {\n\t\t";
1673 buf += "unsigned long counter = 0;\n\t\t";
1674 buf += "do {\n\t\t\t";
1675 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1676 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1677 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001678 buf += " = (";
1679 buf += elementTypeAsString;
1680 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001681 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001682 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001683
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001684 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001685 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001686 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001687 /// objects:items count:16]);
1688 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001689 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001690 /// }
1691 /// else
1692 /// elem = nil;
1693 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001694 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001695 buf = ";\n\t";
1696 buf += "__continue_label_";
1697 buf += utostr(ObjCBcLabelNo.back());
1698 buf += ": ;";
1699 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001700 buf += "} while (counter < limit);\n\t";
1701 buf += "} while (limit = ";
1702 SynthCountByEnumWithState(buf);
1703 buf += ");\n\t";
1704 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001705 buf += " = ((";
1706 buf += elementTypeAsString;
1707 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001708 buf += "__break_label_";
1709 buf += utostr(ObjCBcLabelNo.back());
1710 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001711 buf += "}\n\t";
1712 buf += "else\n\t\t";
1713 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001714 buf += " = ((";
1715 buf += elementTypeAsString;
1716 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001717 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001718
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001719 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001720 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001721 if (isa<CompoundStmt>(S->getBody())) {
1722 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001723 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001724 } else {
1725 /* Need to treat single statements specially. For example:
1726 *
1727 * for (A *a in b) if (stuff()) break;
1728 * for (A *a in b) xxxyy;
1729 *
1730 * The following code simply scans ahead to the semi to find the actual end.
1731 */
1732 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1733 const char *semiBuf = strchr(stmtBuf, ';');
1734 assert(semiBuf && "Can't find ';'");
1735 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001736 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001737 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001738 Stmts.pop_back();
1739 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001740 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001741}
1742
Mike Stump11289f42009-09-09 15:08:12 +00001743/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001744/// This routine rewrites @synchronized(expr) stmt;
1745/// into:
1746/// objc_sync_enter(expr);
1747/// @try stmt @finally { objc_sync_exit(expr); }
1748///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001749Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001750 // Get the start location and compute the semi location.
1751 SourceLocation startLoc = S->getLocStart();
1752 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001754 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001755
1756 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001757 buf = "objc_sync_enter((id)";
1758 const char *lparenBuf = startBuf;
1759 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001760 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001761 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1762 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001763 // been rewritten! (which implies the SourceLocation's are invalid).
1764 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001765 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001766 while (*endBuf != ')') endBuf--;
1767 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001768 buf = ");\n";
1769 // declare a new scope with two variables, _stack and _rethrow.
1770 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1771 buf += "int buf[18/*32-bit i386*/];\n";
1772 buf += "char *pointers[4];} _stack;\n";
1773 buf += "id volatile _rethrow = 0;\n";
1774 buf += "objc_exception_try_enter(&_stack);\n";
1775 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001776 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001777 startLoc = S->getSynchBody()->getLocEnd();
1778 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroffad7013b2008-08-19 13:04:19 +00001780 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001781 SourceLocation lastCurlyLoc = startLoc;
1782 buf = "}\nelse {\n";
1783 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001784 buf += "}\n";
1785 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001786 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001787
1788 std::string syncBuf;
1789 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001790 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001791 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001792 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001793 std::string syncExprBufS;
1794 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001795 syncExpr->printPretty(syncExprBuf, *Context, 0,
1796 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001797 syncBuf += syncExprBuf.str();
1798 syncBuf += ");";
1799
1800 buf += syncBuf;
1801 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001802 buf += "}\n";
1803 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001804
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001805 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001806
1807 bool hasReturns = false;
1808 HasReturnStmts(S->getSynchBody(), hasReturns);
1809 if (hasReturns)
1810 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1811
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001812 return 0;
1813}
1814
Steve Naroffec60b432009-12-05 21:43:12 +00001815void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1816{
Steve Naroff6d6da252008-12-05 17:03:39 +00001817 // Perform a bottom up traversal of all children.
1818 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1819 CI != E; ++CI)
1820 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001821 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001822
Steve Naroffec60b432009-12-05 21:43:12 +00001823 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001824 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001825 TryFinallyContainsReturnDiag);
1826 }
1827 return;
1828}
1829
Steve Naroffec60b432009-12-05 21:43:12 +00001830void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1831{
1832 // Perform a bottom up traversal of all children.
1833 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1834 CI != E; ++CI)
1835 if (*CI)
1836 HasReturnStmts(*CI, hasReturns);
1837
1838 if (isa<ReturnStmt>(S))
1839 hasReturns = true;
1840 return;
1841}
1842
1843void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
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 RewriteTryReturnStmts(*CI);
1849 }
1850 if (isa<ReturnStmt>(S)) {
1851 SourceLocation startLoc = S->getLocStart();
1852 const char *startBuf = SM->getCharacterData(startLoc);
1853
1854 const char *semiBuf = strchr(startBuf, ';');
1855 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1856 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1857
1858 std::string buf;
1859 buf = "{ objc_exception_try_exit(&_stack); return";
1860
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001861 ReplaceText(startLoc, 6, buf);
1862 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001863 }
1864 return;
1865}
1866
1867void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1868 // Perform a bottom up traversal of all children.
1869 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1870 CI != E; ++CI)
1871 if (*CI) {
1872 RewriteSyncReturnStmts(*CI, syncExitBuf);
1873 }
1874 if (isa<ReturnStmt>(S)) {
1875 SourceLocation startLoc = S->getLocStart();
1876 const char *startBuf = SM->getCharacterData(startLoc);
1877
1878 const char *semiBuf = strchr(startBuf, ';');
1879 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1880 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1881
1882 std::string buf;
1883 buf = "{ objc_exception_try_exit(&_stack);";
1884 buf += syncExitBuf;
1885 buf += " return";
1886
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001887 ReplaceText(startLoc, 6, buf);
1888 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001889 }
1890 return;
1891}
1892
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001893Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001894 // Get the start location and compute the semi location.
1895 SourceLocation startLoc = S->getLocStart();
1896 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001897
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898 assert((*startBuf == '@') && "bogus @try location");
1899
1900 std::string buf;
1901 // declare a new scope with two variables, _stack and _rethrow.
1902 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1903 buf += "int buf[18/*32-bit i386*/];\n";
1904 buf += "char *pointers[4];} _stack;\n";
1905 buf += "id volatile _rethrow = 0;\n";
1906 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001907 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001908
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001909 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001910
Steve Naroffbf478ec2007-11-07 04:08:17 +00001911 startLoc = S->getTryBody()->getLocEnd();
1912 startBuf = SM->getCharacterData(startLoc);
1913
1914 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001915
Steve Naroffbf478ec2007-11-07 04:08:17 +00001916 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001917 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001918 startLoc = startLoc.getFileLocWithOffset(1);
1919 buf = " /* @catch begin */ else {\n";
1920 buf += " id _caught = objc_exception_extract(&_stack);\n";
1921 buf += " objc_exception_try_enter (&_stack);\n";
1922 buf += " if (_setjmp(_stack.buf))\n";
1923 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1924 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001925
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001926 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001927 } else { /* no catch list */
1928 buf = "}\nelse {\n";
1929 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1930 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001931 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001932 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001933 bool sawIdTypedCatch = false;
1934 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001935 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1936 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001937 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001938
Douglas Gregor96c79492010-04-23 22:50:49 +00001939 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001940 buf = "if ("; // we are generating code for the first catch clause
1941 else
1942 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001943 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001944 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Steve Naroffbf478ec2007-11-07 04:08:17 +00001946 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001947
Steve Naroffbf478ec2007-11-07 04:08:17 +00001948 const char *lParenLoc = strchr(startBuf, '(');
1949
Douglas Gregor96c79492010-04-23 22:50:49 +00001950 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001951 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001952 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001953 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1954 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001955 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001956 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001957 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001958
Steve Naroffedb5bc62008-02-01 20:02:07 +00001959 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001960 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001961 } else if (catchDecl) {
1962 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001963 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001964 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001965 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001966 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001967 } else if (const ObjCObjectPointerType *Ptr =
1968 t->getAs<ObjCObjectPointerType>()) {
1969 // Should be a pointer to a class.
1970 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1971 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001972 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001973 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001974 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001975 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001976 }
1977 }
1978 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001979 lastCatchBody = Catch->getCatchBody();
1980 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001981 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1982 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1983 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1984 assert((*rParenBuf == ')') && "bogus @catch paren location");
1985 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001986
Mike Stump11289f42009-09-09 15:08:12 +00001987 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001988 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001989 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001990 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001991 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001992 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001993 }
1994 // Complete the catch list...
1995 if (lastCatchBody) {
1996 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001997 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1998 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001999
Steve Naroff4adbe312008-09-11 15:29:03 +00002000 // Insert the last (implicit) else clause *before* the right curly brace.
2001 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2002 buf = "} /* last catch end */\n";
2003 buf += "else {\n";
2004 buf += " _rethrow = _caught;\n";
2005 buf += " objc_exception_try_exit(&_stack);\n";
2006 buf += "} } /* @catch end */\n";
2007 if (!S->getFinallyStmt())
2008 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002009 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Steve Naroffbf478ec2007-11-07 04:08:17 +00002011 // Set lastCurlyLoc
2012 lastCurlyLoc = lastCatchBody->getLocEnd();
2013 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002014 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002015 startLoc = finalStmt->getLocStart();
2016 startBuf = SM->getCharacterData(startLoc);
2017 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002018
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002019 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002020
Steve Naroffbf478ec2007-11-07 04:08:17 +00002021 Stmt *body = finalStmt->getFinallyBody();
2022 SourceLocation startLoc = body->getLocStart();
2023 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002024 assert(*SM->getCharacterData(startLoc) == '{' &&
2025 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002026 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002027 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002028
Steve Naroffbf478ec2007-11-07 04:08:17 +00002029 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002030 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002031 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002032 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002033
Steve Naroffbf478ec2007-11-07 04:08:17 +00002034 // Set lastCurlyLoc
2035 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002036
Steve Naroff6d6da252008-12-05 17:03:39 +00002037 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002038 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002039 } else { /* no finally clause - make sure we synthesize an implicit one */
2040 buf = "{ /* implicit finally clause */\n";
2041 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2042 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2043 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002044 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002045
2046 // Now check for any return/continue/go statements within the @try.
2047 // The implicit finally clause won't called if the @try contains any
2048 // jump statements.
2049 bool hasReturns = false;
2050 HasReturnStmts(S->getTryBody(), hasReturns);
2051 if (hasReturns)
2052 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002053 }
2054 // Now emit the final closing curly brace...
2055 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002056 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002057 return 0;
2058}
2059
Mike Stump11289f42009-09-09 15:08:12 +00002060// This can't be done with ReplaceStmt(S, ThrowExpr), since
2061// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002062// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002063Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002064 // Get the start location and compute the semi location.
2065 SourceLocation startLoc = S->getLocStart();
2066 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002067
Steve Naroffa733c7f2007-11-07 15:32:26 +00002068 assert((*startBuf == '@') && "bogus @throw location");
2069
2070 std::string buf;
2071 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002072 if (S->getThrowExpr())
2073 buf = "objc_exception_throw(";
2074 else // add an implicit argument
2075 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002076
Steve Naroff29788342008-07-25 15:41:30 +00002077 // handle "@ throw" correctly.
2078 const char *wBuf = strchr(startBuf, 'w');
2079 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002080 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002081
Steve Naroffa733c7f2007-11-07 15:32:26 +00002082 const char *semiBuf = strchr(startBuf, ';');
2083 assert((*semiBuf == ';') && "@throw: can't find ';'");
2084 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002085 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002086 return 0;
2087}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002088
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002089Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002090 // Create a new string expression.
2091 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002092 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002093 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002094 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2095 StrEncoding.length(), false,StrType,
2096 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002097 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002098
Chris Lattner4431a1b2007-11-30 22:53:43 +00002099 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002100 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002101 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002102}
2103
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002104Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002105 if (!SelGetUidFunctionDecl)
2106 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002107 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2108 // Create a call to sel_registerName("selName").
2109 llvm::SmallVector<Expr*, 8> SelExprs;
2110 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002111 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002112 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002113 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002114 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002115 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2116 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002117 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002118 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002119 return SelExp;
2120}
2121
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002122CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002123 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2124 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002125 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002126 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002127
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002128 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002129 DeclRefExpr *DRE =
2130 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002131
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002132 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002133 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002134 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002135 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002136 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002137
John McCall9dd450b2009-09-21 23:43:11 +00002138 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002139
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002140 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002141 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002142 FT->getCallResultType(*Context),
2143 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002144 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002145}
2146
Steve Naroff50d42052007-11-01 13:24:47 +00002147static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2148 const char *&startRef, const char *&endRef) {
2149 while (startBuf < endBuf) {
2150 if (*startBuf == '<')
2151 startRef = startBuf; // mark the start.
2152 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002153 if (startRef && *startRef == '<') {
2154 endRef = startBuf; // mark the end.
2155 return true;
2156 }
2157 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002158 }
2159 startBuf++;
2160 }
2161 return false;
2162}
2163
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002164static void scanToNextArgument(const char *&argRef) {
2165 int angle = 0;
2166 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2167 if (*argRef == '<')
2168 angle++;
2169 else if (*argRef == '>')
2170 angle--;
2171 argRef++;
2172 }
2173 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2174}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002175
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002176bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002177 if (T->isObjCQualifiedIdType())
2178 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002179 if (const PointerType *PT = T->getAs<PointerType>()) {
2180 if (PT->getPointeeType()->isObjCQualifiedIdType())
2181 return true;
2182 }
2183 if (T->isObjCObjectPointerType()) {
2184 T = T->getPointeeType();
2185 return T->isObjCQualifiedInterfaceType();
2186 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002187 if (T->isArrayType()) {
2188 QualType ElemTy = Context->getBaseElementType(T);
2189 return needToScanForQualifiers(ElemTy);
2190 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002191 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002192}
2193
Steve Naroff873bd842008-07-29 18:15:38 +00002194void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2195 QualType Type = E->getType();
2196 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002197 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002198
Steve Naroffdbfc6932008-11-19 21:15:47 +00002199 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2200 Loc = ECE->getLParenLoc();
2201 EndLoc = ECE->getRParenLoc();
2202 } else {
2203 Loc = E->getLocStart();
2204 EndLoc = E->getLocEnd();
2205 }
2206 // This will defend against trying to rewrite synthesized expressions.
2207 if (Loc.isInvalid() || EndLoc.isInvalid())
2208 return;
2209
Steve Naroff873bd842008-07-29 18:15:38 +00002210 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002211 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002212 const char *startRef = 0, *endRef = 0;
2213 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2214 // Get the locations of the startRef, endRef.
2215 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2216 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2217 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002218 InsertText(LessLoc, "/*");
2219 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002220 }
2221 }
2222}
2223
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002224void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002225 SourceLocation Loc;
2226 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002227 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002228 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2229 Loc = VD->getLocation();
2230 Type = VD->getType();
2231 }
2232 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2233 Loc = FD->getLocation();
2234 // Check for ObjC 'id' and class types that have been adorned with protocol
2235 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002236 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002237 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002238 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002239 if (!proto)
2240 return;
2241 Type = proto->getResultType();
2242 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002243 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2244 Loc = FD->getLocation();
2245 Type = FD->getType();
2246 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002247 else
2248 return;
Mike Stump11289f42009-09-09 15:08:12 +00002249
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002250 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002251 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002252
Steve Naroff50d42052007-11-01 13:24:47 +00002253 const char *endBuf = SM->getCharacterData(Loc);
2254 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002255 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002256 startBuf--; // scan backward (from the decl location) for return type.
2257 const char *startRef = 0, *endRef = 0;
2258 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2259 // Get the locations of the startRef, endRef.
2260 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2261 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2262 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002263 InsertText(LessLoc, "/*");
2264 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002265 }
2266 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002267 if (!proto)
2268 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002269 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002270 const char *startBuf = SM->getCharacterData(Loc);
2271 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002272 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2273 if (needToScanForQualifiers(proto->getArgType(i))) {
2274 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002275
Steve Naroff50d42052007-11-01 13:24:47 +00002276 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002277 // scan forward (from the decl location) for argument types.
2278 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002279 const char *startRef = 0, *endRef = 0;
2280 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2281 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002282 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002283 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002284 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002285 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002286 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002287 InsertText(LessLoc, "/*");
2288 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002289 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002290 startBuf = ++endBuf;
2291 }
2292 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002293 // If the function name is derived from a macro expansion, then the
2294 // argument buffer will not follow the name. Need to speak with Chris.
2295 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002296 startBuf++; // scan forward (from the decl location) for argument types.
2297 startBuf++;
2298 }
Steve Naroff50d42052007-11-01 13:24:47 +00002299 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002300}
2301
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002302void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2303 QualType QT = ND->getType();
2304 const Type* TypePtr = QT->getAs<Type>();
2305 if (!isa<TypeOfExprType>(TypePtr))
2306 return;
2307 while (isa<TypeOfExprType>(TypePtr)) {
2308 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2309 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2310 TypePtr = QT->getAs<Type>();
2311 }
2312 // FIXME. This will not work for multiple declarators; as in:
2313 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002314 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002315 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2316 const char *startBuf = SM->getCharacterData(DeclLoc);
2317 if (ND->getInit()) {
2318 std::string Name(ND->getNameAsString());
2319 TypeAsString += " " + Name + " = ";
2320 Expr *E = ND->getInit();
2321 SourceLocation startLoc;
2322 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2323 startLoc = ECE->getLParenLoc();
2324 else
2325 startLoc = E->getLocStart();
2326 startLoc = SM->getInstantiationLoc(startLoc);
2327 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002328 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002329 }
2330 else {
2331 SourceLocation X = ND->getLocEnd();
2332 X = SM->getInstantiationLoc(X);
2333 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002334 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002335 }
2336}
2337
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002338// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002339void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002340 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2341 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002342 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002343 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002344 &ArgTys[0], ArgTys.size(),
2345 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002346 false, false, 0, 0,
2347 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002348 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002349 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002350 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002351 SC_Extern,
2352 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002353}
2354
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002355void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002356 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002357 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002358 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002359 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002360 return;
2361 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002362 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002363}
2364
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002365void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2366 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002367 const char *argPtr = TypeString.c_str();
2368 if (!strchr(argPtr, '^')) {
2369 Str += TypeString;
2370 return;
2371 }
2372 while (*argPtr) {
2373 Str += (*argPtr == '^' ? '*' : *argPtr);
2374 argPtr++;
2375 }
2376}
2377
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002378// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002379void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2380 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002381 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002382 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002383 const char *argPtr = TypeString.c_str();
2384 int paren = 0;
2385 while (*argPtr) {
2386 switch (*argPtr) {
2387 case '(':
2388 Str += *argPtr;
2389 paren++;
2390 break;
2391 case ')':
2392 Str += *argPtr;
2393 paren--;
2394 break;
2395 case '^':
2396 Str += '*';
2397 if (paren == 1)
2398 Str += VD->getNameAsString();
2399 break;
2400 default:
2401 Str += *argPtr;
2402 break;
2403 }
2404 argPtr++;
2405 }
2406}
2407
2408
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002409void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2410 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2411 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2412 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2413 if (!proto)
2414 return;
2415 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002416 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002417 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002418 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002419 FdStr += "(";
2420 unsigned numArgs = proto->getNumArgs();
2421 for (unsigned i = 0; i < numArgs; i++) {
2422 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002423 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002424 if (i+1 < numArgs)
2425 FdStr += ", ";
2426 }
2427 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002428 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002429 CurFunctionDeclToDeclareForBlock = 0;
2430}
2431
Steve Naroff17978c42008-03-11 17:37:02 +00002432// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002433void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002434 if (SuperContructorFunctionDecl)
2435 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002436 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002437 llvm::SmallVector<QualType, 16> ArgTys;
2438 QualType argT = Context->getObjCIdType();
2439 assert(!argT.isNull() && "Can't find 'id' type");
2440 ArgTys.push_back(argT);
2441 ArgTys.push_back(argT);
2442 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2443 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002444 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002445 false, false, 0, 0,
2446 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002447 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002448 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002449 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002450 SC_Extern,
2451 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002452}
2453
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002454// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002455void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002456 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2457 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002458 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002461 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002464 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002465 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002466 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002467 false, false, 0, 0,
2468 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002469 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002470 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002471 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002472 SC_Extern,
2473 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002474}
2475
Steve Naroff7fa2f042007-11-15 10:28:18 +00002476// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002477void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002478 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2479 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002480 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002481 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002482 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002483 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2484 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2485 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002486 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002487 assert(!argT.isNull() && "Can't find 'SEL' type");
2488 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002489 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002490 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002491 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002492 false, false, 0, 0,
2493 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002494 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002495 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002496 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002497 SC_Extern,
2498 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499}
2500
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002501// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002502void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002503 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2504 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002505 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002506 assert(!argT.isNull() && "Can't find 'id' type");
2507 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002508 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002509 assert(!argT.isNull() && "Can't find 'SEL' type");
2510 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002511 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002512 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002513 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002514 false, false, 0, 0,
2515 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002516 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002517 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002518 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002519 SC_Extern,
2520 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002521}
2522
Mike Stump11289f42009-09-09 15:08:12 +00002523// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002524// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002525void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002526 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002527 &Context->Idents.get("objc_msgSendSuper_stret");
2528 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002529 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002530 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002531 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002532 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2533 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2534 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002535 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002536 assert(!argT.isNull() && "Can't find 'SEL' type");
2537 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002538 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002539 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002540 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002541 false, false, 0, 0,
2542 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002543 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002544 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002545 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002546 SC_Extern,
2547 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002548}
2549
Steve Naroff2e4e3852008-05-08 22:02:18 +00002550// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002551void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002552 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2553 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002554 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002555 assert(!argT.isNull() && "Can't find 'id' type");
2556 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002557 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002558 assert(!argT.isNull() && "Can't find 'SEL' type");
2559 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002560 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002561 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002562 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002563 false, false, 0, 0,
2564 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002565 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002566 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002567 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002568 SC_Extern,
2569 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002570}
2571
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002572// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002573void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002574 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2575 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002576 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002577 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002578 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002579 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002580 false, false, 0, 0,
2581 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002582 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002583 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002584 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002585 SC_Extern,
2586 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002587}
2588
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002589// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2590void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2591 IdentifierInfo *getSuperClassIdent =
2592 &Context->Idents.get("class_getSuperclass");
2593 llvm::SmallVector<QualType, 16> ArgTys;
2594 ArgTys.push_back(Context->getObjCClassType());
2595 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2596 &ArgTys[0], ArgTys.size(),
2597 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002598 false, false, 0, 0,
2599 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002600 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002601 SourceLocation(),
2602 getSuperClassIdent,
2603 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002604 SC_Extern,
2605 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002606 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002607}
2608
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002609// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002610void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002611 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2612 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002613 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002614 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002615 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002616 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002617 false, false, 0, 0,
2618 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002619 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002620 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002621 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002622 SC_Extern,
2623 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002624}
2625
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002626Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002627 QualType strType = getConstantStringStructType();
2628
2629 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002630
2631 std::string tmpName = InFileName;
2632 unsigned i;
2633 for (i=0; i < tmpName.length(); i++) {
2634 char c = tmpName.at(i);
2635 // replace any non alphanumeric characters with '_'.
2636 if (!isalpha(c) && (c < '0' || c > '9'))
2637 tmpName[i] = '_';
2638 }
2639 S += tmpName;
2640 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002641 S += utostr(NumObjCStringLiterals++);
2642
Steve Naroff00a31762008-03-27 22:29:16 +00002643 Preamble += "static __NSConstantStringImpl " + S;
2644 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2645 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002646 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002647 std::string prettyBufS;
2648 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002649 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2650 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002651 Preamble += prettyBuf.str();
2652 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002653 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002654
2655 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002656 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002657 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002658 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2659 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002660 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002661 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002662 VK_RValue, OK_Ordinary,
2663 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002664 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002665 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002666 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002667 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002668 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002669 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002670}
2671
Steve Naroff7fa2f042007-11-15 10:28:18 +00002672// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002673QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002674 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002675 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002676 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002677 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002678 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002679
Steve Naroff7fa2f042007-11-15 10:28:18 +00002680 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002681 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002682 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002683 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002684
Steve Naroff7fa2f042007-11-15 10:28:18 +00002685 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002686 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002687 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2688 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002689 FieldTypes[i], 0,
2690 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002691 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693
Douglas Gregord5058122010-02-11 01:19:42 +00002694 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002695 }
2696 return Context->getTagDeclType(SuperStructDecl);
2697}
2698
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002699QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002700 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002701 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002702 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002703 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002704 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Naroffce8e8862008-03-15 00:55:56 +00002706 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002707 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002708 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002709 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002710 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002711 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002712 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002713 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002714
Steve Naroffce8e8862008-03-15 00:55:56 +00002715 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002716 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002717 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2718 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002719 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002720 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002721 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002722 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002723 }
2724
Douglas Gregord5058122010-02-11 01:19:42 +00002725 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002726 }
2727 return Context->getTagDeclType(ConstantStringDecl);
2728}
2729
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002730Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2731 SourceLocation StartLoc,
2732 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002733 if (!SelGetUidFunctionDecl)
2734 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002735 if (!MsgSendFunctionDecl)
2736 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002737 if (!MsgSendSuperFunctionDecl)
2738 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002739 if (!MsgSendStretFunctionDecl)
2740 SynthMsgSendStretFunctionDecl();
2741 if (!MsgSendSuperStretFunctionDecl)
2742 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002743 if (!MsgSendFpretFunctionDecl)
2744 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002745 if (!GetClassFunctionDecl)
2746 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002747 if (!GetSuperClassFunctionDecl)
2748 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002749 if (!GetMetaClassFunctionDecl)
2750 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002751
Steve Naroff7fa2f042007-11-15 10:28:18 +00002752 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002753 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2754 // May need to use objc_msgSend_stret() as well.
2755 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002756 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2757 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002758 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002759 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002760 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002761 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Steve Naroff574440f2007-10-24 22:48:43 +00002764 // Synthesize a call to objc_msgSend().
2765 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 switch (Exp->getReceiverKind()) {
2767 case ObjCMessageExpr::SuperClass: {
2768 MsgSendFlavor = MsgSendSuperFunctionDecl;
2769 if (MsgSendStretFlavor)
2770 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2771 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregor9a129192010-04-21 00:45:42 +00002773 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002774
Douglas Gregor9a129192010-04-21 00:45:42 +00002775 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002776
Douglas Gregor9a129192010-04-21 00:45:42 +00002777 // set the receiver to self, the first argument to all methods.
2778 InitExprs.push_back(
2779 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002780 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002781 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002782 Context->getObjCIdType(),
2783 VK_RValue,
2784 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2788 llvm::SmallVector<Expr*, 8> ClsExprs;
2789 QualType argType = Context->getPointerType(Context->CharTy);
2790 ClsExprs.push_back(StringLiteral::Create(*Context,
2791 ClassDecl->getIdentifier()->getNameStart(),
2792 ClassDecl->getIdentifier()->getLength(),
2793 false, argType, SourceLocation()));
2794 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2795 &ClsExprs[0],
2796 ClsExprs.size(),
2797 StartLoc,
2798 EndLoc);
2799 // (Class)objc_getClass("CurrentClass")
2800 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2801 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002802 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002803 ClsExprs.clear();
2804 ClsExprs.push_back(ArgExpr);
2805 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2806 &ClsExprs[0], ClsExprs.size(),
2807 StartLoc, EndLoc);
2808
2809 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2810 // To turn off a warning, type-cast to 'id'
2811 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2812 NoTypeInfoCStyleCastExpr(Context,
2813 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002814 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002815 // struct objc_super
2816 QualType superType = getSuperStructType();
2817 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002818
Douglas Gregor9a129192010-04-21 00:45:42 +00002819 if (LangOpts.Microsoft) {
2820 SynthSuperContructorFunctionDecl();
2821 // Simulate a contructor call...
2822 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002823 superType, VK_LValue,
2824 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002825 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2826 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002827 superType, VK_LValue,
2828 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002829 // The code for super is a little tricky to prevent collision with
2830 // the structure definition in the header. The rewriter has it's own
2831 // internal definition (__rw_objc_super) that is uses. This is why
2832 // we need the cast below. For example:
2833 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2834 //
John McCalle3027922010-08-25 11:45:40 +00002835 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002836 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002837 VK_RValue, OK_Ordinary,
2838 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2840 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002841 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002842 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002843 // (struct objc_super) { <exprs from above> }
2844 InitListExpr *ILE =
2845 new (Context) InitListExpr(*Context, SourceLocation(),
2846 &InitExprs[0], InitExprs.size(),
2847 SourceLocation());
2848 TypeSourceInfo *superTInfo
2849 = Context->getTrivialTypeSourceInfo(superType);
2850 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002851 superType, VK_LValue,
2852 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002853 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002854 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002855 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002856 VK_RValue, OK_Ordinary,
2857 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002858 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002859 MsgExprs.push_back(SuperRep);
2860 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002861 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002862
2863 case ObjCMessageExpr::Class: {
2864 llvm::SmallVector<Expr*, 8> ClsExprs;
2865 QualType argType = Context->getPointerType(Context->CharTy);
2866 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002867 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002868 IdentifierInfo *clsName = Class->getIdentifier();
2869 ClsExprs.push_back(StringLiteral::Create(*Context,
2870 clsName->getNameStart(),
2871 clsName->getLength(),
2872 false, argType,
2873 SourceLocation()));
2874 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2875 &ClsExprs[0],
2876 ClsExprs.size(),
2877 StartLoc, EndLoc);
2878 MsgExprs.push_back(Cls);
2879 break;
2880 }
2881
2882 case ObjCMessageExpr::SuperInstance:{
2883 MsgSendFlavor = MsgSendSuperFunctionDecl;
2884 if (MsgSendStretFlavor)
2885 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2886 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2887 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2888 llvm::SmallVector<Expr*, 4> InitExprs;
2889
2890 InitExprs.push_back(
2891 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002892 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002893 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002894 Context->getObjCIdType(),
2895 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002896 ); // set the 'receiver'.
2897
2898 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2899 llvm::SmallVector<Expr*, 8> ClsExprs;
2900 QualType argType = Context->getPointerType(Context->CharTy);
2901 ClsExprs.push_back(StringLiteral::Create(*Context,
2902 ClassDecl->getIdentifier()->getNameStart(),
2903 ClassDecl->getIdentifier()->getLength(),
2904 false, argType, SourceLocation()));
2905 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2906 &ClsExprs[0],
2907 ClsExprs.size(),
2908 StartLoc, EndLoc);
2909 // (Class)objc_getClass("CurrentClass")
2910 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2911 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002912 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002913 ClsExprs.clear();
2914 ClsExprs.push_back(ArgExpr);
2915 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2916 &ClsExprs[0], ClsExprs.size(),
2917 StartLoc, EndLoc);
2918
2919 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2920 // To turn off a warning, type-cast to 'id'
2921 InitExprs.push_back(
2922 // set 'super class', using class_getSuperclass().
2923 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002924 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002925 // struct objc_super
2926 QualType superType = getSuperStructType();
2927 Expr *SuperRep;
2928
2929 if (LangOpts.Microsoft) {
2930 SynthSuperContructorFunctionDecl();
2931 // Simulate a contructor call...
2932 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002933 superType, VK_LValue,
2934 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002935 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2936 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002937 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002938 // The code for super is a little tricky to prevent collision with
2939 // the structure definition in the header. The rewriter has it's own
2940 // internal definition (__rw_objc_super) that is uses. This is why
2941 // we need the cast below. For example:
2942 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2943 //
John McCalle3027922010-08-25 11:45:40 +00002944 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002945 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002946 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002947 SourceLocation());
2948 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2949 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002950 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002951 } else {
2952 // (struct objc_super) { <exprs from above> }
2953 InitListExpr *ILE =
2954 new (Context) InitListExpr(*Context, SourceLocation(),
2955 &InitExprs[0], InitExprs.size(),
2956 SourceLocation());
2957 TypeSourceInfo *superTInfo
2958 = Context->getTrivialTypeSourceInfo(superType);
2959 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002960 superType, VK_RValue, ILE,
2961 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002962 }
2963 MsgExprs.push_back(SuperRep);
2964 break;
2965 }
2966
2967 case ObjCMessageExpr::Instance: {
2968 // Remove all type-casts because it may contain objc-style types; e.g.
2969 // Foo<Proto> *.
2970 Expr *recExpr = Exp->getInstanceReceiver();
2971 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2972 recExpr = CE->getSubExpr();
2973 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002974 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002975 MsgExprs.push_back(recExpr);
2976 break;
2977 }
2978 }
2979
Steve Naroffa397efd2007-11-03 11:27:19 +00002980 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002981 llvm::SmallVector<Expr*, 8> SelExprs;
2982 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002983 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002984 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002985 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002986 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002987 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002988 &SelExprs[0], SelExprs.size(),
2989 StartLoc,
2990 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002991 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002992
Steve Naroff574440f2007-10-24 22:48:43 +00002993 // Now push any user supplied arguments.
2994 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002995 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002996 // Make all implicit casts explicit...ICE comes in handy:-)
2997 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2998 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002999 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003000 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00003001 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003002 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003003 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00003004 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003005 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003006 }
3007 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00003008 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003009 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003010 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003011 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003012 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003013 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003014 }
Mike Stump11289f42009-09-09 15:08:12 +00003015 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003016 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003017 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3018 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003019 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003020 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003021 }
Steve Narofff36987c2007-11-04 22:37:50 +00003022 // Generate the funky cast.
3023 CastExpr *cast;
3024 llvm::SmallVector<QualType, 8> ArgTypes;
3025 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003026
Steve Narofff36987c2007-11-04 22:37:50 +00003027 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003028 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3029 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3030 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003031 ArgTypes.push_back(Context->getObjCIdType());
3032 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003033 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003034 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003035 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3036 E = OMD->param_end(); PI != E; ++PI) {
3037 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003038 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003039 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003040 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003041 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003042 ArgTypes.push_back(t);
3043 }
Chris Lattnera4997152009-02-20 18:43:26 +00003044 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3045 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003046 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003047 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003048 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003049 }
3050 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003051 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003052
Steve Narofff36987c2007-11-04 22:37:50 +00003053 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003054 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003055 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003056
Mike Stump11289f42009-09-09 15:08:12 +00003057 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003058 // If we don't do this cast, we get the following bizarre warning/note:
3059 // xx.m:13: warning: function called through a non-compatible type
3060 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003061 cast = NoTypeInfoCStyleCastExpr(Context,
3062 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003063 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003064
Steve Narofff36987c2007-11-04 22:37:50 +00003065 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003066 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003067 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003068 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003069 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003070 false, false, 0, 0,
3071 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003072 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003073 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003074 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003075
3076 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003077 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003078
John McCall9dd450b2009-09-21 23:43:11 +00003079 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003080 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003081 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003082 FT->getResultType(), VK_RValue,
3083 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003084 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003085 if (MsgSendStretFlavor) {
3086 // We have the method which returns a struct/union. Must also generate
3087 // call to objc_msgSend_stret and hang both varieties on a conditional
3088 // expression which dictate which one to envoke depending on size of
3089 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003090
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003091 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003092 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003093 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003094 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003095 cast = NoTypeInfoCStyleCastExpr(Context,
3096 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003097 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003098 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003099 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003100 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003101 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003102 false, false, 0, 0,
3103 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003104 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003105 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003106 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003107
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003108 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003109 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003110
John McCall9dd450b2009-09-21 23:43:11 +00003111 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003112 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003113 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003114 FT->getResultType(), VK_RValue,
3115 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003116
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003117 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003118 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003119 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003120 Context->getSizeType(),
3121 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003122 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3123 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3124 // For X86 it is more complicated and some kind of target specific routine
3125 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003126 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003127 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003128 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3129 llvm::APInt(IntSize, 8),
3130 Context->IntTy,
3131 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003132 BinaryOperator *lessThanExpr =
3133 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3134 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003135 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003136 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003137 new (Context) ConditionalOperator(lessThanExpr,
3138 SourceLocation(), CE,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003139 SourceLocation(), STCE, (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00003140 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003141 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3142 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003143 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003144 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003145 return ReplacingStmt;
3146}
3147
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003148Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003149 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3150 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003151
Steve Naroff574440f2007-10-24 22:48:43 +00003152 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003153 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003154
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003155 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003156 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003157}
3158
Steve Naroffd9803712009-04-29 16:37:50 +00003159// typedef struct objc_object Protocol;
3160QualType RewriteObjC::getProtocolType() {
3161 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003162 TypeSourceInfo *TInfo
3163 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003164 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003165 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003166 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003167 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003168 }
3169 return Context->getTypeDeclType(ProtocolTypeDecl);
3170}
3171
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003172/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003173/// a synthesized/forward data reference (to the protocol's metadata).
3174/// The forward references (and metadata) are generated in
3175/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003176Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003177 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3178 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003179 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003180 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003181 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003182 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3183 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003184 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003185 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003186 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003187 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003188 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003189 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003190 ReplaceStmt(Exp, castExpr);
3191 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003192 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003193 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003194
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003195}
3196
Mike Stump11289f42009-09-09 15:08:12 +00003197bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003198 const char *endBuf) {
3199 while (startBuf < endBuf) {
3200 if (*startBuf == '#') {
3201 // Skip whitespace.
3202 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3203 ;
3204 if (!strncmp(startBuf, "if", strlen("if")) ||
3205 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3206 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3207 !strncmp(startBuf, "define", strlen("define")) ||
3208 !strncmp(startBuf, "undef", strlen("undef")) ||
3209 !strncmp(startBuf, "else", strlen("else")) ||
3210 !strncmp(startBuf, "elif", strlen("elif")) ||
3211 !strncmp(startBuf, "endif", strlen("endif")) ||
3212 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3213 !strncmp(startBuf, "include", strlen("include")) ||
3214 !strncmp(startBuf, "import", strlen("import")) ||
3215 !strncmp(startBuf, "include_next", strlen("include_next")))
3216 return true;
3217 }
3218 startBuf++;
3219 }
3220 return false;
3221}
3222
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003223/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003224/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003225void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003226 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003227 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003228 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003229 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003230 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003231 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003232 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003233 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003234 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003235 SourceLocation LocStart = CDecl->getLocStart();
3236 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003237
Steve Naroffdde78982007-11-14 19:25:57 +00003238 const char *startBuf = SM->getCharacterData(LocStart);
3239 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003240
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003241 // If no ivars and no root or if its root, directly or indirectly,
3242 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003243 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3244 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003245 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003246 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003247 return;
3248 }
Mike Stump11289f42009-09-09 15:08:12 +00003249
3250 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003251 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003252 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003253 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003254 if (LangOpts.Microsoft)
3255 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003256
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003257 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003258 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003259 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003260 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003261 // If the buffer contains preprocessor directives, we do more fine-grained
3262 // rewrites. This is intended to fix code that looks like (which occurs in
3263 // NSURL.h, for example):
3264 //
3265 // #ifdef XYZ
3266 // @interface Foo : NSObject
3267 // #else
3268 // @interface FooBar : NSObject
3269 // #endif
3270 // {
3271 // int i;
3272 // }
3273 // @end
3274 //
3275 // This clause is segregated to avoid breaking the common case.
3276 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003277 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003278 CDecl->getClassLoc();
3279 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003280 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003281
Chris Lattnerf5b77512009-02-20 18:18:36 +00003282 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003283 // advance to the end of the referenced protocols.
3284 while (endHeader < cursor && *endHeader != '>') endHeader++;
3285 endHeader++;
3286 }
3287 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003288 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003289 } else {
3290 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003291 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003292 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003293 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003294 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003295 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003296 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003297 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003298 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003299
Steve Naroffdde78982007-11-14 19:25:57 +00003300 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003301 SourceLocation OnePastCurly =
3302 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003303 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003304 }
3305 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003306
Steve Naroffdde78982007-11-14 19:25:57 +00003307 // Now comment out any visibility specifiers.
3308 while (cursor < endBuf) {
3309 if (*cursor == '@') {
3310 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003311 // Skip whitespace.
3312 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3313 /*scan*/;
3314
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003315 // FIXME: presence of @public, etc. inside comment results in
3316 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003317 if (!strncmp(cursor, "public", strlen("public")) ||
3318 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003319 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003320 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003321 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003322 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003323 // FIXME: If there are cases where '<' is used in ivar declaration part
3324 // of user code, then scan the ivar list and use needToScanForQualifiers
3325 // for type checking.
3326 else if (*cursor == '<') {
3327 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003328 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003329 cursor = strchr(cursor, '>');
3330 cursor++;
3331 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003332 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003333 } else if (*cursor == '^') { // rewrite block specifier.
3334 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003335 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003336 }
Steve Naroffdde78982007-11-14 19:25:57 +00003337 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003338 }
Steve Naroffdde78982007-11-14 19:25:57 +00003339 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003340 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003341 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003342 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003343 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003344 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003345 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003346 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003347 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003348 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003349 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003350 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003351 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003352 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003353}
3354
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003355// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003356/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003357template<typename MethodIterator>
3358void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3359 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003360 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003361 llvm::StringRef prefix,
3362 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003363 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003364 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattner31bc07e2007-12-12 07:46:12 +00003366 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003367 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003368 SEL _cmd;
3369 char *method_types;
3370 void *_imp;
3371 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003372 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003373 Result += "\nstruct _objc_method {\n";
3374 Result += "\tSEL _cmd;\n";
3375 Result += "\tchar *method_types;\n";
3376 Result += "\tvoid *_imp;\n";
3377 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003378
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003379 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003380 }
Mike Stump11289f42009-09-09 15:08:12 +00003381
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003382 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003383
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003384 /* struct {
3385 struct _objc_method_list *next_method;
3386 int method_count;
3387 struct _objc_method method_list[];
3388 }
3389 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003390 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003391 Result += "\nstatic struct {\n";
3392 Result += "\tstruct _objc_method_list *next_method;\n";
3393 Result += "\tint method_count;\n";
3394 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003395 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003396 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003397 Result += prefix;
3398 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3399 Result += "_METHODS_";
3400 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003401 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003402 Result += IsInstanceMethod ? "inst" : "cls";
3403 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003404 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405
Chris Lattner31bc07e2007-12-12 07:46:12 +00003406 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003407 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003408 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003409 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003410 Result += "\", \"";
3411 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003412 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003413 Result += MethodInternalNames[*MethodBegin];
3414 Result += "}\n";
3415 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3416 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003417 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003418 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003419 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003420 Result += "\", \"";
3421 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003422 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003423 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003424 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003425 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003426 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003427}
3428
Steve Naroffd9803712009-04-29 16:37:50 +00003429/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003430void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003431RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3432 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003433 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003434
3435 // Output struct protocol_methods holder of method selector and type.
3436 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3437 /* struct protocol_methods {
3438 SEL _cmd;
3439 char *method_types;
3440 }
3441 */
3442 Result += "\nstruct _protocol_methods {\n";
3443 Result += "\tstruct objc_selector *_cmd;\n";
3444 Result += "\tchar *method_types;\n";
3445 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003446
Steve Naroffd9803712009-04-29 16:37:50 +00003447 objc_protocol_methods = true;
3448 }
3449 // Do not synthesize the protocol more than once.
3450 if (ObjCSynthesizedProtocols.count(PDecl))
3451 return;
Mike Stump11289f42009-09-09 15:08:12 +00003452
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003453 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3454 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3455 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003456 /* struct _objc_protocol_method_list {
3457 int protocol_method_count;
3458 struct protocol_methods protocols[];
3459 }
Steve Naroff251084d2008-03-12 01:06:30 +00003460 */
Steve Naroffd9803712009-04-29 16:37:50 +00003461 Result += "\nstatic struct {\n";
3462 Result += "\tint protocol_method_count;\n";
3463 Result += "\tstruct _protocol_methods protocol_methods[";
3464 Result += utostr(NumMethods);
3465 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3466 Result += PDecl->getNameAsString();
3467 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3468 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003469
Steve Naroffd9803712009-04-29 16:37:50 +00003470 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003471 for (ObjCProtocolDecl::instmeth_iterator
3472 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003473 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003474 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003475 Result += "\t ,{{(struct objc_selector *)\"";
3476 else
3477 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003478 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003479 std::string MethodTypeString;
3480 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3481 Result += "\", \"";
3482 Result += MethodTypeString;
3483 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003484 }
Steve Naroffd9803712009-04-29 16:37:50 +00003485 Result += "\t }\n};\n";
3486 }
Mike Stump11289f42009-09-09 15:08:12 +00003487
Steve Naroffd9803712009-04-29 16:37:50 +00003488 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003489 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3490 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003491 if (NumMethods > 0) {
3492 /* struct _objc_protocol_method_list {
3493 int protocol_method_count;
3494 struct protocol_methods protocols[];
3495 }
3496 */
3497 Result += "\nstatic struct {\n";
3498 Result += "\tint protocol_method_count;\n";
3499 Result += "\tstruct _protocol_methods protocol_methods[";
3500 Result += utostr(NumMethods);
3501 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3502 Result += PDecl->getNameAsString();
3503 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3504 "{\n\t";
3505 Result += utostr(NumMethods);
3506 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003507
Steve Naroffd9803712009-04-29 16:37:50 +00003508 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003509 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003510 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003511 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003512 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003513 Result += "\t ,{{(struct objc_selector *)\"";
3514 else
3515 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003516 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003517 std::string MethodTypeString;
3518 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3519 Result += "\", \"";
3520 Result += MethodTypeString;
3521 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003522 }
Steve Naroffd9803712009-04-29 16:37:50 +00003523 Result += "\t }\n};\n";
3524 }
3525
3526 // Output:
3527 /* struct _objc_protocol {
3528 // Objective-C 1.0 extensions
3529 struct _objc_protocol_extension *isa;
3530 char *protocol_name;
3531 struct _objc_protocol **protocol_list;
3532 struct _objc_protocol_method_list *instance_methods;
3533 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003534 };
Steve Naroffd9803712009-04-29 16:37:50 +00003535 */
3536 static bool objc_protocol = false;
3537 if (!objc_protocol) {
3538 Result += "\nstruct _objc_protocol {\n";
3539 Result += "\tstruct _objc_protocol_extension *isa;\n";
3540 Result += "\tchar *protocol_name;\n";
3541 Result += "\tstruct _objc_protocol **protocol_list;\n";
3542 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3543 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003544 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003545
Steve Naroffd9803712009-04-29 16:37:50 +00003546 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003547 }
Mike Stump11289f42009-09-09 15:08:12 +00003548
Steve Naroffd9803712009-04-29 16:37:50 +00003549 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3550 Result += PDecl->getNameAsString();
3551 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3552 "{\n\t0, \"";
3553 Result += PDecl->getNameAsString();
3554 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003555 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003556 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3557 Result += PDecl->getNameAsString();
3558 Result += ", ";
3559 }
3560 else
3561 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003562 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003563 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3564 Result += PDecl->getNameAsString();
3565 Result += "\n";
3566 }
3567 else
3568 Result += "0\n";
3569 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003570
Steve Naroffd9803712009-04-29 16:37:50 +00003571 // Mark this protocol as having been generated.
3572 if (!ObjCSynthesizedProtocols.insert(PDecl))
3573 assert(false && "protocol already synthesized");
3574
3575}
3576
3577void RewriteObjC::
3578RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003579 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003580 std::string &Result) {
3581 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003582
Steve Naroffd9803712009-04-29 16:37:50 +00003583 for (unsigned i = 0; i != Protocols.size(); i++)
3584 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3585
Chris Lattner388f6e92008-07-21 21:33:21 +00003586 // Output the top lovel protocol meta-data for the class.
3587 /* struct _objc_protocol_list {
3588 struct _objc_protocol_list *next;
3589 int protocol_count;
3590 struct _objc_protocol *class_protocols[];
3591 }
3592 */
3593 Result += "\nstatic struct {\n";
3594 Result += "\tstruct _objc_protocol_list *next;\n";
3595 Result += "\tint protocol_count;\n";
3596 Result += "\tstruct _objc_protocol *class_protocols[";
3597 Result += utostr(Protocols.size());
3598 Result += "];\n} _OBJC_";
3599 Result += prefix;
3600 Result += "_PROTOCOLS_";
3601 Result += ClassName;
3602 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3603 "{\n\t0, ";
3604 Result += utostr(Protocols.size());
3605 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003606
Chris Lattner388f6e92008-07-21 21:33:21 +00003607 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003608 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003609 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003610
Chris Lattner388f6e92008-07-21 21:33:21 +00003611 for (unsigned i = 1; i != Protocols.size(); i++) {
3612 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003613 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003614 Result += "\n";
3615 }
3616 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003617}
3618
Steve Naroffd9803712009-04-29 16:37:50 +00003619
Mike Stump11289f42009-09-09 15:08:12 +00003620/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003621/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003622void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003623 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003624 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003625 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003626 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003627 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003628 CDecl = CDecl->getNextClassCategory())
3629 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3630 break;
Mike Stump11289f42009-09-09 15:08:12 +00003631
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003632 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003633 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003634 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003635
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003636 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003637 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003638 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003639
3640 // If any of our property implementations have associated getters or
3641 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003642 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3643 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003644 Prop != PropEnd; ++Prop) {
3645 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3646 continue;
3647 if (!(*Prop)->getPropertyIvarDecl())
3648 continue;
3649 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3650 if (!PD)
3651 continue;
3652 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3653 InstanceMethods.push_back(Getter);
3654 if (PD->isReadOnly())
3655 continue;
3656 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3657 InstanceMethods.push_back(Setter);
3658 }
3659 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003660 true, "CATEGORY_", FullCategoryName.c_str(),
3661 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003662
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003663 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003664 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003665 false, "CATEGORY_", FullCategoryName.c_str(),
3666 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003667
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003668 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003669 // Null CDecl is case of a category implementation with no category interface
3670 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003671 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003672 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003673 /* struct _objc_category {
3674 char *category_name;
3675 char *class_name;
3676 struct _objc_method_list *instance_methods;
3677 struct _objc_method_list *class_methods;
3678 struct _objc_protocol_list *protocols;
3679 // Objective-C 1.0 extensions
3680 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003681 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003682 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003683 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003684 */
Mike Stump11289f42009-09-09 15:08:12 +00003685
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003686 static bool objc_category = false;
3687 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003688 Result += "\nstruct _objc_category {\n";
3689 Result += "\tchar *category_name;\n";
3690 Result += "\tchar *class_name;\n";
3691 Result += "\tstruct _objc_method_list *instance_methods;\n";
3692 Result += "\tstruct _objc_method_list *class_methods;\n";
3693 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003694 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003695 Result += "\tstruct _objc_property_list *instance_properties;\n";
3696 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003697 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003698 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003699 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3700 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003701 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003702 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003703 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003706
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003707 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 Result += "\t, (struct _objc_method_list *)"
3709 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3710 Result += FullCategoryName;
3711 Result += "\n";
3712 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003713 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003714 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003715 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003716 Result += "\t, (struct _objc_method_list *)"
3717 "&_OBJC_CATEGORY_CLASS_METHODS_";
3718 Result += FullCategoryName;
3719 Result += "\n";
3720 }
3721 else
3722 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003723
Chris Lattnerf5b77512009-02-20 18:18:36 +00003724 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003725 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003726 Result += FullCategoryName;
3727 Result += "\n";
3728 }
3729 else
3730 Result += "\t, 0\n";
3731 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003732}
3733
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003734/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3735/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003736void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003737 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003738 if (ivar->isBitField()) {
3739 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3740 // place all bitfields at offset 0.
3741 Result += "0";
3742 } else {
3743 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003744 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003745 if (LangOpts.Microsoft)
3746 Result += "_IMPL";
3747 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003748 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003749 Result += ")";
3750 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003751}
3752
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003753//===----------------------------------------------------------------------===//
3754// Meta Data Emission
3755//===----------------------------------------------------------------------===//
3756
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003757void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003758 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003759 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003760
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003761 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003762 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003763 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003764 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003765 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767
Chris Lattner30d23e82007-12-12 07:56:42 +00003768 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003769 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003770 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003771 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003772 if (NumIvars > 0) {
3773 static bool objc_ivar = false;
3774 if (!objc_ivar) {
3775 /* struct _objc_ivar {
3776 char *ivar_name;
3777 char *ivar_type;
3778 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003779 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003780 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003781 Result += "\nstruct _objc_ivar {\n";
3782 Result += "\tchar *ivar_name;\n";
3783 Result += "\tchar *ivar_type;\n";
3784 Result += "\tint ivar_offset;\n";
3785 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003786
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003787 objc_ivar = true;
3788 }
3789
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003790 /* struct {
3791 int ivar_count;
3792 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003793 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003794 */
Mike Stump11289f42009-09-09 15:08:12 +00003795 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003796 Result += "\tint ivar_count;\n";
3797 Result += "\tstruct _objc_ivar ivar_list[";
3798 Result += utostr(NumIvars);
3799 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003800 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003801 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003802 "{\n\t";
3803 Result += utostr(NumIvars);
3804 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003805
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003806 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003807 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003808 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003809 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003810 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003811 IV != IVEnd; ++IV)
3812 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003813 IVI = IDecl->ivar_begin();
3814 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003815 } else {
3816 IVI = CDecl->ivar_begin();
3817 IVE = CDecl->ivar_end();
3818 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003819 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003820 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003821 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003822 std::string TmpString, StrEncoding;
3823 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3824 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003825 Result += StrEncoding;
3826 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003827 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003828 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003829 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003830 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003831 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003832 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003833 std::string TmpString, StrEncoding;
3834 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3835 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003836 Result += StrEncoding;
3837 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003838 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003839 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003840 }
Mike Stump11289f42009-09-09 15:08:12 +00003841
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003842 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003843 }
Mike Stump11289f42009-09-09 15:08:12 +00003844
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003845 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003846 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003847 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003848
3849 // If any of our property implementations have associated getters or
3850 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003851 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3852 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003853 Prop != PropEnd; ++Prop) {
3854 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3855 continue;
3856 if (!(*Prop)->getPropertyIvarDecl())
3857 continue;
3858 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3859 if (!PD)
3860 continue;
3861 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003862 if (!Getter->isDefined())
3863 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003864 if (PD->isReadOnly())
3865 continue;
3866 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003867 if (!Setter->isDefined())
3868 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003869 }
3870 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003871 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003872
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003873 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003874 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003875 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003876
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003877 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003878 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003879 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003880
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003881 // Declaration of class/meta-class metadata
3882 /* struct _objc_class {
3883 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003884 const char *super_class_name;
3885 char *name;
3886 long version;
3887 long info;
3888 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003889 struct _objc_ivar_list *ivars;
3890 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003891 struct objc_cache *cache;
3892 struct objc_protocol_list *protocols;
3893 const char *ivar_layout;
3894 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003895 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003896 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003897 static bool objc_class = false;
3898 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003899 Result += "\nstruct _objc_class {\n";
3900 Result += "\tstruct _objc_class *isa;\n";
3901 Result += "\tconst char *super_class_name;\n";
3902 Result += "\tchar *name;\n";
3903 Result += "\tlong version;\n";
3904 Result += "\tlong info;\n";
3905 Result += "\tlong instance_size;\n";
3906 Result += "\tstruct _objc_ivar_list *ivars;\n";
3907 Result += "\tstruct _objc_method_list *methods;\n";
3908 Result += "\tstruct objc_cache *cache;\n";
3909 Result += "\tstruct _objc_protocol_list *protocols;\n";
3910 Result += "\tconst char *ivar_layout;\n";
3911 Result += "\tstruct _objc_class_ext *ext;\n";
3912 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003913 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003914 }
Mike Stump11289f42009-09-09 15:08:12 +00003915
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003916 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003917 ObjCInterfaceDecl *RootClass = 0;
3918 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003919 while (SuperClass) {
3920 RootClass = SuperClass;
3921 SuperClass = SuperClass->getSuperClass();
3922 }
3923 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003924
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003925 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003926 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003927 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003928 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003929 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003930 Result += "\"";
3931
3932 if (SuperClass) {
3933 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003934 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003935 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003936 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003937 Result += "\"";
3938 }
3939 else {
3940 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003941 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003942 Result += "\"";
3943 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003944 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003945 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003946 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003947 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003948 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003949 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003950 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003951 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003952 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003953 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003954 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003955 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003956 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003957 Result += ",0,0\n";
3958 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003959 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003960 Result += "\t,0,0,0,0\n";
3961 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003962
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003963 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003964 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003965 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003966 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003967 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003969 if (SuperClass) {
3970 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003971 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003972 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003973 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003974 Result += "\"";
3975 }
3976 else {
3977 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003978 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003979 Result += "\"";
3980 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003981 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003982 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003983 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003984 Result += ",0";
3985 else {
3986 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003987 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003988 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003989 if (LangOpts.Microsoft)
3990 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003991 Result += ")";
3992 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003993 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003994 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003995 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003996 Result += "\n\t";
3997 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003998 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003999 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004000 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00004001 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004002 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00004003 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004004 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004005 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004006 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00004007 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00004008 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004009 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004010 Result += ", 0,0\n";
4011 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004012 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004013 Result += ",0,0,0\n";
4014 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004015}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004016
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004017/// RewriteImplementations - This routine rewrites all method implementations
4018/// and emits meta-data.
4019
Steve Narofff8cfd162008-11-13 20:07:04 +00004020void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004021 int ClsDefCount = ClassImplementation.size();
4022 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004023
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004024 // Rewrite implemented methods
4025 for (int i = 0; i < ClsDefCount; i++)
4026 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004027
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004028 for (int i = 0; i < CatDefCount; i++)
4029 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004030}
Mike Stump11289f42009-09-09 15:08:12 +00004031
Steve Narofff8cfd162008-11-13 20:07:04 +00004032void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4033 int ClsDefCount = ClassImplementation.size();
4034 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004035
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004036 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004037 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004038 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004039
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004040 // For each implemented category, write out all its meta data.
4041 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004042 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004043
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004044 // Write objc_symtab metadata
4045 /*
4046 struct _objc_symtab
4047 {
4048 long sel_ref_cnt;
4049 SEL *refs;
4050 short cls_def_cnt;
4051 short cat_def_cnt;
4052 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004053 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004054 */
Mike Stump11289f42009-09-09 15:08:12 +00004055
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004056 Result += "\nstruct _objc_symtab {\n";
4057 Result += "\tlong sel_ref_cnt;\n";
4058 Result += "\tSEL *refs;\n";
4059 Result += "\tshort cls_def_cnt;\n";
4060 Result += "\tshort cat_def_cnt;\n";
4061 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4062 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004063
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004064 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004065 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004066 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004067 + ", " + utostr(CatDefCount) + "\n";
4068 for (int i = 0; i < ClsDefCount; i++) {
4069 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004070 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004071 Result += "\n";
4072 }
Mike Stump11289f42009-09-09 15:08:12 +00004073
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004074 for (int i = 0; i < CatDefCount; i++) {
4075 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004076 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004077 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004078 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004079 Result += "\n";
4080 }
Mike Stump11289f42009-09-09 15:08:12 +00004081
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004082 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004083
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004084 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004085
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004086 /*
4087 struct _objc_module {
4088 long version;
4089 long size;
4090 const char *name;
4091 struct _objc_symtab *symtab;
4092 }
4093 */
Mike Stump11289f42009-09-09 15:08:12 +00004094
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004095 Result += "\nstruct _objc_module {\n";
4096 Result += "\tlong version;\n";
4097 Result += "\tlong size;\n";
4098 Result += "\tconst char *name;\n";
4099 Result += "\tstruct _objc_symtab *symtab;\n";
4100 Result += "};\n\n";
4101 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004102 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004103 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004104 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004105 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004106
4107 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004108 if (ProtocolExprDecls.size()) {
4109 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4110 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004111 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004112 E = ProtocolExprDecls.end(); I != E; ++I) {
4113 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4114 Result += (*I)->getNameAsString();
4115 Result += " = &_OBJC_PROTOCOL_";
4116 Result += (*I)->getNameAsString();
4117 Result += ";\n";
4118 }
4119 Result += "#pragma data_seg(pop)\n\n";
4120 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004121 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004122 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004123 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4124 Result += "&_OBJC_MODULES;\n";
4125 Result += "#pragma data_seg(pop)\n\n";
4126 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004127}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004128
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004129void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4130 const std::string &Name,
4131 ValueDecl *VD) {
4132 assert(BlockByRefDeclNo.count(VD) &&
4133 "RewriteByRefString: ByRef decl missing");
4134 ResultStr += "struct __Block_byref_" + Name +
4135 "_" + utostr(BlockByRefDeclNo[VD]) ;
4136}
4137
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004138static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4139 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4140 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4141 return false;
4142}
4143
Steve Naroff677ab3a2008-10-27 17:20:55 +00004144std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004145 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004146 std::string Tag) {
4147 const FunctionType *AFT = CE->getFunctionType();
4148 QualType RT = AFT->getResultType();
4149 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004150 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004151 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004152
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004154
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004155 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004156 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004157 // block (to reference imported block decl refs).
4158 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004159 } else if (BD->param_empty()) {
4160 S += "(" + StructRef + " *__cself)";
4161 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004162 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163 assert(FT && "SynthesizeBlockFunc: No function proto");
4164 S += '(';
4165 // first add the implicit argument.
4166 S += StructRef + " *__cself, ";
4167 std::string ParamStr;
4168 for (BlockDecl::param_iterator AI = BD->param_begin(),
4169 E = BD->param_end(); AI != E; ++AI) {
4170 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004171 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004172 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004173 if (convertBlockPointerToFunctionPointer(QT))
4174 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004175 else
4176 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177 S += ParamStr;
4178 }
4179 if (FT->isVariadic()) {
4180 if (!BD->param_empty()) S += ", ";
4181 S += "...";
4182 }
4183 S += ')';
4184 }
4185 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004186
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 // Create local declarations to avoid rewriting all closure decl ref exprs.
4188 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004189 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004190 E = BlockByRefDecls.end(); I != E; ++I) {
4191 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004192 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004193 std::string TypeString;
4194 RewriteByRefString(TypeString, Name, (*I));
4195 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004196 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004197 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004198 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004200 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004201 E = BlockByCopyDecls.end(); I != E; ++I) {
4202 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004203 // Handle nested closure invocation. For example:
4204 //
4205 // void (^myImportedClosure)(void);
4206 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004207 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 // void (^anotherClosure)(void);
4209 // anotherClosure = ^(void) {
4210 // myImportedClosure(); // import and invoke the closure
4211 // };
4212 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004213 if (isTopLevelBlockPointerType((*I)->getType())) {
4214 RewriteBlockPointerTypeVariable(S, (*I));
4215 S += " = (";
4216 RewriteBlockPointerType(S, (*I)->getType());
4217 S += ")";
4218 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4219 }
4220 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004221 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004222 QualType QT = (*I)->getType();
4223 if (HasLocalVariableExternalStorage(*I))
4224 QT = Context->getPointerType(QT);
4225 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004226 S += Name + " = __cself->" +
4227 (*I)->getNameAsString() + "; // bound by copy\n";
4228 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004229 }
4230 std::string RewrittenStr = RewrittenBlockExprs[CE];
4231 const char *cstr = RewrittenStr.c_str();
4232 while (*cstr++ != '{') ;
4233 S += cstr;
4234 S += "\n";
4235 return S;
4236}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004237
Steve Naroff677ab3a2008-10-27 17:20:55 +00004238std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004239 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004240 std::string Tag) {
4241 std::string StructRef = "struct " + Tag;
4242 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004243
Steve Naroff677ab3a2008-10-27 17:20:55 +00004244 S += funcName;
4245 S += "_block_copy_" + utostr(i);
4246 S += "(" + StructRef;
4247 S += "*dst, " + StructRef;
4248 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004249 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004251 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004252 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004253 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004254 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004255 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004256 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004257 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004258 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004260 S += "}\n";
4261
Steve Naroff677ab3a2008-10-27 17:20:55 +00004262 S += "\nstatic void __";
4263 S += funcName;
4264 S += "_block_dispose_" + utostr(i);
4265 S += "(" + StructRef;
4266 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004267 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004268 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004269 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004270 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004271 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004272 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004273 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004274 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004275 }
Mike Stump11289f42009-09-09 15:08:12 +00004276 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 return S;
4278}
4279
Steve Naroff30484702009-12-06 21:14:13 +00004280std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4281 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004282 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004283 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004284
Steve Naroff677ab3a2008-10-27 17:20:55 +00004285 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004286 S += " struct " + Desc;
4287 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004288
Steve Naroff30484702009-12-06 21:14:13 +00004289 Constructor += "(void *fp, "; // Invoke function pointer.
4290 Constructor += "struct " + Desc; // Descriptor pointer.
4291 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004292
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 if (BlockDeclRefs.size()) {
4294 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004295 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004296 E = BlockByCopyDecls.end(); I != E; ++I) {
4297 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004298 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 std::string ArgName = "_" + FieldName;
4300 // Handle nested closure invocation. For example:
4301 //
4302 // void (^myImportedBlock)(void);
4303 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004304 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 // void (^anotherBlock)(void);
4306 // anotherBlock = ^(void) {
4307 // myImportedBlock(); // import and invoke the closure
4308 // };
4309 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004310 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 S += "struct __block_impl *";
4312 Constructor += ", void *" + ArgName;
4313 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004314 QualType QT = (*I)->getType();
4315 if (HasLocalVariableExternalStorage(*I))
4316 QT = Context->getPointerType(QT);
4317 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4318 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004319 Constructor += ", " + ArgName;
4320 }
4321 S += FieldName + ";\n";
4322 }
4323 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004324 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 E = BlockByRefDecls.end(); I != E; ++I) {
4326 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004327 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 std::string ArgName = "_" + FieldName;
4329 // Handle nested closure invocation. For example:
4330 //
4331 // void (^myImportedBlock)(void);
4332 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004333 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004334 // void (^anotherBlock)(void);
4335 // anotherBlock = ^(void) {
4336 // myImportedBlock(); // import and invoke the closure
4337 // };
4338 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004339 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004340 S += "struct __block_impl *";
4341 Constructor += ", void *" + ArgName;
4342 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004343 std::string TypeString;
4344 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004345 TypeString += " *";
4346 FieldName = TypeString + FieldName;
4347 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 Constructor += ", " + ArgName;
4349 }
4350 S += FieldName + "; // by ref\n";
4351 }
4352 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004353 Constructor += ", int flags=0)";
4354 // Initialize all "by copy" arguments.
4355 bool firsTime = true;
4356 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4357 E = BlockByCopyDecls.end(); I != E; ++I) {
4358 std::string Name = (*I)->getNameAsString();
4359 if (firsTime) {
4360 Constructor += " : ";
4361 firsTime = false;
4362 }
4363 else
4364 Constructor += ", ";
4365 if (isTopLevelBlockPointerType((*I)->getType()))
4366 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4367 else
4368 Constructor += Name + "(_" + Name + ")";
4369 }
4370 // Initialize all "by ref" arguments.
4371 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4372 E = BlockByRefDecls.end(); I != E; ++I) {
4373 std::string Name = (*I)->getNameAsString();
4374 if (firsTime) {
4375 Constructor += " : ";
4376 firsTime = false;
4377 }
4378 else
4379 Constructor += ", ";
4380 if (isTopLevelBlockPointerType((*I)->getType()))
4381 Constructor += Name + "((struct __block_impl *)_"
4382 + Name + "->__forwarding)";
4383 else
4384 Constructor += Name + "(_" + Name + "->__forwarding)";
4385 }
4386
4387 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004388 if (GlobalVarDecl)
4389 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4390 else
4391 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004392 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004393
Steve Naroff30484702009-12-06 21:14:13 +00004394 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004395 } else {
4396 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004397 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004398 if (GlobalVarDecl)
4399 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4400 else
4401 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004402 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4403 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004404 }
4405 Constructor += " ";
4406 Constructor += "}\n";
4407 S += Constructor;
4408 S += "};\n";
4409 return S;
4410}
4411
Steve Naroff30484702009-12-06 21:14:13 +00004412std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4413 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004414 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004415 unsigned hasCopy) {
4416 std::string S = "\nstatic struct " + DescTag;
4417
4418 S += " {\n unsigned long reserved;\n";
4419 S += " unsigned long Block_size;\n";
4420 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004421 S += " void (*copy)(struct ";
4422 S += ImplTag; S += "*, struct ";
4423 S += ImplTag; S += "*);\n";
4424
4425 S += " void (*dispose)(struct ";
4426 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004427 }
4428 S += "} ";
4429
4430 S += DescTag + "_DATA = { 0, sizeof(struct ";
4431 S += ImplTag + ")";
4432 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004433 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4434 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004435 }
4436 S += "};\n";
4437 return S;
4438}
4439
Steve Naroff677ab3a2008-10-27 17:20:55 +00004440void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004441 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004442 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004443 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004444 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004445 bool RewriteSC = (GlobalVarDecl &&
4446 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004447 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004448 GlobalVarDecl->getType().getCVRQualifiers());
4449 if (RewriteSC) {
4450 std::string SC(" void __");
4451 SC += GlobalVarDecl->getNameAsString();
4452 SC += "() {}";
4453 InsertText(FunLocStart, SC);
4454 }
4455
Steve Naroff677ab3a2008-10-27 17:20:55 +00004456 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004457 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4458 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004459 // Need to copy-in the inner copied-in variables not actually used in this
4460 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004461 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4462 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4463 ValueDecl *VD = Exp->getDecl();
4464 BlockDeclRefs.push_back(Exp);
4465 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4466 BlockByCopyDeclsPtrSet.insert(VD);
4467 BlockByCopyDecls.push_back(VD);
4468 }
4469 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4470 BlockByRefDeclsPtrSet.insert(VD);
4471 BlockByRefDecls.push_back(VD);
4472 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004473 // imported objects in the inner blocks not used in the outer
4474 // blocks must be copied/disposed in the outer block as well.
4475 if (Exp->isByRef() ||
4476 VD->getType()->isObjCObjectPointerType() ||
4477 VD->getType()->isBlockPointerType())
4478 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004479 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004480
Daniel Dunbar56df9772010-08-17 22:39:59 +00004481 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4482 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004483
Steve Naroff30484702009-12-06 21:14:13 +00004484 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004485
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004486 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004487
Steve Naroff30484702009-12-06 21:14:13 +00004488 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004489
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004490 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004491
4492 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004493 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004494 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004495 }
Steve Naroff30484702009-12-06 21:14:13 +00004496 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4497 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004498 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004499
Steve Naroff677ab3a2008-10-27 17:20:55 +00004500 BlockDeclRefs.clear();
4501 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004502 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004503 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004504 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004505 ImportedBlockDecls.clear();
4506 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004507 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004508 // Must insert any 'const/volatile/static here. Since it has been
4509 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004510 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004511 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004512 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004513 if (GlobalVarDecl->getType().isConstQualified())
4514 SC += "const ";
4515 if (GlobalVarDecl->getType().isVolatileQualified())
4516 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004517 if (GlobalVarDecl->getType().isRestrictQualified())
4518 SC += "restrict ";
4519 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004520 }
4521
Steve Naroff677ab3a2008-10-27 17:20:55 +00004522 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004523 InnerDeclRefsCount.clear();
4524 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004525 RewrittenBlockExprs.clear();
4526}
4527
4528void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4529 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004530 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004531
Steve Naroff677ab3a2008-10-27 17:20:55 +00004532 SynthesizeBlockLiterals(FunLocStart, FuncName);
4533}
4534
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004535static void BuildUniqueMethodName(std::string &Name,
4536 ObjCMethodDecl *MD) {
4537 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004538 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004539 Name += "__" + MD->getSelector().getAsString();
4540 // Convert colons to underscores.
4541 std::string::size_type loc = 0;
4542 while ((loc = Name.find(":", loc)) != std::string::npos)
4543 Name.replace(loc, 1, "_");
4544}
4545
Steve Naroff677ab3a2008-10-27 17:20:55 +00004546void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004547 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4548 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004549 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004550 std::string FuncName;
4551 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004552 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004553}
4554
4555void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4556 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4557 CI != E; ++CI)
4558 if (*CI) {
4559 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4560 GetBlockDeclRefExprs(CBE->getBody());
4561 else
4562 GetBlockDeclRefExprs(*CI);
4563 }
4564 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004565 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004566 // FIXME: Handle enums.
4567 if (!isa<FunctionDecl>(CDRE->getDecl()))
4568 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004569 }
4570 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4571 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4572 BlockDeclRefExpr *BDRE =
4573 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004574 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004575 BlockDeclRefs.push_back(BDRE);
4576 }
4577
Steve Naroff677ab3a2008-10-27 17:20:55 +00004578 return;
4579}
4580
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004581void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4582 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004583 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004584 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4585 CI != E; ++CI)
4586 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004587 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4588 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004589 GetInnerBlockDeclRefExprs(CBE->getBody(),
4590 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004591 InnerContexts);
4592 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004593 else
4594 GetInnerBlockDeclRefExprs(*CI,
4595 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004596 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004597
4598 }
4599 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004600 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004601 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004602 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004603 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004604 }
4605 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4606 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4607 if (Var->isFunctionOrMethodVarDecl())
4608 ImportedLocalExternalDecls.insert(Var);
4609 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004610
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004611 return;
4612}
4613
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004614/// convertFunctionTypeOfBlocks - This routine converts a function type
4615/// whose result type may be a block pointer or whose argument type(s)
4616/// might be block pointers to an equivalent funtion type replacing
4617/// all block pointers to function pointers.
4618QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4619 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4620 // FTP will be null for closures that don't take arguments.
4621 // Generate a funky cast.
4622 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004623 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004624 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004625
4626 if (FTP) {
4627 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4628 E = FTP->arg_type_end(); I && (I != E); ++I) {
4629 QualType t = *I;
4630 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004631 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004632 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004633 ArgTypes.push_back(t);
4634 }
4635 }
4636 QualType FuncType;
4637 // FIXME. Does this work if block takes no argument but has a return type
4638 // which is of block type?
4639 if (HasBlockType)
4640 FuncType = Context->getFunctionType(Res,
4641 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4642 false, false, 0, 0, FunctionType::ExtInfo());
4643 else FuncType = QualType(FT, 0);
4644 return FuncType;
4645}
4646
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004647Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004648 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004649 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004650
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004651 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004652 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004653 } else if (const BlockDeclRefExpr *CDRE =
4654 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004655 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004656 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004657 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004658 }
4659 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4660 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4661 }
4662 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4663 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4664 else if (const ConditionalOperator *CEXPR =
4665 dyn_cast<ConditionalOperator>(BlockExp)) {
4666 Expr *LHSExp = CEXPR->getLHS();
4667 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4668 Expr *RHSExp = CEXPR->getRHS();
4669 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4670 Expr *CONDExp = CEXPR->getCond();
4671 ConditionalOperator *CondExpr =
4672 new (Context) ConditionalOperator(CONDExp,
4673 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004674 SourceLocation(), cast<Expr>(RHSStmt),
4675 (Expr*)0,
John McCall4bc41ae2010-11-18 19:01:18 +00004676 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004677 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004678 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4679 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680 } else {
4681 assert(1 && "RewriteBlockClass: Bad type");
4682 }
4683 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004684 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004685 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004686 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004687 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004688
Abramo Bagnara6150c882010-05-11 21:36:43 +00004689 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004690 SourceLocation(),
4691 &Context->Idents.get("__block_impl"));
4692 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004693
Steve Naroff350b6652008-10-30 10:07:53 +00004694 // Generate a funky cast.
4695 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004696
Steve Naroff350b6652008-10-30 10:07:53 +00004697 // Push the block argument type.
4698 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004699 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004700 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004701 E = FTP->arg_type_end(); I && (I != E); ++I) {
4702 QualType t = *I;
4703 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004704 if (!convertBlockPointerToFunctionPointer(t))
4705 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004706 ArgTypes.push_back(t);
4707 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004708 }
Steve Naroff350b6652008-10-30 10:07:53 +00004709 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004710 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004711 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4712 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004713 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004714
Steve Naroff350b6652008-10-30 10:07:53 +00004715 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004716
John McCall97513962010-01-15 18:39:57 +00004717 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004718 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004719 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004720 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004721 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4722 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004723 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004724
Douglas Gregor91f84212008-12-11 16:49:14 +00004725 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004726 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004727 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004728 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004729 FD->getType(), VK_LValue,
4730 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004731
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004732
John McCall97513962010-01-15 18:39:57 +00004733 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004734 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004735 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004736
Steve Naroff350b6652008-10-30 10:07:53 +00004737 llvm::SmallVector<Expr*, 8> BlkExprs;
4738 // Add the implicit argument.
4739 BlkExprs.push_back(BlkCast);
4740 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004741 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004742 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004743 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004744 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004745 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4746 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004747 Exp->getType(), VK_RValue,
4748 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004749 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004750}
4751
Steve Naroffd9803712009-04-29 16:37:50 +00004752// We need to return the rewritten expression to handle cases where the
4753// BlockDeclRefExpr is embedded in another expression being rewritten.
4754// For example:
4755//
4756// int main() {
4757// __block Foo *f;
4758// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004759//
Steve Naroffd9803712009-04-29 16:37:50 +00004760// void (^myblock)() = ^() {
4761// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4762// i = 77;
4763// };
4764//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004765Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004766 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004767 // for each DeclRefExp where BYREFVAR is name of the variable.
4768 ValueDecl *VD;
4769 bool isArrow = true;
4770 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4771 VD = BDRE->getDecl();
4772 else {
4773 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4774 isArrow = false;
4775 }
4776
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004777 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4778 &Context->Idents.get("__forwarding"),
4779 Context->VoidPtrTy, 0,
4780 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004781 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4782 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004783 FD->getType(), VK_LValue,
4784 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004785
Daniel Dunbar56df9772010-08-17 22:39:59 +00004786 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004787 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4788 &Context->Idents.get(Name),
4789 Context->VoidPtrTy, 0,
4790 /*BitWidth=*/0, /*Mutable=*/true);
4791 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004792 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004793
4794
4795
Steve Narofff26a1d42009-02-02 17:19:26 +00004796 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004797 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4798 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004799 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004800 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004801}
4802
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004803// Rewrites the imported local variable V with external storage
4804// (static, extern, etc.) as *V
4805//
4806Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4807 ValueDecl *VD = DRE->getDecl();
4808 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4809 if (!ImportedLocalExternalDecls.count(Var))
4810 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004811 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4812 VK_LValue, OK_Ordinary,
4813 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004814 // Need parens to enforce precedence.
4815 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4816 Exp);
4817 ReplaceStmt(DRE, PE);
4818 return PE;
4819}
4820
Steve Naroffc989a7b2008-11-03 23:29:32 +00004821void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4822 SourceLocation LocStart = CE->getLParenLoc();
4823 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004824
4825 // Need to avoid trying to rewrite synthesized casts.
4826 if (LocStart.isInvalid())
4827 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004828 // Need to avoid trying to rewrite casts contained in macros.
4829 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4830 return;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Steve Naroff677ab3a2008-10-27 17:20:55 +00004832 const char *startBuf = SM->getCharacterData(LocStart);
4833 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004834 QualType QT = CE->getType();
4835 const Type* TypePtr = QT->getAs<Type>();
4836 if (isa<TypeOfExprType>(TypePtr)) {
4837 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4838 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4839 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004840 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004841 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004842 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004843 return;
4844 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004845 // advance the location to startArgList.
4846 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004847
Steve Naroff677ab3a2008-10-27 17:20:55 +00004848 while (*argPtr++ && (argPtr < endBuf)) {
4849 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004850 case '^':
4851 // Replace the '^' with '*'.
4852 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004853 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004854 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004855 }
4856 }
4857 return;
4858}
4859
4860void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4861 SourceLocation DeclLoc = FD->getLocation();
4862 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004863
Steve Naroff677ab3a2008-10-27 17:20:55 +00004864 // We have 1 or more arguments that have closure pointers.
4865 const char *startBuf = SM->getCharacterData(DeclLoc);
4866 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004867
Steve Naroff677ab3a2008-10-27 17:20:55 +00004868 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004869
Steve Naroff677ab3a2008-10-27 17:20:55 +00004870 parenCount++;
4871 // advance the location to startArgList.
4872 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4873 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004874
Steve Naroff677ab3a2008-10-27 17:20:55 +00004875 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004876
Steve Naroff677ab3a2008-10-27 17:20:55 +00004877 while (*argPtr++ && parenCount) {
4878 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004879 case '^':
4880 // Replace the '^' with '*'.
4881 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004882 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004883 break;
4884 case '(':
4885 parenCount++;
4886 break;
4887 case ')':
4888 parenCount--;
4889 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004890 }
4891 }
4892 return;
4893}
4894
4895bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004896 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004897 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004898 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004899 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004900 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004901 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004902 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004903 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004904 }
4905 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004906 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004907 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004908 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004909 return true;
4910 }
4911 return false;
4912}
4913
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004914bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4915 const FunctionProtoType *FTP;
4916 const PointerType *PT = QT->getAs<PointerType>();
4917 if (PT) {
4918 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4919 } else {
4920 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4921 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4922 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4923 }
4924 if (FTP) {
4925 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004926 E = FTP->arg_type_end(); I != E; ++I) {
4927 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004928 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004929 if ((*I)->isObjCObjectPointerType() &&
4930 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4931 return true;
4932 }
4933
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004934 }
4935 return false;
4936}
4937
Ted Kremenek5a201952009-02-07 01:47:29 +00004938void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4939 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004940 const char *argPtr = strchr(Name, '(');
4941 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004942
Steve Naroff677ab3a2008-10-27 17:20:55 +00004943 LParen = argPtr; // output the start.
4944 argPtr++; // skip past the left paren.
4945 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004946
Steve Naroff677ab3a2008-10-27 17:20:55 +00004947 while (*argPtr && parenCount) {
4948 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004949 case '(': parenCount++; break;
4950 case ')': parenCount--; break;
4951 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004952 }
4953 if (parenCount) argPtr++;
4954 }
4955 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4956 RParen = argPtr; // output the end
4957}
4958
4959void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4960 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4961 RewriteBlockPointerFunctionArgs(FD);
4962 return;
Mike Stump11289f42009-09-09 15:08:12 +00004963 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004964 // Handle Variables and Typedefs.
4965 SourceLocation DeclLoc = ND->getLocation();
4966 QualType DeclT;
4967 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4968 DeclT = VD->getType();
4969 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4970 DeclT = TDD->getUnderlyingType();
4971 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4972 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004973 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004974 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004975
Steve Naroff677ab3a2008-10-27 17:20:55 +00004976 const char *startBuf = SM->getCharacterData(DeclLoc);
4977 const char *endBuf = startBuf;
4978 // scan backward (from the decl location) for the end of the previous decl.
4979 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4980 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004981 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4982 std::string buf;
4983 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004984 // *startBuf != '^' if we are dealing with a pointer to function that
4985 // may take block argument types (which will be handled below).
4986 if (*startBuf == '^') {
4987 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004988 buf = '*';
4989 startBuf++;
4990 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004991 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004992 while (*startBuf != ')') {
4993 buf += *startBuf;
4994 startBuf++;
4995 OrigLength++;
4996 }
4997 buf += ')';
4998 OrigLength++;
4999
5000 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5001 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005002 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005003 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00005004 DeclLoc = ND->getLocation();
5005 startBuf = SM->getCharacterData(DeclLoc);
5006 const char *argListBegin, *argListEnd;
5007 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5008 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005009 if (*argListBegin == '^')
5010 buf += '*';
5011 else if (*argListBegin == '<') {
5012 buf += "/*";
5013 buf += *argListBegin++;
5014 OrigLength++;;
5015 while (*argListBegin != '>') {
5016 buf += *argListBegin++;
5017 OrigLength++;
5018 }
5019 buf += *argListBegin;
5020 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005021 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005022 else
5023 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005024 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005025 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005026 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005027 buf += ')';
5028 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005029 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005030 ReplaceText(Start, OrigLength, buf);
5031
Steve Naroff677ab3a2008-10-27 17:20:55 +00005032 return;
5033}
5034
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005035
5036/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5037/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5038/// struct Block_byref_id_object *src) {
5039/// _Block_object_assign (&_dest->object, _src->object,
5040/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5041/// [|BLOCK_FIELD_IS_WEAK]) // object
5042/// _Block_object_assign(&_dest->object, _src->object,
5043/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5044/// [|BLOCK_FIELD_IS_WEAK]) // block
5045/// }
5046/// And:
5047/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5048/// _Block_object_dispose(_src->object,
5049/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5050/// [|BLOCK_FIELD_IS_WEAK]) // object
5051/// _Block_object_dispose(_src->object,
5052/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5053/// [|BLOCK_FIELD_IS_WEAK]) // block
5054/// }
5055
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005056std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5057 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005058 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005059 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005060 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005061 CopyDestroyCache.insert(flag);
5062 S = "static void __Block_byref_id_object_copy_";
5063 S += utostr(flag);
5064 S += "(void *dst, void *src) {\n";
5065
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005066 // offset into the object pointer is computed as:
5067 // void * + void* + int + int + void* + void *
5068 unsigned IntSize =
5069 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5070 unsigned VoidPtrSize =
5071 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5072
5073 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5074 S += " _Block_object_assign((char*)dst + ";
5075 S += utostr(offset);
5076 S += ", *(void * *) ((char*)src + ";
5077 S += utostr(offset);
5078 S += "), ";
5079 S += utostr(flag);
5080 S += ");\n}\n";
5081
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005082 S += "static void __Block_byref_id_object_dispose_";
5083 S += utostr(flag);
5084 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005085 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5086 S += utostr(offset);
5087 S += "), ";
5088 S += utostr(flag);
5089 S += ");\n}\n";
5090 return S;
5091}
5092
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005093/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5094/// the declaration into:
5095/// struct __Block_byref_ND {
5096/// void *__isa; // NULL for everything except __weak pointers
5097/// struct __Block_byref_ND *__forwarding;
5098/// int32_t __flags;
5099/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005100/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5101/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005102/// typex ND;
5103/// };
5104///
5105/// It then replaces declaration of ND variable with:
5106/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5107/// __size=sizeof(struct __Block_byref_ND),
5108/// ND=initializer-if-any};
5109///
5110///
5111void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005112 // Insert declaration for the function in which block literal is
5113 // used.
5114 if (CurFunctionDeclToDeclareForBlock)
5115 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005116 int flag = 0;
5117 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005118 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005119 if (DeclLoc.isInvalid())
5120 // If type location is missing, it is because of missing type (a warning).
5121 // Use variable's location which is good for this case.
5122 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005123 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005124 SourceLocation X = ND->getLocEnd();
5125 X = SM->getInstantiationLoc(X);
5126 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005127 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005128 std::string ByrefType;
5129 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005130 ByrefType += " {\n";
5131 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005132 RewriteByRefString(ByrefType, Name, ND);
5133 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005134 ByrefType += " int __flags;\n";
5135 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005136 // Add void *__Block_byref_id_object_copy;
5137 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005138 QualType Ty = ND->getType();
5139 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5140 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005141 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5142 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005143 }
5144
5145 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005146 ByrefType += " " + Name + ";\n";
5147 ByrefType += "};\n";
5148 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005149 SourceLocation FunLocStart;
5150 if (CurFunctionDef)
5151 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5152 else {
5153 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5154 FunLocStart = CurMethodDef->getLocStart();
5155 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005156 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005157 if (Ty.isObjCGCWeak()) {
5158 flag |= BLOCK_FIELD_IS_WEAK;
5159 isa = 1;
5160 }
5161
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005162 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005163 flag = BLOCK_BYREF_CALLER;
5164 QualType Ty = ND->getType();
5165 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5166 if (Ty->isBlockPointerType())
5167 flag |= BLOCK_FIELD_IS_BLOCK;
5168 else
5169 flag |= BLOCK_FIELD_IS_OBJECT;
5170 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005171 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005172 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005173 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005174
5175 // struct __Block_byref_ND ND =
5176 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5177 // initializer-if-any};
5178 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005179 unsigned flags = 0;
5180 if (HasCopyAndDispose)
5181 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005182 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005183 ByrefType.clear();
5184 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005185 std::string ForwardingCastType("(");
5186 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005187 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005188 ByrefType += " " + Name + " = {(void*)";
5189 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005190 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005191 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005192 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005193 ByrefType += "sizeof(";
5194 RewriteByRefString(ByrefType, Name, ND);
5195 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005196 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005197 ByrefType += ", __Block_byref_id_object_copy_";
5198 ByrefType += utostr(flag);
5199 ByrefType += ", __Block_byref_id_object_dispose_";
5200 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005201 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005202 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005203 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005204 }
5205 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005206 SourceLocation startLoc;
5207 Expr *E = ND->getInit();
5208 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5209 startLoc = ECE->getLParenLoc();
5210 else
5211 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005212 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005213 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005214 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005215 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005216 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005217 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005218 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005219 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005220 ByrefType += "sizeof(";
5221 RewriteByRefString(ByrefType, Name, ND);
5222 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005223 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005224 ByrefType += "__Block_byref_id_object_copy_";
5225 ByrefType += utostr(flag);
5226 ByrefType += ", __Block_byref_id_object_dispose_";
5227 ByrefType += utostr(flag);
5228 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005229 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005230 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005231
5232 // Complete the newly synthesized compound expression by inserting a right
5233 // curly brace before the end of the declaration.
5234 // FIXME: This approach avoids rewriting the initializer expression. It
5235 // also assumes there is only one declarator. For example, the following
5236 // isn't currently supported by this routine (in general):
5237 //
5238 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5239 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005240 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5241 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005242 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5243 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005244 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005245
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005246 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005247 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005248 return;
5249}
5250
Mike Stump11289f42009-09-09 15:08:12 +00005251void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005252 // Add initializers for any closure decl refs.
5253 GetBlockDeclRefExprs(Exp->getBody());
5254 if (BlockDeclRefs.size()) {
5255 // Unique all "by copy" declarations.
5256 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005257 if (!BlockDeclRefs[i]->isByRef()) {
5258 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5259 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5260 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5261 }
5262 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005263 // Unique all "by ref" declarations.
5264 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5265 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005266 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5267 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5268 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5269 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005270 }
5271 // Find any imported blocks...they will need special attention.
5272 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005273 if (BlockDeclRefs[i]->isByRef() ||
5274 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005275 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005276 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005277 }
5278}
5279
Daniel Dunbar56df9772010-08-17 22:39:59 +00005280FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005281 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005282 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005283 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005284 ID, FType, 0, SC_Extern,
5285 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005286}
5287
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005288Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5289 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005290 Blocks.push_back(Exp);
5291
5292 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005293
5294 // Add inner imported variables now used in current block.
5295 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005296 if (!InnerBlockDeclRefs.empty()) {
5297 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5298 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5299 ValueDecl *VD = Exp->getDecl();
5300 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005301 // We need to save the copied-in variables in nested
5302 // blocks because it is needed at the end for some of the API generations.
5303 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005304 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5305 BlockDeclRefs.push_back(Exp);
5306 BlockByCopyDeclsPtrSet.insert(VD);
5307 BlockByCopyDecls.push_back(VD);
5308 }
5309 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5310 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5311 BlockDeclRefs.push_back(Exp);
5312 BlockByRefDeclsPtrSet.insert(VD);
5313 BlockByRefDecls.push_back(VD);
5314 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005315 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005316 // Find any imported blocks...they will need special attention.
5317 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5318 if (InnerBlockDeclRefs[i]->isByRef() ||
5319 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5320 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5321 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005322 }
5323 InnerDeclRefsCount.push_back(countOfInnerDecls);
5324
Steve Narofff4b992a2008-10-28 20:29:00 +00005325 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005326
Steve Narofff4b992a2008-10-28 20:29:00 +00005327 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005328 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005329 else if (CurMethodDef)
5330 BuildUniqueMethodName(FuncName, CurMethodDef);
5331 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005332 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005333
Steve Narofff4b992a2008-10-28 20:29:00 +00005334 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005335
Steve Narofff4b992a2008-10-28 20:29:00 +00005336 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5337 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005338
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005340 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5341 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005342
5343 FunctionDecl *FD;
5344 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005345
Steve Narofff4b992a2008-10-28 20:29:00 +00005346 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005347 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005348 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5349 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005350
Steve Narofff4b992a2008-10-28 20:29:00 +00005351 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005352
Steve Naroffe2514232008-10-29 21:23:59 +00005353 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005354 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005355 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005356 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005357 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005358 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005359 InitExprs.push_back(castExpr);
5360
Steve Naroff30484702009-12-06 21:14:13 +00005361 // Initialize the block descriptor.
5362 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005363
Steve Naroff30484702009-12-06 21:14:13 +00005364 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5365 &Context->Idents.get(DescData.c_str()),
5366 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005367 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005368 UnaryOperator *DescRefExpr =
5369 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5370 Context->VoidPtrTy,
5371 VK_LValue,
5372 SourceLocation()),
5373 UO_AddrOf,
5374 Context->getPointerType(Context->VoidPtrTy),
5375 VK_RValue, OK_Ordinary,
5376 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005377 InitExprs.push_back(DescRefExpr);
5378
Steve Narofff4b992a2008-10-28 20:29:00 +00005379 // Add initializers for any closure decl refs.
5380 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005381 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005382 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005383 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005384 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005385 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005386 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005387 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005388 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5389 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005390 if (HasLocalVariableExternalStorage(*I)) {
5391 QualType QT = (*I)->getType();
5392 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005393 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5394 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005395 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005396 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005397 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005398 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5399 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005400 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005401 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005402 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005403 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005404 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5405 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005406 if (HasLocalVariableExternalStorage(*I)) {
5407 QualType QT = (*I)->getType();
5408 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005409 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5410 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005411 }
5412
Steve Narofff4b992a2008-10-28 20:29:00 +00005413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005415 }
5416 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005417 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005418 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005419 ValueDecl *ND = (*I);
5420 std::string Name(ND->getNameAsString());
5421 std::string RecName;
5422 RewriteByRefString(RecName, Name, ND);
5423 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5424 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005425 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005426 SourceLocation(), II);
5427 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5428 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5429
Daniel Dunbar56df9772010-08-17 22:39:59 +00005430 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005431 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5432 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005433 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005434 Context->getPointerType(Exp->getType()),
5435 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005436 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005437 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005438 }
5439 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005440 if (ImportedBlockDecls.size()) {
5441 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5442 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005443 unsigned IntSize =
5444 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005445 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5446 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005447 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005448 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005449 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005450 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005451 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005452 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005453 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005454 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005455 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005456 BlockDeclRefs.clear();
5457 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005458 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005460 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005461 ImportedBlockDecls.clear();
5462 return NewRep;
5463}
5464
5465//===----------------------------------------------------------------------===//
5466// Function Body / Expression rewriting
5467//===----------------------------------------------------------------------===//
5468
Steve Naroff4588d0f2008-12-04 16:24:46 +00005469// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5470// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5471// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5472// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5473// Since the rewriter isn't capable of rewriting rewritten code, it's important
5474// we get this right.
5475void RewriteObjC::CollectPropertySetters(Stmt *S) {
5476 // Perform a bottom up traversal of all children.
5477 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5478 CI != E; ++CI)
5479 if (*CI)
5480 CollectPropertySetters(*CI);
5481
5482 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5483 if (BinOp->isAssignmentOp()) {
John McCallb7bd14f2010-12-02 01:19:52 +00005484 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5485 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005486 }
5487 }
5488}
5489
Steve Narofff4b992a2008-10-28 20:29:00 +00005490Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005491 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005492 isa<DoStmt>(S) || isa<ForStmt>(S))
5493 Stmts.push_back(S);
5494 else if (isa<ObjCForCollectionStmt>(S)) {
5495 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005496 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005497 }
Mike Stump11289f42009-09-09 15:08:12 +00005498
Steve Narofff4b992a2008-10-28 20:29:00 +00005499 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005500
Steve Narofff4b992a2008-10-28 20:29:00 +00005501 // Perform a bottom up rewrite of all children.
5502 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5503 CI != E; ++CI)
5504 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005505 Stmt *newStmt;
5506 Stmt *S = (*CI);
5507 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5508 Expr *OldBase = IvarRefExpr->getBase();
5509 bool replaced = false;
5510 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5511 if (replaced) {
5512 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5513 ReplaceStmt(OldBase, IRE->getBase());
5514 else
5515 ReplaceStmt(S, newStmt);
5516 }
5517 }
5518 else
5519 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005520 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005521 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005522 // If dealing with an assignment with LHS being a property reference
5523 // expression, the entire assignment tree is rewritten into a property
5524 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5525 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005526 if (Expr *Exp = dyn_cast<Expr>(S))
John McCallb7bd14f2010-12-02 01:19:52 +00005527 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005528 if (PropSetters[Exp]) {
5529 ++CI;
5530 continue;
5531 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005532 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005533 }
Mike Stump11289f42009-09-09 15:08:12 +00005534
Steve Narofff4b992a2008-10-28 20:29:00 +00005535 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005536 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005537 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5538 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005539 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005540 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005541 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005542 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005543 Stmt *SaveCurrentBody = CurrentBody;
5544 CurrentBody = BE->getBody();
5545 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005546 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005547 CurrentBody = SaveCurrentBody;
5548 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005549 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005550 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005551 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005552 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005553
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005554 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5555
Steve Narofff4b992a2008-10-28 20:29:00 +00005556 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005557 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005558 return blockTranscribed;
5559 }
5560 // Handle specific things.
5561 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5562 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005563
John McCallb7bd14f2010-12-02 01:19:52 +00005564 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005565 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5566 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5567
5568 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005569 if (BinOp) {
5570 // Because the rewriter doesn't allow us to rewrite rewritten code,
5571 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005572 DisableReplaceStmt = true;
5573 // Save the source range. Even if we disable the replacement, the
5574 // rewritten node will have been inserted into the tree. If the synthesized
5575 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005576 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005577 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5578 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005579 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005580 // Need to rewrite the ivar access expression if need be.
5581 if (isa<ObjCIvarRefExpr>(newStmt)) {
5582 bool replaced = false;
5583 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5584 }
5585
Steve Naroff08628db2008-12-09 12:56:34 +00005586 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005587 //
5588 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5589 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5590 // to see the original expression). Consider this example:
5591 //
5592 // Foo *obj1, *obj2;
5593 //
5594 // obj1.i = [obj2 rrrr];
5595 //
5596 // 'BinOp' for the previous expression looks like:
5597 //
5598 // (BinaryOperator 0x231ccf0 'int' '='
5599 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5600 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5601 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5602 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5603 //
5604 // 'newStmt' represents the rewritten message expression. For example:
5605 //
5606 // (CallExpr 0x231d300 'id':'struct objc_object *'
5607 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5608 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5609 // (CStyleCastExpr 0x231d220 'void *'
5610 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5611 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005612 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005613 // can be used as the setter argument. ReplaceStmt() will still 'see'
5614 // the original RHS (since we haven't altered BinOp).
5615 //
Mike Stump11289f42009-09-09 15:08:12 +00005616 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005617 // node. As a result, we now leak the original AST nodes.
5618 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005619 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005620 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005621 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005622 }
5623 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005624
Steve Narofff4b992a2008-10-28 20:29:00 +00005625 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5626 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005627
Steve Narofff4b992a2008-10-28 20:29:00 +00005628 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5629 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005630
Steve Narofff4b992a2008-10-28 20:29:00 +00005631 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005632#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005633 // Before we rewrite it, put the original message expression in a comment.
5634 SourceLocation startLoc = MessExpr->getLocStart();
5635 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005636
Steve Narofff4b992a2008-10-28 20:29:00 +00005637 const char *startBuf = SM->getCharacterData(startLoc);
5638 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005639
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 std::string messString;
5641 messString += "// ";
5642 messString.append(startBuf, endBuf-startBuf+1);
5643 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005644
5645 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005646 // InsertText(clang::SourceLocation, char const*, unsigned int).
5647 // InsertText(startLoc, messString.c_str(), messString.size());
5648 // Tried this, but it didn't work either...
5649 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005650#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005651 return RewriteMessageExpr(MessExpr);
5652 }
Mike Stump11289f42009-09-09 15:08:12 +00005653
Steve Narofff4b992a2008-10-28 20:29:00 +00005654 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5655 return RewriteObjCTryStmt(StmtTry);
5656
5657 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5658 return RewriteObjCSynchronizedStmt(StmtTry);
5659
5660 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5661 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005662
Steve Narofff4b992a2008-10-28 20:29:00 +00005663 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5664 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005665
5666 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005667 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005668 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005669 OrigStmtRange.getEnd());
5670 if (BreakStmt *StmtBreakStmt =
5671 dyn_cast<BreakStmt>(S))
5672 return RewriteBreakStmt(StmtBreakStmt);
5673 if (ContinueStmt *StmtContinueStmt =
5674 dyn_cast<ContinueStmt>(S))
5675 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005676
5677 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005678 // and cast exprs.
5679 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5680 // FIXME: What we're doing here is modifying the type-specifier that
5681 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005682 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005683 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5684 // the context of an ObjCForCollectionStmt. For example:
5685 // NSArray *someArray;
5686 // for (id <FooProtocol> index in someArray) ;
5687 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5688 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005689 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005690 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005691
Steve Narofff4b992a2008-10-28 20:29:00 +00005692 // Blocks rewrite rules.
5693 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5694 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005695 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005696 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005697 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005698 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005699 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005700 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005701 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005702 if (VD->hasAttr<BlocksAttr>()) {
5703 static unsigned uniqueByrefDeclCount = 0;
5704 assert(!BlockByRefDeclNo.count(ND) &&
5705 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5706 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005707 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005708 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005709 else
5710 RewriteTypeOfDecl(VD);
5711 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005712 }
5713 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005714 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005715 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005716 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005717 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5718 }
5719 }
5720 }
Mike Stump11289f42009-09-09 15:08:12 +00005721
Steve Narofff4b992a2008-10-28 20:29:00 +00005722 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5723 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005724
5725 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005726 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5727 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005728 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5729 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005730 && "Statement stack mismatch");
5731 Stmts.pop_back();
5732 }
5733 // Handle blocks rewriting.
5734 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5735 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005736 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005737 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5739 ValueDecl *VD = DRE->getDecl();
5740 if (VD->hasAttr<BlocksAttr>())
5741 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005742 if (HasLocalVariableExternalStorage(VD))
5743 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005744 }
5745
Steve Narofff4b992a2008-10-28 20:29:00 +00005746 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005747 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005748 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005749 ReplaceStmt(S, BlockCall);
5750 return BlockCall;
5751 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005752 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005753 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005754 RewriteCastExpr(CE);
5755 }
5756#if 0
5757 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005758 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5759 ICE->getSubExpr(),
5760 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005761 // Get the new text.
5762 std::string SStr;
5763 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005764 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005765 const std::string &Str = Buf.str();
5766
5767 printf("CAST = %s\n", &Str[0]);
5768 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5769 delete S;
5770 return Replacement;
5771 }
5772#endif
5773 // Return this stmt unmodified.
5774 return S;
5775}
5776
Steve Naroffe70a52a2009-12-05 15:55:59 +00005777void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5778 for (RecordDecl::field_iterator i = RD->field_begin(),
5779 e = RD->field_end(); i != e; ++i) {
5780 FieldDecl *FD = *i;
5781 if (isTopLevelBlockPointerType(FD->getType()))
5782 RewriteBlockPointerDecl(FD);
5783 if (FD->getType()->isObjCQualifiedIdType() ||
5784 FD->getType()->isObjCQualifiedInterfaceType())
5785 RewriteObjCQualifiedInterfaceTypes(FD);
5786 }
5787}
5788
Steve Narofff4b992a2008-10-28 20:29:00 +00005789/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5790/// main file of the input.
5791void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005793 if (FD->isOverloadedOperator())
5794 return;
Mike Stump11289f42009-09-09 15:08:12 +00005795
Steve Narofff4b992a2008-10-28 20:29:00 +00005796 // Since function prototypes don't have ParmDecl's, we check the function
5797 // prototype. This enables us to rewrite function declarations and
5798 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005799 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005800
Sebastian Redla7b98a72009-04-26 20:35:05 +00005801 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005802 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005803 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005804 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005805 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005806 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005807 Body =
5808 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5809 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005810 CurrentBody = 0;
5811 if (PropParentMap) {
5812 delete PropParentMap;
5813 PropParentMap = 0;
5814 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005815 // This synthesizes and inserts the block "impl" struct, invoke function,
5816 // and any copy/dispose helper functions.
5817 InsertBlockLiteralsWithinFunction(FD);
5818 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005819 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005820 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005821 return;
5822 }
5823 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005824 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005825 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005826 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005827 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005828 Body =
5829 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5830 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005831 CurrentBody = 0;
5832 if (PropParentMap) {
5833 delete PropParentMap;
5834 PropParentMap = 0;
5835 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005836 InsertBlockLiteralsWithinMethod(MD);
5837 CurMethodDef = 0;
5838 }
5839 }
5840 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5841 ClassImplementation.push_back(CI);
5842 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5843 CategoryImplementation.push_back(CI);
5844 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5845 RewriteForwardClassDecl(CD);
5846 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5847 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005848 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005849 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005850 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005851 CheckFunctionPointerDecl(VD->getType(), VD);
5852 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005853 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005854 RewriteCastExpr(CE);
5855 }
5856 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005857 } else if (VD->getType()->isRecordType()) {
5858 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5859 if (RD->isDefinition())
5860 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005861 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005862 if (VD->getInit()) {
5863 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005864 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005865 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005866 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005867 CurrentBody = 0;
5868 if (PropParentMap) {
5869 delete PropParentMap;
5870 PropParentMap = 0;
5871 }
Mike Stump11289f42009-09-09 15:08:12 +00005872 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005873 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005874 GlobalVarDecl = 0;
5875
5876 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005877 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005878 RewriteCastExpr(CE);
5879 }
5880 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005881 return;
5882 }
5883 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005884 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005885 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005886 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005887 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5888 return;
5889 }
5890 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005891 if (RD->isDefinition())
5892 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005893 return;
5894 }
5895 // Nothing yet.
5896}
5897
Chris Lattnercf169832009-03-28 04:11:33 +00005898void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005899 if (Diags.hasErrorOccurred())
5900 return;
Mike Stump11289f42009-09-09 15:08:12 +00005901
Steve Narofff4b992a2008-10-28 20:29:00 +00005902 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005903
Steve Naroffd9803712009-04-29 16:37:50 +00005904 // Here's a great place to add any extra declarations that may be needed.
5905 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005906 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005907 E = ProtocolExprDecls.end(); I != E; ++I)
5908 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5909
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005910 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005911 if (ClassImplementation.size() || CategoryImplementation.size())
5912 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005913
Steve Narofff4b992a2008-10-28 20:29:00 +00005914 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5915 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005916 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005917 Rewrite.getRewriteBufferFor(MainFileID)) {
5918 //printf("Changed:\n");
5919 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5920 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005921 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005922 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005923
Steve Naroffd9803712009-04-29 16:37:50 +00005924 if (ClassImplementation.size() || CategoryImplementation.size() ||
5925 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005926 // Rewrite Objective-c meta data*
5927 std::string ResultStr;
5928 SynthesizeMetaDataIntoBuffer(ResultStr);
5929 // Emit metadata.
5930 *OutFile << ResultStr;
5931 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005932 OutFile->flush();
5933}