blob: 78e370b97743991b03ba8242b461ce6a865849dc [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,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000255 ValueDecl *VD, bool def=false);
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);
Fariborz Jahanian74405b02011-02-24 21:29:21 +0000301 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump11289f42009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000303 Expr **args, unsigned nargs,
304 SourceLocation StartLoc=SourceLocation(),
305 SourceLocation EndLoc=SourceLocation());
306 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
307 SourceLocation StartLoc=SourceLocation(),
308 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000311 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000313 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000314 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000315 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000316 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000317 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000318 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000319 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000320 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner3c799d72007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000327
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000335 llvm::StringRef prefix,
336 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +0000337 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Steve Naroffd9803712009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000340 llvm::StringRef prefix,
341 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000344 llvm::StringRef prefix,
345 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000346 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000348 std::string &Result);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000349 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000350 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000351 void RewriteImplementations();
352 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Steve Naroff677ab3a2008-10-27 17:20:55 +0000354 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000355 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
359 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000360
361 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000362 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000363 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000365 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000366 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000367 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000368
369 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000370 llvm::StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000371 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000372 llvm::StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000373 std::string SynthesizeBlockImpl(BlockExpr *CE,
374 std::string Tag, std::string Desc);
375 std::string SynthesizeBlockDescriptor(std::string DescTag,
376 std::string ImplTag,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000377 int i, llvm::StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000378 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000379 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000380 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000381 llvm::StringRef FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000382 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000386 void GetInnerBlockDeclRefExprs(Stmt *S,
387 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000388 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 // We avoid calling Type::isBlockPointerType(), since it operates on the
391 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000392 bool isTopLevelBlockPointerType(QualType T) {
393 return isa<BlockPointerType>(T);
394 }
Mike Stump11289f42009-09-09 15:08:12 +0000395
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000396 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
397 /// to a function pointer type and upon success, returns true; false
398 /// otherwise.
399 bool convertBlockPointerToFunctionPointer(QualType &T) {
400 if (isTopLevelBlockPointerType(T)) {
401 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
402 T = Context->getPointerType(BPT->getPointeeType());
403 return true;
404 }
405 return false;
406 }
407
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000408 void convertToUnqualifiedObjCType(QualType &T) {
409 if (T->isObjCQualifiedIdType())
410 T = Context->getObjCIdType();
411 else if (T->isObjCQualifiedClassType())
412 T = Context->getObjCClassType();
413 else if (T->isObjCObjectPointerType() &&
414 T->getPointeeType()->isObjCQualifiedInterfaceType())
415 T = Context->getObjCIdType();
416 }
417
Steve Naroff677ab3a2008-10-27 17:20:55 +0000418 // FIXME: This predicate seems like it would be useful to add to ASTContext.
419 bool isObjCType(QualType T) {
420 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
421 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Steve Naroff677ab3a2008-10-27 17:20:55 +0000423 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000424
Steve Naroff677ab3a2008-10-27 17:20:55 +0000425 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
426 OCT == Context->getCanonicalType(Context->getObjCClassType()))
427 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000429 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000431 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000432 return true;
433 }
434 return false;
435 }
436 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000437 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000438 void GetExtentOfArgList(const char *Name, const char *&LParen,
439 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000440 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Daniel Dunbar56df9772010-08-17 22:39:59 +0000442 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
444 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Steve Naroffd9803712009-04-29 16:37:50 +0000446 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000447 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000448 if (From[i] == '"')
449 To += "\\\"";
450 else
451 To += From[i];
452 }
453 }
John McCalldb40c7f2010-12-14 08:05:40 +0000454
455 QualType getSimpleFunctionType(QualType result,
456 const QualType *args,
457 unsigned numArgs,
458 bool variadic = false) {
459 FunctionProtoType::ExtProtoInfo fpi;
460 fpi.Variadic = variadic;
461 return Context->getFunctionType(result, args, numArgs, fpi);
462 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000463 };
John McCall97513962010-01-15 18:39:57 +0000464
465 // Helper function: create a CStyleCastExpr with trivial type source info.
466 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000467 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000468 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +0000469 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallcf142162010-08-07 06:22:56 +0000470 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000471 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000472}
473
Mike Stump11289f42009-09-09 15:08:12 +0000474void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
475 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000476 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000477 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000479 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000480 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000481 // All the args are checked/rewritten. Don't call twice!
482 RewriteBlockPointerDecl(D);
483 break;
484 }
485 }
486}
487
488void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000490 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000491 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000492}
493
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000494static bool IsHeaderFile(const std::string &Filename) {
495 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000496
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000497 if (DotPos == std::string::npos) {
498 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000499 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000502 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
503 // C header: .h
504 // C++ header: .hh or .H;
505 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000506}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000507
Eli Friedman94cf21e2009-05-18 22:20:00 +0000508RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000509 Diagnostic &D, const LangOptions &LOpts,
510 bool silenceMacroWarn)
511 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
512 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000513 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000514 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000515 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000516 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000517 "rewriter doesn't support user-specified control flow semantics "
518 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000519}
520
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000521ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
522 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000523 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000524 const LangOptions &LOpts,
525 bool SilenceRewriteMacroWarning) {
526 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000527}
Chris Lattnere99c8322007-10-11 00:43:27 +0000528
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000529void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000530 Context = &context;
531 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000532 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000533 MsgSendFunctionDecl = 0;
534 MsgSendSuperFunctionDecl = 0;
535 MsgSendStretFunctionDecl = 0;
536 MsgSendSuperStretFunctionDecl = 0;
537 MsgSendFpretFunctionDecl = 0;
538 GetClassFunctionDecl = 0;
539 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000540 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000541 SelGetUidFunctionDecl = 0;
542 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000543 ConstantStringClassReference = 0;
544 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000545 CurMethodDef = 0;
546 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000547 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000548 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000549 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000550 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000551 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000552 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000553 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000554 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000555 PropParentMap = 0;
556 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000557 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000558 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner187f6262008-01-31 19:38:44 +0000560 // Get the ID and start/end of the main file.
561 MainFileID = SM->getMainFileID();
562 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
563 MainFileStart = MainBuf->getBufferStart();
564 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner184e65d2009-04-14 23:22:57 +0000566 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattner187f6262008-01-31 19:38:44 +0000568 // declaring objc_selector outside the parameter list removes a silly
569 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000570 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000571 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000573 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000575 if (LangOpts.Microsoft) {
576 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000577 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
578 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000580 }
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
583 Preamble += "typedef struct objc_object Protocol;\n";
584 Preamble += "#define _REWRITER_typedef_Protocol\n";
585 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000586 if (LangOpts.Microsoft) {
587 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
588 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
589 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000590 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000592 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000594 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000596 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000598 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000600 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000602 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000603 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
604 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000606 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
611 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000612 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000613 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
616 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000617 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
618 Preamble += "struct __objcFastEnumerationState {\n\t";
619 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000620 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000621 Preamble += "unsigned long *mutationsPtr;\n\t";
622 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000624 Preamble += "#define __FASTENUMERATIONSTATE\n";
625 Preamble += "#endif\n";
626 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
627 Preamble += "struct __NSConstantStringImpl {\n";
628 Preamble += " int *isa;\n";
629 Preamble += " int flags;\n";
630 Preamble += " char *str;\n";
631 Preamble += " long length;\n";
632 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000633 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
634 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
635 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000636 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000637 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000638 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
639 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000640 // Blocks preamble.
641 Preamble += "#ifndef BLOCK_IMPL\n";
642 Preamble += "#define BLOCK_IMPL\n";
643 Preamble += "struct __block_impl {\n";
644 Preamble += " void *isa;\n";
645 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000646 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000647 Preamble += " void *FuncPtr;\n";
648 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000649 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000650 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000651 Preamble += "extern \"C\" __declspec(dllexport) "
652 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000653 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
655 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
656 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
658 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
660 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
661 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000662 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000663 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000664 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
665 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000666 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000667 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000668 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000669 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000670 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000671 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000672 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000673 Preamble += "#define __weak\n";
674 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000675 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
676 // as this avoids warning in any 64bit/32bit compilation model.
677 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000678}
679
680
Chris Lattner3c799d72007-10-24 17:06:59 +0000681//===----------------------------------------------------------------------===//
682// Top Level Driver Code
683//===----------------------------------------------------------------------===//
684
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000685void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000686 if (Diags.hasErrorOccurred())
687 return;
688
Chris Lattner0bd1c972007-10-16 21:07:07 +0000689 // Two cases: either the decl could be in the main file, or it could be in a
690 // #included file. If the former, rewrite it now. If the later, check to see
691 // if we rewrote the #include/#import.
692 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000693 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner0bd1c972007-10-16 21:07:07 +0000695 // If this is for a builtin, ignore it.
696 if (Loc.isInvalid()) return;
697
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000698 // Look for built-in declarations that we need to refer during the rewrite.
699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000700 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000701 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000702 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000703 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000704 ConstantStringClassReference = FVD;
705 return;
706 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000707 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000708 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000709 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000710 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000711 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000712 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000713 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000714 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000715 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000716 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
717 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000718 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
719 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000720 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000721 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000722 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000726}
727
Chris Lattner3c799d72007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000734 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000738
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000750 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffc038b3a2008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
780 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000784
Steve Naroff9af94912008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000788
Steve Naroff003d00e2008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000802 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
824 Context->PrintingPolicy);
825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
838 SynthesizeIvarOffsetComputation(OID, Getr);
839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000845 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000848 return;
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Naroff9af94912008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000868 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000871 Setr += ", ";
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
873 Setr += "0, ";
874 else
875 Setr += "1, ";
876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000884 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000887}
Chris Lattner16a0de42007-10-11 18:38:32 +0000888
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000889void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = ClassDecl->getLocation();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattner3c799d72007-10-24 17:06:59 +0000895 // Translate to typedef's that forward reference structs with the same name
896 // as the class. As a convenience, we include the original declaration
897 // as a comment.
898 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000899 typedefString += "// @class ";
900 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
901 I != E; ++I) {
902 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
903 typedefString += ForwardDecl->getNameAsString();
904 if (I+1 != E)
905 typedefString += ", ";
906 else
907 typedefString += ";\n";
908 }
909
Chris Lattner9ee23b72009-02-20 18:04:31 +0000910 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
911 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000912 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000913 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000914 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000915 typedefString += "\n";
916 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000917 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000918 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000919 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000920 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000921 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Steve Naroff574440f2007-10-24 22:48:43 +0000924 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000925 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000926}
927
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000928void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000929 // When method is a synthesized one, such as a getter/setter there is
930 // nothing to rewrite.
931 if (Method->isSynthesized())
932 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000933 SourceLocation LocStart = Method->getLocStart();
934 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner88ea93e2009-02-04 01:06:56 +0000936 if (SM->getInstantiationLineNumber(LocEnd) >
937 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000938 InsertText(LocStart, "#if 0\n");
939 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000940 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000941 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000942 }
943}
944
Mike Stump11289f42009-09-09 15:08:12 +0000945void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000946 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000947
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000948 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000949 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000950}
951
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000952void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000953 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000954
Steve Naroff5448cf62007-10-30 13:30:57 +0000955 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000956 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000957
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000958 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
959 E = CatDecl->prop_end(); I != E; ++I)
960 RewriteProperty(*I);
961
Mike Stump11289f42009-09-09 15:08:12 +0000962 for (ObjCCategoryDecl::instmeth_iterator
963 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000964 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000965 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000966 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000967 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000968 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000969 RewriteMethodDeclaration(*I);
970
Steve Naroff5448cf62007-10-30 13:30:57 +0000971 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000972 ReplaceText(CatDecl->getAtEndRange().getBegin(),
973 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000974}
975
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000976void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000977 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Steve Narofff921385f2007-10-30 16:42:30 +0000979 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000980 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000981
982 for (ObjCProtocolDecl::instmeth_iterator
983 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000984 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000985 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000986 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000987 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000988 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000989 RewriteMethodDeclaration(*I);
990
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000991 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
992 E = PDecl->prop_end(); I != E; ++I)
993 RewriteProperty(*I);
994
Steve Narofff921385f2007-10-30 16:42:30 +0000995 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000996 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000997 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000998
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000999 // Must comment out @optional/@required
1000 const char *startBuf = SM->getCharacterData(LocStart);
1001 const char *endBuf = SM->getCharacterData(LocEnd);
1002 for (const char *p = startBuf; p < endBuf; p++) {
1003 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001004 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001005 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001006
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001007 }
1008 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001009 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001010 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001011
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001012 }
1013 }
Steve Narofff921385f2007-10-30 16:42:30 +00001014}
1015
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001016void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001017 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001018 if (LocStart.isInvalid())
1019 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001020 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001021 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001022}
1023
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001024void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1025 const FunctionType *&FPRetType) {
1026 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001027 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001028 else if (T->isFunctionPointerType() ||
1029 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001030 // needs special handling, since pointer-to-functions have special
1031 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001032 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001033 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001035 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001036 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001037 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001038 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001039 ResultStr += FPRetType->getResultType().getAsString(
1040 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001041 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001042 }
1043 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001044 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001045}
1046
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001047void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1048 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001049 std::string &ResultStr) {
1050 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1051 const FunctionType *FPRetType = 0;
1052 ResultStr += "\nstatic ";
1053 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001054 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001055
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001056 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001057 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Douglas Gregorffca3a22009-01-09 17:18:27 +00001059 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001060 NameStr += "_I_";
1061 else
1062 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001063
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001064 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001065 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001066
1067 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001068 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001069 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001073 {
1074 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001075 int len = selString.size();
1076 for (int i = 0; i < len; i++)
1077 if (selString[i] == ':')
1078 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001079 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001081 // Remember this name for metadata emission
1082 MethodInternalNames[OMD] = NameStr;
1083 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085 // Rewrite arguments
1086 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001087
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001089 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001090 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001092 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001093 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001094 ResultStr += "struct ";
1095 }
1096 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001097 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001098 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001099 }
1100 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001101 ResultStr += Context->getObjCClassType().getAsString(
1102 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001103
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001104 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001105 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001106 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001108 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001109 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1110 E = OMD->param_end(); PI != E; ++PI) {
1111 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001113 if (PDecl->getType()->isObjCQualifiedIdType()) {
1114 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001115 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001116 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001117 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001118 QualType QT = PDecl->getType();
1119 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1120 if (convertBlockPointerToFunctionPointer(QT))
1121 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1122 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001123 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001124 ResultStr += Name;
1125 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001126 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001127 if (OMD->isVariadic())
1128 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001129 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001130
Steve Naroffb067bbd2008-07-16 14:40:40 +00001131 if (FPRetType) {
1132 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001133
Steve Naroffb067bbd2008-07-16 14:40:40 +00001134 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001135 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001136 ResultStr += "(";
1137 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1138 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001139 std::string ParamStr = FT->getArgType(i).getAsString(
1140 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001141 ResultStr += ParamStr;
1142 }
1143 if (FT->isVariadic()) {
1144 if (FT->getNumArgs()) ResultStr += ", ";
1145 ResultStr += "...";
1146 }
1147 ResultStr += ")";
1148 } else {
1149 ResultStr += "()";
1150 }
1151 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001152}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001153void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001154 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1155 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001156
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001157 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001158
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001159 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001160 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1161 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001162 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001163 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001164 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001165 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001166 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001167 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001168
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001169 const char *startBuf = SM->getCharacterData(LocStart);
1170 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001171 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001174 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001175 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1176 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001177 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001178 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001179 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001180 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001181 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001182 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001184 const char *startBuf = SM->getCharacterData(LocStart);
1185 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001186 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001187 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001188 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001189 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001190 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001191 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001192 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001193 }
1194
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001195 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001196}
1197
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001198void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001199 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001200 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001201 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001202 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001204 ResultStr += "\n";
1205 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001207 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001208 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001210 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001211 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001212 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001213 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001214 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001215
1216 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001217 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001218 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001219 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001220 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001221 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001222 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001223 for (ObjCInterfaceDecl::classmeth_iterator
1224 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001225 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001226 RewriteMethodDeclaration(*I);
1227
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001228 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001229 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001231}
1232
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001233Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001234 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001235 ObjCMethodDecl *OMD = 0;
1236 QualType Ty;
1237 Selector Sel;
Duncan Sands3a02f3e2010-10-20 08:21:16 +00001238 Stmt *Receiver = 0;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001239 bool Super = false;
1240 QualType SuperTy;
1241 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001242 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001243 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001244 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCallb7bd14f2010-12-02 01:19:52 +00001245 if (ObjCPropertyRefExpr *PropRefExpr =
1246 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001247 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001248 if (PropRefExpr->isExplicitProperty()) {
1249 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1250 OMD = PDecl->getSetterMethodDecl();
1251 Ty = PDecl->getType();
1252 Sel = PDecl->getSetterName();
1253 } else {
1254 OMD = PropRefExpr->getImplicitPropertySetter();
1255 Sel = OMD->getSelector();
1256 Ty = PropRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001257 }
John McCallb7bd14f2010-12-02 01:19:52 +00001258 Super = PropRefExpr->isSuperReceiver();
1259 if (!Super) {
1260 Receiver = PropRefExpr->getBase();
1261 } else {
1262 SuperTy = PropRefExpr->getSuperReceiverType();
1263 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001264 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001265 }
1266
1267 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001268 llvm::SmallVector<Expr *, 1> ExprVec;
1269 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001271 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001272 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001273 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001274 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001275 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001276 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001277 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001278 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001279 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001280 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001281 &ExprVec[0], 1,
1282 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001283 else {
1284 // FIXME. Refactor this into common code with that in
1285 // RewritePropertyOrImplicitGetter
1286 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1287 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1288 if (PropGetters[Exp])
1289 // This allows us to handle chain/nested property/implicit getters.
1290 Receiver = PropGetters[Exp];
1291
Douglas Gregor9a129192010-04-21 00:45:42 +00001292 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001293 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001294 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001295 /*FIXME: */SourceLocation(),
1296 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001297 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001298 &ExprVec[0], 1,
1299 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001300 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001301 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Steve Naroff4588d0f2008-12-04 16:24:46 +00001303 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001304 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001305 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001306 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1307 // to things that stay around.
1308 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001309 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001310}
1311
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001312Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1313 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001314 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001315 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001316 ObjCMethodDecl *OMD = 0;
1317 QualType Ty;
1318 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001319 bool Super = false;
1320 QualType SuperTy;
1321 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001322 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001323 if (ObjCPropertyRefExpr *PropRefExpr =
1324 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001325 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001326 if (PropRefExpr->isExplicitProperty()) {
1327 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1328 OMD = PDecl->getGetterMethodDecl();
1329 Ty = PDecl->getType();
1330 Sel = PDecl->getGetterName();
1331 } else {
1332 OMD = PropRefExpr->getImplicitPropertyGetter();
1333 Sel = OMD->getSelector();
1334 Ty = PropRefExpr->getType();
1335 }
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001336 Super = PropRefExpr->isSuperReceiver();
1337 if (!Super)
1338 Receiver = PropRefExpr->getBase();
1339 else {
John McCallb7bd14f2010-12-02 01:19:52 +00001340 SuperTy = PropRefExpr->getSuperReceiverType();
1341 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001342 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001343 }
1344
1345 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1346
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001347 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001348 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001349 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001350 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001351 Expr::getValueKindForType(Ty),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001352 /*FIXME?*/SourceLocation(),
1353 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001354 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001355 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001356 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001357 0, 0,
1358 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001359 else {
1360 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1361 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1362 if (PropGetters[Exp])
1363 // This allows us to handle chain/nested property/implicit getters.
1364 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001365 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001366 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001367 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001368 /*FIXME:*/SourceLocation(),
1369 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001370 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001371 0, 0,
1372 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001373 }
Steve Narofff326f402008-12-03 00:56:33 +00001374
Steve Naroff22216db2008-12-04 23:50:32 +00001375 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001376
1377 if (!PropParentMap)
1378 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001379 bool NestedPropertyRef = false;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001380 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001381 ImplicitCastExpr*ICE=0;
1382 if (Parent)
1383 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1384 assert((ICE->getCastKind() == CK_GetObjCProperty)
1385 && "RewritePropertyOrImplicitGetter");
1386 Parent = PropParentMap->getParent(Parent);
1387 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1388 }
1389 if (NestedPropertyRef) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001390 // We stash away the ReplacingStmt since actually doing the
1391 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001392 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001393 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1394 // to things that stay around.
1395 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001396 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001397 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001398 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001399 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001400 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1401 // to things that stay around.
1402 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001403 return ReplacingStmt;
1404 }
Steve Narofff326f402008-12-03 00:56:33 +00001405}
1406
Mike Stump11289f42009-09-09 15:08:12 +00001407Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001408 SourceLocation OrigStart,
1409 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001410 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001411 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001412 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001413 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001414 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001415 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001416 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001417 // lookup which class implements the instance variable.
1418 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001419 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001420 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001421 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001422
Steve Naroffb1c02372008-05-08 17:52:16 +00001423 // Synthesize an explicit cast to gain access to the ivar.
1424 std::string RecName = clsDeclared->getIdentifier()->getName();
1425 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001426 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001427 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001428 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001429 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1430 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001431 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001432 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001433 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001434 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001435 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001436 IV->getBase()->getLocEnd(),
1437 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001438 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001439 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001440 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001441 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001442 IV->getLocation(),
1443 D->getType(),
1444 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001445 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001446 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001447 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001448 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001449 // Cannot delete IV->getBase(), since PE points to it.
1450 // Replace the old base with the cast. This is important when doing
1451 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001452 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001453 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001454 }
Steve Naroff24840f62008-04-18 21:55:08 +00001455 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001456 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001457
Steve Naroff29ce4e52008-05-06 23:20:07 +00001458 // Explicit ivar refs need to have a cast inserted.
1459 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001460 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001461 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001462 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001463 // lookup which class implements the instance variable.
1464 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001465 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001466 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001467 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001468
Steve Naroff29ce4e52008-05-06 23:20:07 +00001469 // Synthesize an explicit cast to gain access to the ivar.
1470 std::string RecName = clsDeclared->getIdentifier()->getName();
1471 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001472 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001473 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001474 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001475 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1476 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001478 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001479 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001480 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001481 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001482 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001483 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001484 // Cannot delete IV->getBase(), since PE points to it.
1485 // Replace the old base with the cast. This is important when doing
1486 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001487 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001488 return IV;
1489 }
Steve Naroff05caa482007-11-15 11:33:00 +00001490 }
Steve Naroff24840f62008-04-18 21:55:08 +00001491 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001492}
1493
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001494Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall8322c3a2011-02-13 04:07:26 +00001495 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001496 if (*CI) {
1497 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1498 if (newStmt)
1499 *CI = newStmt;
1500 }
1501 }
1502 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1503 SourceRange OrigStmtRange = S->getSourceRange();
1504 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1505 replaced);
1506 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001507 }
1508 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1509 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1510 return newStmt;
1511 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001512 return S;
1513}
1514
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515/// SynthCountByEnumWithState - To print:
1516/// ((unsigned int (*)
1517/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001518/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001519/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001520/// "countByEnumeratingWithState:objects:count:"),
1521/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522/// (id *)items, (unsigned int)16)
1523///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001524void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001525 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1526 "id *, unsigned int))(void *)objc_msgSend)";
1527 buf += "\n\t\t";
1528 buf += "((id)l_collection,\n\t\t";
1529 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1530 buf += "\n\t\t";
1531 buf += "&enumState, "
1532 "(id *)items, (unsigned int)16)";
1533}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001534
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001535/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1536/// statement to exit to its outer synthesized loop.
1537///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001538Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001539 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540 return S;
1541 // replace break with goto __break_label
1542 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001543
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001544 SourceLocation startLoc = S->getLocStart();
1545 buf = "goto __break_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001547 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001548
1549 return 0;
1550}
1551
1552/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1553/// statement to continue with its inner synthesized loop.
1554///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001555Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001556 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1557 return S;
1558 // replace continue with goto __continue_label
1559 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001560
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001561 SourceLocation startLoc = S->getLocStart();
1562 buf = "goto __continue_label_";
1563 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001564 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001566 return 0;
1567}
1568
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001569/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001570/// It rewrites:
1571/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001573/// Into:
1574/// {
Mike Stump11289f42009-09-09 15:08:12 +00001575/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001576/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001577/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001578/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001579/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001580/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001581/// if (limit) {
1582/// unsigned long startMutations = *enumState.mutationsPtr;
1583/// do {
1584/// unsigned long counter = 0;
1585/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001586/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001587/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001588/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001589/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001590/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001591/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001592/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001593/// objects:items count:16]);
1594/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001595/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001596/// }
1597/// else
1598/// elem = nil;
1599/// }
1600///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001601Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001602 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001603 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001604 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001605 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001606 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001607 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001608
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001611 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001612 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 std::string buf;
1614 buf = "\n{\n\t";
1615 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1616 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001617 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001618 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001619 if (ElementType->isObjCQualifiedIdType() ||
1620 ElementType->isObjCQualifiedInterfaceType())
1621 // Simply use 'id' for all qualified types.
1622 elementTypeAsString = "id";
1623 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001624 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001625 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001626 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001627 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001628 buf += elementName;
1629 buf += ";\n\t";
1630 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001631 else {
1632 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001633 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001634 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1635 if (VD->getType()->isObjCQualifiedIdType() ||
1636 VD->getType()->isObjCQualifiedInterfaceType())
1637 // Simply use 'id' for all qualified types.
1638 elementTypeAsString = "id";
1639 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001640 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001643 // struct __objcFastEnumerationState enumState = { 0 };
1644 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1645 // id items[16];
1646 buf += "id items[16];\n\t";
1647 // id l_collection = (id)
1648 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001649 // Find start location of 'collection' the hard way!
1650 const char *startCollectionBuf = startBuf;
1651 startCollectionBuf += 3; // skip 'for'
1652 startCollectionBuf = strchr(startCollectionBuf, '(');
1653 startCollectionBuf++; // skip '('
1654 // find 'in' and skip it.
1655 while (*startCollectionBuf != ' ' ||
1656 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1657 (*(startCollectionBuf+3) != ' ' &&
1658 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1659 startCollectionBuf++;
1660 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001661
1662 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001663 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001664 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001665 SourceLocation rightParenLoc = S->getRParenLoc();
1666 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1667 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001668 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001669
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001670 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1671 // objects:items count:16];
1672 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001673 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001674 // ((unsigned int (*)
1675 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001676 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001677 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001678 // "countByEnumeratingWithState:objects:count:"),
1679 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 // (id *)items, (unsigned int)16);
1681 buf += "unsigned long limit =\n\t\t";
1682 SynthCountByEnumWithState(buf);
1683 buf += ";\n\t";
1684 /// if (limit) {
1685 /// unsigned long startMutations = *enumState.mutationsPtr;
1686 /// do {
1687 /// unsigned long counter = 0;
1688 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001689 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001690 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001691 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001692 buf += "if (limit) {\n\t";
1693 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1694 buf += "do {\n\t\t";
1695 buf += "unsigned long counter = 0;\n\t\t";
1696 buf += "do {\n\t\t\t";
1697 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1698 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1699 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001700 buf += " = (";
1701 buf += elementTypeAsString;
1702 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001703 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001704 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001705
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001706 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001707 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001708 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001709 /// objects:items count:16]);
1710 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001711 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001712 /// }
1713 /// else
1714 /// elem = nil;
1715 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001716 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001717 buf = ";\n\t";
1718 buf += "__continue_label_";
1719 buf += utostr(ObjCBcLabelNo.back());
1720 buf += ": ;";
1721 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001722 buf += "} while (counter < limit);\n\t";
1723 buf += "} while (limit = ";
1724 SynthCountByEnumWithState(buf);
1725 buf += ");\n\t";
1726 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001727 buf += " = ((";
1728 buf += elementTypeAsString;
1729 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001730 buf += "__break_label_";
1731 buf += utostr(ObjCBcLabelNo.back());
1732 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001733 buf += "}\n\t";
1734 buf += "else\n\t\t";
1735 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001736 buf += " = ((";
1737 buf += elementTypeAsString;
1738 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001739 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001740
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001741 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001742 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001743 if (isa<CompoundStmt>(S->getBody())) {
1744 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001745 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001746 } else {
1747 /* Need to treat single statements specially. For example:
1748 *
1749 * for (A *a in b) if (stuff()) break;
1750 * for (A *a in b) xxxyy;
1751 *
1752 * The following code simply scans ahead to the semi to find the actual end.
1753 */
1754 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1755 const char *semiBuf = strchr(stmtBuf, ';');
1756 assert(semiBuf && "Can't find ';'");
1757 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001758 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001759 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001760 Stmts.pop_back();
1761 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001762 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001763}
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001766/// This routine rewrites @synchronized(expr) stmt;
1767/// into:
1768/// objc_sync_enter(expr);
1769/// @try stmt @finally { objc_sync_exit(expr); }
1770///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001771Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001772 // Get the start location and compute the semi location.
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001776 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001777
1778 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001779 buf = "objc_sync_enter((id)";
1780 const char *lparenBuf = startBuf;
1781 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001782 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001783 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1784 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001785 // been rewritten! (which implies the SourceLocation's are invalid).
1786 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001787 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001788 while (*endBuf != ')') endBuf--;
1789 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001790 buf = ");\n";
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
1797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001798 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001799 startLoc = S->getSynchBody()->getLocEnd();
1800 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroffad7013b2008-08-19 13:04:19 +00001802 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001803 SourceLocation lastCurlyLoc = startLoc;
1804 buf = "}\nelse {\n";
1805 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001806 buf += "}\n";
1807 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001808 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001809
1810 std::string syncBuf;
1811 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001812 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001813 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001814 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001815 std::string syncExprBufS;
1816 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001817 syncExpr->printPretty(syncExprBuf, *Context, 0,
1818 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001819 syncBuf += syncExprBuf.str();
1820 syncBuf += ");";
1821
1822 buf += syncBuf;
1823 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001824 buf += "}\n";
1825 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001826
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001827 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001828
1829 bool hasReturns = false;
1830 HasReturnStmts(S->getSynchBody(), hasReturns);
1831 if (hasReturns)
1832 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1833
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001834 return 0;
1835}
1836
Steve Naroffec60b432009-12-05 21:43:12 +00001837void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1838{
Steve Naroff6d6da252008-12-05 17:03:39 +00001839 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001840 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001841 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001842 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001843
Steve Naroffec60b432009-12-05 21:43:12 +00001844 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001845 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001846 TryFinallyContainsReturnDiag);
1847 }
1848 return;
1849}
1850
Steve Naroffec60b432009-12-05 21:43:12 +00001851void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1852{
1853 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001854 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001855 if (*CI)
1856 HasReturnStmts(*CI, hasReturns);
1857
1858 if (isa<ReturnStmt>(S))
1859 hasReturns = true;
1860 return;
1861}
1862
1863void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1864 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001865 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001866 if (*CI) {
1867 RewriteTryReturnStmts(*CI);
1868 }
1869 if (isa<ReturnStmt>(S)) {
1870 SourceLocation startLoc = S->getLocStart();
1871 const char *startBuf = SM->getCharacterData(startLoc);
1872
1873 const char *semiBuf = strchr(startBuf, ';');
1874 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1875 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1876
1877 std::string buf;
1878 buf = "{ objc_exception_try_exit(&_stack); return";
1879
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001880 ReplaceText(startLoc, 6, buf);
1881 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001882 }
1883 return;
1884}
1885
1886void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1887 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001888 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001889 if (*CI) {
1890 RewriteSyncReturnStmts(*CI, syncExitBuf);
1891 }
1892 if (isa<ReturnStmt>(S)) {
1893 SourceLocation startLoc = S->getLocStart();
1894 const char *startBuf = SM->getCharacterData(startLoc);
1895
1896 const char *semiBuf = strchr(startBuf, ';');
1897 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1898 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1899
1900 std::string buf;
1901 buf = "{ objc_exception_try_exit(&_stack);";
1902 buf += syncExitBuf;
1903 buf += " return";
1904
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001905 ReplaceText(startLoc, 6, buf);
1906 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001907 }
1908 return;
1909}
1910
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001911Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001912 // Get the start location and compute the semi location.
1913 SourceLocation startLoc = S->getLocStart();
1914 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001915
Steve Naroffbf478ec2007-11-07 04:08:17 +00001916 assert((*startBuf == '@') && "bogus @try location");
1917
1918 std::string buf;
1919 // declare a new scope with two variables, _stack and _rethrow.
1920 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1921 buf += "int buf[18/*32-bit i386*/];\n";
1922 buf += "char *pointers[4];} _stack;\n";
1923 buf += "id volatile _rethrow = 0;\n";
1924 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001925 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001926
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001927 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Steve Naroffbf478ec2007-11-07 04:08:17 +00001929 startLoc = S->getTryBody()->getLocEnd();
1930 startBuf = SM->getCharacterData(startLoc);
1931
1932 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001933
Steve Naroffbf478ec2007-11-07 04:08:17 +00001934 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001935 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001936 startLoc = startLoc.getFileLocWithOffset(1);
1937 buf = " /* @catch begin */ else {\n";
1938 buf += " id _caught = objc_exception_extract(&_stack);\n";
1939 buf += " objc_exception_try_enter (&_stack);\n";
1940 buf += " if (_setjmp(_stack.buf))\n";
1941 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1942 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001943
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001944 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001945 } else { /* no catch list */
1946 buf = "}\nelse {\n";
1947 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1948 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001949 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001950 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001951 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001952 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1953 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001954 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001955
Douglas Gregor96c79492010-04-23 22:50:49 +00001956 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001957 buf = "if ("; // we are generating code for the first catch clause
1958 else
1959 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001960 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001961 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Steve Naroffbf478ec2007-11-07 04:08:17 +00001963 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001964
Steve Naroffbf478ec2007-11-07 04:08:17 +00001965 const char *lParenLoc = strchr(startBuf, '(');
1966
Douglas Gregor96c79492010-04-23 22:50:49 +00001967 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001968 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001969 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001970 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1971 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001972 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001973 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001974 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001975
Steve Naroffedb5bc62008-02-01 20:02:07 +00001976 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001977 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001978 } else if (catchDecl) {
1979 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001980 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001981 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001982 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001983 } else if (const ObjCObjectPointerType *Ptr =
1984 t->getAs<ObjCObjectPointerType>()) {
1985 // Should be a pointer to a class.
1986 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1987 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001988 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001989 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001990 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001991 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001992 }
1993 }
1994 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001995 lastCatchBody = Catch->getCatchBody();
1996 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001997 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1998 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1999 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2000 assert((*rParenBuf == ')') && "bogus @catch paren location");
2001 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002002
Mike Stump11289f42009-09-09 15:08:12 +00002003 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00002004 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002005 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00002006 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002007 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002008 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00002009 }
2010 // Complete the catch list...
2011 if (lastCatchBody) {
2012 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002013 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2014 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002015
Steve Naroff4adbe312008-09-11 15:29:03 +00002016 // Insert the last (implicit) else clause *before* the right curly brace.
2017 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2018 buf = "} /* last catch end */\n";
2019 buf += "else {\n";
2020 buf += " _rethrow = _caught;\n";
2021 buf += " objc_exception_try_exit(&_stack);\n";
2022 buf += "} } /* @catch end */\n";
2023 if (!S->getFinallyStmt())
2024 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002025 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002026
Steve Naroffbf478ec2007-11-07 04:08:17 +00002027 // Set lastCurlyLoc
2028 lastCurlyLoc = lastCatchBody->getLocEnd();
2029 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002030 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002031 startLoc = finalStmt->getLocStart();
2032 startBuf = SM->getCharacterData(startLoc);
2033 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002034
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002035 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002036
Steve Naroffbf478ec2007-11-07 04:08:17 +00002037 Stmt *body = finalStmt->getFinallyBody();
2038 SourceLocation startLoc = body->getLocStart();
2039 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002040 assert(*SM->getCharacterData(startLoc) == '{' &&
2041 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002042 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002043 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002044
Steve Naroffbf478ec2007-11-07 04:08:17 +00002045 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002046 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002047 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002048 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002049
Steve Naroffbf478ec2007-11-07 04:08:17 +00002050 // Set lastCurlyLoc
2051 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002052
Steve Naroff6d6da252008-12-05 17:03:39 +00002053 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002054 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002055 } else { /* no finally clause - make sure we synthesize an implicit one */
2056 buf = "{ /* implicit finally clause */\n";
2057 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2058 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2059 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002060 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002061
2062 // Now check for any return/continue/go statements within the @try.
2063 // The implicit finally clause won't called if the @try contains any
2064 // jump statements.
2065 bool hasReturns = false;
2066 HasReturnStmts(S->getTryBody(), hasReturns);
2067 if (hasReturns)
2068 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002069 }
2070 // Now emit the final closing curly brace...
2071 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002072 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002073 return 0;
2074}
2075
Mike Stump11289f42009-09-09 15:08:12 +00002076// This can't be done with ReplaceStmt(S, ThrowExpr), since
2077// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002078// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002079Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002080 // Get the start location and compute the semi location.
2081 SourceLocation startLoc = S->getLocStart();
2082 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002083
Steve Naroffa733c7f2007-11-07 15:32:26 +00002084 assert((*startBuf == '@') && "bogus @throw location");
2085
2086 std::string buf;
2087 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002088 if (S->getThrowExpr())
2089 buf = "objc_exception_throw(";
2090 else // add an implicit argument
2091 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002092
Steve Naroff29788342008-07-25 15:41:30 +00002093 // handle "@ throw" correctly.
2094 const char *wBuf = strchr(startBuf, 'w');
2095 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002096 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002097
Steve Naroffa733c7f2007-11-07 15:32:26 +00002098 const char *semiBuf = strchr(startBuf, ';');
2099 assert((*semiBuf == ';') && "@throw: can't find ';'");
2100 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002101 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002102 return 0;
2103}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002104
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002105Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002106 // Create a new string expression.
2107 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002108 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002109 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002110 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2111 StrEncoding.length(), false,StrType,
2112 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002113 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattner4431a1b2007-11-30 22:53:43 +00002115 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002116 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002117 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002118}
2119
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002120Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002121 if (!SelGetUidFunctionDecl)
2122 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002123 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2124 // Create a call to sel_registerName("selName").
2125 llvm::SmallVector<Expr*, 8> SelExprs;
2126 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002127 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002128 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002129 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002130 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002131 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2132 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002133 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002135 return SelExp;
2136}
2137
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002138CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002139 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2140 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002141 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002142 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002143
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002144 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002145 DeclRefExpr *DRE =
2146 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002147
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002148 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002149 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002150 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002151 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002152 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002153
John McCall9dd450b2009-09-21 23:43:11 +00002154 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002155
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002156 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002157 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002158 FT->getCallResultType(*Context),
2159 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002160 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002161}
2162
Steve Naroff50d42052007-11-01 13:24:47 +00002163static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2164 const char *&startRef, const char *&endRef) {
2165 while (startBuf < endBuf) {
2166 if (*startBuf == '<')
2167 startRef = startBuf; // mark the start.
2168 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002169 if (startRef && *startRef == '<') {
2170 endRef = startBuf; // mark the end.
2171 return true;
2172 }
2173 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002174 }
2175 startBuf++;
2176 }
2177 return false;
2178}
2179
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002180static void scanToNextArgument(const char *&argRef) {
2181 int angle = 0;
2182 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2183 if (*argRef == '<')
2184 angle++;
2185 else if (*argRef == '>')
2186 angle--;
2187 argRef++;
2188 }
2189 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2190}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002191
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002192bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002193 if (T->isObjCQualifiedIdType())
2194 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002195 if (const PointerType *PT = T->getAs<PointerType>()) {
2196 if (PT->getPointeeType()->isObjCQualifiedIdType())
2197 return true;
2198 }
2199 if (T->isObjCObjectPointerType()) {
2200 T = T->getPointeeType();
2201 return T->isObjCQualifiedInterfaceType();
2202 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002203 if (T->isArrayType()) {
2204 QualType ElemTy = Context->getBaseElementType(T);
2205 return needToScanForQualifiers(ElemTy);
2206 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002207 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002208}
2209
Steve Naroff873bd842008-07-29 18:15:38 +00002210void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2211 QualType Type = E->getType();
2212 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002213 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002214
Steve Naroffdbfc6932008-11-19 21:15:47 +00002215 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2216 Loc = ECE->getLParenLoc();
2217 EndLoc = ECE->getRParenLoc();
2218 } else {
2219 Loc = E->getLocStart();
2220 EndLoc = E->getLocEnd();
2221 }
2222 // This will defend against trying to rewrite synthesized expressions.
2223 if (Loc.isInvalid() || EndLoc.isInvalid())
2224 return;
2225
Steve Naroff873bd842008-07-29 18:15:38 +00002226 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002227 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002228 const char *startRef = 0, *endRef = 0;
2229 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2230 // Get the locations of the startRef, endRef.
2231 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2232 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2233 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002234 InsertText(LessLoc, "/*");
2235 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002236 }
2237 }
2238}
2239
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002240void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002241 SourceLocation Loc;
2242 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002243 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002244 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2245 Loc = VD->getLocation();
2246 Type = VD->getType();
2247 }
2248 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2249 Loc = FD->getLocation();
2250 // Check for ObjC 'id' and class types that have been adorned with protocol
2251 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002252 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002253 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002254 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002255 if (!proto)
2256 return;
2257 Type = proto->getResultType();
2258 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002259 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2260 Loc = FD->getLocation();
2261 Type = FD->getType();
2262 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002263 else
2264 return;
Mike Stump11289f42009-09-09 15:08:12 +00002265
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002266 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002267 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002268
Steve Naroff50d42052007-11-01 13:24:47 +00002269 const char *endBuf = SM->getCharacterData(Loc);
2270 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002271 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002272 startBuf--; // scan backward (from the decl location) for return type.
2273 const char *startRef = 0, *endRef = 0;
2274 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2275 // Get the locations of the startRef, endRef.
2276 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2277 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2278 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002279 InsertText(LessLoc, "/*");
2280 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002281 }
2282 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002283 if (!proto)
2284 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002285 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002286 const char *startBuf = SM->getCharacterData(Loc);
2287 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002288 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2289 if (needToScanForQualifiers(proto->getArgType(i))) {
2290 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002291
Steve Naroff50d42052007-11-01 13:24:47 +00002292 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002293 // scan forward (from the decl location) for argument types.
2294 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002295 const char *startRef = 0, *endRef = 0;
2296 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2297 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002298 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002299 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002300 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002301 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002302 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002303 InsertText(LessLoc, "/*");
2304 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002305 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002306 startBuf = ++endBuf;
2307 }
2308 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002309 // If the function name is derived from a macro expansion, then the
2310 // argument buffer will not follow the name. Need to speak with Chris.
2311 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002312 startBuf++; // scan forward (from the decl location) for argument types.
2313 startBuf++;
2314 }
Steve Naroff50d42052007-11-01 13:24:47 +00002315 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002316}
2317
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002318void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2319 QualType QT = ND->getType();
2320 const Type* TypePtr = QT->getAs<Type>();
2321 if (!isa<TypeOfExprType>(TypePtr))
2322 return;
2323 while (isa<TypeOfExprType>(TypePtr)) {
2324 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2325 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2326 TypePtr = QT->getAs<Type>();
2327 }
2328 // FIXME. This will not work for multiple declarators; as in:
2329 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002330 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002331 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2332 const char *startBuf = SM->getCharacterData(DeclLoc);
2333 if (ND->getInit()) {
2334 std::string Name(ND->getNameAsString());
2335 TypeAsString += " " + Name + " = ";
2336 Expr *E = ND->getInit();
2337 SourceLocation startLoc;
2338 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2339 startLoc = ECE->getLParenLoc();
2340 else
2341 startLoc = E->getLocStart();
2342 startLoc = SM->getInstantiationLoc(startLoc);
2343 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002344 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002345 }
2346 else {
2347 SourceLocation X = ND->getLocEnd();
2348 X = SM->getInstantiationLoc(X);
2349 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002350 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002351 }
2352}
2353
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002354// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002355void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002356 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2357 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002358 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002359 QualType getFuncType =
2360 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002361 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002362 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002363 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002364 SC_Extern,
2365 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002366}
2367
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002368void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002369 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002370 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002371 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002372 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002373 return;
2374 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002375 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002376}
2377
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002378void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2379 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002380 const char *argPtr = TypeString.c_str();
2381 if (!strchr(argPtr, '^')) {
2382 Str += TypeString;
2383 return;
2384 }
2385 while (*argPtr) {
2386 Str += (*argPtr == '^' ? '*' : *argPtr);
2387 argPtr++;
2388 }
2389}
2390
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002391// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002392void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2393 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002394 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002395 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002396 const char *argPtr = TypeString.c_str();
2397 int paren = 0;
2398 while (*argPtr) {
2399 switch (*argPtr) {
2400 case '(':
2401 Str += *argPtr;
2402 paren++;
2403 break;
2404 case ')':
2405 Str += *argPtr;
2406 paren--;
2407 break;
2408 case '^':
2409 Str += '*';
2410 if (paren == 1)
2411 Str += VD->getNameAsString();
2412 break;
2413 default:
2414 Str += *argPtr;
2415 break;
2416 }
2417 argPtr++;
2418 }
2419}
2420
2421
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002422void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2423 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2424 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2425 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2426 if (!proto)
2427 return;
2428 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002429 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002430 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002431 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002432 FdStr += "(";
2433 unsigned numArgs = proto->getNumArgs();
2434 for (unsigned i = 0; i < numArgs; i++) {
2435 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002436 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002437 if (i+1 < numArgs)
2438 FdStr += ", ";
2439 }
2440 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002441 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002442 CurFunctionDeclToDeclareForBlock = 0;
2443}
2444
Steve Naroff17978c42008-03-11 17:37:02 +00002445// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002446void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002447 if (SuperContructorFunctionDecl)
2448 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002449 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002450 llvm::SmallVector<QualType, 16> ArgTys;
2451 QualType argT = Context->getObjCIdType();
2452 assert(!argT.isNull() && "Can't find 'id' type");
2453 ArgTys.push_back(argT);
2454 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002455 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2456 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002457 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002458 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002459 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002460 SC_Extern,
2461 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002462}
2463
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002464// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002465void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2467 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002468 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002469 assert(!argT.isNull() && "Can't find 'id' type");
2470 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002471 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002472 assert(!argT.isNull() && "Can't find 'SEL' type");
2473 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002474 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2475 &ArgTys[0], ArgTys.size(),
2476 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002477 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002478 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002479 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002480 SC_Extern,
2481 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002482}
2483
Steve Naroff7fa2f042007-11-15 10:28:18 +00002484// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002485void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2487 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002488 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002489 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002490 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002491 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2492 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2493 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002494 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002495 assert(!argT.isNull() && "Can't find 'SEL' type");
2496 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002497 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2498 &ArgTys[0], ArgTys.size(),
2499 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002500 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002501 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002502 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002503 SC_Extern,
2504 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002505}
2506
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002507// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002508void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002509 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2510 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002511 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002512 assert(!argT.isNull() && "Can't find 'id' type");
2513 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002514 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002515 assert(!argT.isNull() && "Can't find 'SEL' type");
2516 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002517 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2518 &ArgTys[0], ArgTys.size(),
2519 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002520 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002521 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002522 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002523 SC_Extern,
2524 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002525}
2526
Mike Stump11289f42009-09-09 15:08:12 +00002527// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002528// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002529void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002530 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002531 &Context->Idents.get("objc_msgSendSuper_stret");
2532 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002533 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002534 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002535 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002536 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2537 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2538 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002539 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002540 assert(!argT.isNull() && "Can't find 'SEL' type");
2541 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002542 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2543 &ArgTys[0], ArgTys.size(),
2544 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002545 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002546 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002547 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002548 SC_Extern,
2549 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002550}
2551
Steve Naroff2e4e3852008-05-08 22:02:18 +00002552// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002553void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002554 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2555 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002556 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002557 assert(!argT.isNull() && "Can't find 'id' type");
2558 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002559 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002560 assert(!argT.isNull() && "Can't find 'SEL' type");
2561 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002562 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2563 &ArgTys[0], ArgTys.size(),
2564 true /*isVariadic*/);
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()));
John McCalldb40c7f2010-12-14 08:05:40 +00002577 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2578 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002579 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002580 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002581 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002582 SC_Extern,
2583 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002584}
2585
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002586// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2587void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2588 IdentifierInfo *getSuperClassIdent =
2589 &Context->Idents.get("class_getSuperclass");
2590 llvm::SmallVector<QualType, 16> ArgTys;
2591 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002592 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2593 &ArgTys[0], ArgTys.size());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002594 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002595 SourceLocation(),
2596 getSuperClassIdent,
2597 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002598 SC_Extern,
2599 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002600 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002601}
2602
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002603// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002604void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002605 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2606 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002607 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002608 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2609 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002610 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002611 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002612 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002613 SC_Extern,
2614 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002615}
2616
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002617Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002618 QualType strType = getConstantStringStructType();
2619
2620 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002621
2622 std::string tmpName = InFileName;
2623 unsigned i;
2624 for (i=0; i < tmpName.length(); i++) {
2625 char c = tmpName.at(i);
2626 // replace any non alphanumeric characters with '_'.
2627 if (!isalpha(c) && (c < '0' || c > '9'))
2628 tmpName[i] = '_';
2629 }
2630 S += tmpName;
2631 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002632 S += utostr(NumObjCStringLiterals++);
2633
Steve Naroff00a31762008-03-27 22:29:16 +00002634 Preamble += "static __NSConstantStringImpl " + S;
2635 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2636 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002637 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002638 std::string prettyBufS;
2639 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002640 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2641 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002642 Preamble += prettyBuf.str();
2643 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002644 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002645
2646 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002647 &Context->Idents.get(S), strType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002648 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002649 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2650 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002651 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002652 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002653 VK_RValue, OK_Ordinary,
2654 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002655 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002656 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002657 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002658 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002659 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002660 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002661}
2662
Steve Naroff7fa2f042007-11-15 10:28:18 +00002663// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002664QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002665 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002666 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002667 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002668 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002669 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002670
Steve Naroff7fa2f042007-11-15 10:28:18 +00002671 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002672 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002673 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002674 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002675
Steve Naroff7fa2f042007-11-15 10:28:18 +00002676 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002677 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002678 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2679 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002680 FieldTypes[i], 0,
2681 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002682 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregord5058122010-02-11 01:19:42 +00002685 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002686 }
2687 return Context->getTagDeclType(SuperStructDecl);
2688}
2689
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002690QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002691 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002692 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002693 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002694 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002695 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002696
Steve Naroffce8e8862008-03-15 00:55:56 +00002697 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002698 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002699 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002700 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002701 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002702 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002703 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002704 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002705
Steve Naroffce8e8862008-03-15 00:55:56 +00002706 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002707 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002708 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2709 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002710 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002711 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002712 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002713 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002714 }
2715
Douglas Gregord5058122010-02-11 01:19:42 +00002716 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002717 }
2718 return Context->getTagDeclType(ConstantStringDecl);
2719}
2720
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002721Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2722 SourceLocation StartLoc,
2723 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002724 if (!SelGetUidFunctionDecl)
2725 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002726 if (!MsgSendFunctionDecl)
2727 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002728 if (!MsgSendSuperFunctionDecl)
2729 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002730 if (!MsgSendStretFunctionDecl)
2731 SynthMsgSendStretFunctionDecl();
2732 if (!MsgSendSuperStretFunctionDecl)
2733 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002734 if (!MsgSendFpretFunctionDecl)
2735 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002736 if (!GetClassFunctionDecl)
2737 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002738 if (!GetSuperClassFunctionDecl)
2739 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002740 if (!GetMetaClassFunctionDecl)
2741 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002742
Steve Naroff7fa2f042007-11-15 10:28:18 +00002743 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002744 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2745 // May need to use objc_msgSend_stret() as well.
2746 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002747 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2748 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002749 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002750 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002751 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002752 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Steve Naroff574440f2007-10-24 22:48:43 +00002755 // Synthesize a call to objc_msgSend().
2756 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002757 switch (Exp->getReceiverKind()) {
2758 case ObjCMessageExpr::SuperClass: {
2759 MsgSendFlavor = MsgSendSuperFunctionDecl;
2760 if (MsgSendStretFlavor)
2761 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2762 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002763
Douglas Gregor9a129192010-04-21 00:45:42 +00002764 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002767
Douglas Gregor9a129192010-04-21 00:45:42 +00002768 // set the receiver to self, the first argument to all methods.
2769 InitExprs.push_back(
2770 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002771 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002772 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002773 Context->getObjCIdType(),
2774 VK_RValue,
2775 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002777
Douglas Gregor9a129192010-04-21 00:45:42 +00002778 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2779 llvm::SmallVector<Expr*, 8> ClsExprs;
2780 QualType argType = Context->getPointerType(Context->CharTy);
2781 ClsExprs.push_back(StringLiteral::Create(*Context,
2782 ClassDecl->getIdentifier()->getNameStart(),
2783 ClassDecl->getIdentifier()->getLength(),
2784 false, argType, SourceLocation()));
2785 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2786 &ClsExprs[0],
2787 ClsExprs.size(),
2788 StartLoc,
2789 EndLoc);
2790 // (Class)objc_getClass("CurrentClass")
2791 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2792 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002793 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002794 ClsExprs.clear();
2795 ClsExprs.push_back(ArgExpr);
2796 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2797 &ClsExprs[0], ClsExprs.size(),
2798 StartLoc, EndLoc);
2799
2800 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2801 // To turn off a warning, type-cast to 'id'
2802 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2803 NoTypeInfoCStyleCastExpr(Context,
2804 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002805 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002806 // struct objc_super
2807 QualType superType = getSuperStructType();
2808 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002809
Douglas Gregor9a129192010-04-21 00:45:42 +00002810 if (LangOpts.Microsoft) {
2811 SynthSuperContructorFunctionDecl();
2812 // Simulate a contructor call...
2813 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002814 superType, VK_LValue,
2815 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002816 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2817 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002818 superType, VK_LValue,
2819 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002820 // The code for super is a little tricky to prevent collision with
2821 // the structure definition in the header. The rewriter has it's own
2822 // internal definition (__rw_objc_super) that is uses. This is why
2823 // we need the cast below. For example:
2824 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2825 //
John McCalle3027922010-08-25 11:45:40 +00002826 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002827 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002828 VK_RValue, OK_Ordinary,
2829 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002830 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2831 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002832 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002833 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002834 // (struct objc_super) { <exprs from above> }
2835 InitListExpr *ILE =
2836 new (Context) InitListExpr(*Context, SourceLocation(),
2837 &InitExprs[0], InitExprs.size(),
2838 SourceLocation());
2839 TypeSourceInfo *superTInfo
2840 = Context->getTrivialTypeSourceInfo(superType);
2841 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002842 superType, VK_LValue,
2843 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002844 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002845 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002846 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002847 VK_RValue, OK_Ordinary,
2848 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002849 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002850 MsgExprs.push_back(SuperRep);
2851 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002852 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002853
2854 case ObjCMessageExpr::Class: {
2855 llvm::SmallVector<Expr*, 8> ClsExprs;
2856 QualType argType = Context->getPointerType(Context->CharTy);
2857 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002858 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002859 IdentifierInfo *clsName = Class->getIdentifier();
2860 ClsExprs.push_back(StringLiteral::Create(*Context,
2861 clsName->getNameStart(),
2862 clsName->getLength(),
2863 false, argType,
2864 SourceLocation()));
2865 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2866 &ClsExprs[0],
2867 ClsExprs.size(),
2868 StartLoc, EndLoc);
2869 MsgExprs.push_back(Cls);
2870 break;
2871 }
2872
2873 case ObjCMessageExpr::SuperInstance:{
2874 MsgSendFlavor = MsgSendSuperFunctionDecl;
2875 if (MsgSendStretFlavor)
2876 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2877 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2878 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2879 llvm::SmallVector<Expr*, 4> InitExprs;
2880
2881 InitExprs.push_back(
2882 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002883 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002884 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002885 Context->getObjCIdType(),
2886 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002887 ); // set the 'receiver'.
2888
2889 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2890 llvm::SmallVector<Expr*, 8> ClsExprs;
2891 QualType argType = Context->getPointerType(Context->CharTy);
2892 ClsExprs.push_back(StringLiteral::Create(*Context,
2893 ClassDecl->getIdentifier()->getNameStart(),
2894 ClassDecl->getIdentifier()->getLength(),
2895 false, argType, SourceLocation()));
2896 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2897 &ClsExprs[0],
2898 ClsExprs.size(),
2899 StartLoc, EndLoc);
2900 // (Class)objc_getClass("CurrentClass")
2901 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2902 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002903 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002904 ClsExprs.clear();
2905 ClsExprs.push_back(ArgExpr);
2906 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2907 &ClsExprs[0], ClsExprs.size(),
2908 StartLoc, EndLoc);
2909
2910 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2911 // To turn off a warning, type-cast to 'id'
2912 InitExprs.push_back(
2913 // set 'super class', using class_getSuperclass().
2914 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002915 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002916 // struct objc_super
2917 QualType superType = getSuperStructType();
2918 Expr *SuperRep;
2919
2920 if (LangOpts.Microsoft) {
2921 SynthSuperContructorFunctionDecl();
2922 // Simulate a contructor call...
2923 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002924 superType, VK_LValue,
2925 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002926 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2927 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002928 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002929 // The code for super is a little tricky to prevent collision with
2930 // the structure definition in the header. The rewriter has it's own
2931 // internal definition (__rw_objc_super) that is uses. This is why
2932 // we need the cast below. For example:
2933 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2934 //
John McCalle3027922010-08-25 11:45:40 +00002935 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002936 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002937 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002938 SourceLocation());
2939 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2940 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002941 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002942 } else {
2943 // (struct objc_super) { <exprs from above> }
2944 InitListExpr *ILE =
2945 new (Context) InitListExpr(*Context, SourceLocation(),
2946 &InitExprs[0], InitExprs.size(),
2947 SourceLocation());
2948 TypeSourceInfo *superTInfo
2949 = Context->getTrivialTypeSourceInfo(superType);
2950 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002951 superType, VK_RValue, ILE,
2952 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002953 }
2954 MsgExprs.push_back(SuperRep);
2955 break;
2956 }
2957
2958 case ObjCMessageExpr::Instance: {
2959 // Remove all type-casts because it may contain objc-style types; e.g.
2960 // Foo<Proto> *.
2961 Expr *recExpr = Exp->getInstanceReceiver();
2962 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2963 recExpr = CE->getSubExpr();
2964 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002965 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002966 MsgExprs.push_back(recExpr);
2967 break;
2968 }
2969 }
2970
Steve Naroffa397efd2007-11-03 11:27:19 +00002971 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002972 llvm::SmallVector<Expr*, 8> SelExprs;
2973 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002974 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002975 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002976 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002977 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002978 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002979 &SelExprs[0], SelExprs.size(),
2980 StartLoc,
2981 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002982 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002983
Steve Naroff574440f2007-10-24 22:48:43 +00002984 // Now push any user supplied arguments.
2985 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002986 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002987 // Make all implicit casts explicit...ICE comes in handy:-)
2988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2989 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002990 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002991 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002992 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002993 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002994 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00002995 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002996 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002997 }
2998 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002999 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003000 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003001 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003002 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003003 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003004 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003007 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003008 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3009 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003010 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003011 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003012 }
Steve Narofff36987c2007-11-04 22:37:50 +00003013 // Generate the funky cast.
3014 CastExpr *cast;
3015 llvm::SmallVector<QualType, 8> ArgTypes;
3016 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Steve Narofff36987c2007-11-04 22:37:50 +00003018 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003019 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3020 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3021 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003022 ArgTypes.push_back(Context->getObjCIdType());
3023 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003024 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003025 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003026 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3027 E = OMD->param_end(); PI != E; ++PI) {
3028 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003029 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003030 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003031 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003032 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003033 ArgTypes.push_back(t);
3034 }
Chris Lattnera4997152009-02-20 18:43:26 +00003035 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3036 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003037 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003038 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003039 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003040 }
3041 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003042 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003043
Steve Narofff36987c2007-11-04 22:37:50 +00003044 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003045 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003046 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003047
Mike Stump11289f42009-09-09 15:08:12 +00003048 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003049 // If we don't do this cast, we get the following bizarre warning/note:
3050 // xx.m:13: warning: function called through a non-compatible type
3051 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003052 cast = NoTypeInfoCStyleCastExpr(Context,
3053 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003054 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003055
Steve Narofff36987c2007-11-04 22:37:50 +00003056 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003057 QualType castType =
3058 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3059 // If we don't have a method decl, force a variadic cast.
3060 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00003061 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003062 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003063 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003064
3065 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003066 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003067
John McCall9dd450b2009-09-21 23:43:11 +00003068 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003069 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003070 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003071 FT->getResultType(), VK_RValue,
3072 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003073 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003074 if (MsgSendStretFlavor) {
3075 // We have the method which returns a struct/union. Must also generate
3076 // call to objc_msgSend_stret and hang both varieties on a conditional
3077 // expression which dictate which one to envoke depending on size of
3078 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003079
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003080 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003081 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003082 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003083 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003084 cast = NoTypeInfoCStyleCastExpr(Context,
3085 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003086 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003087 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003088 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3089 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003090 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003091 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003092 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003093
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003094 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003095 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003096
John McCall9dd450b2009-09-21 23:43:11 +00003097 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003098 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003099 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003100 FT->getResultType(), VK_RValue,
3101 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003102
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003103 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003104 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003105 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003106 Context->getSizeType(),
3107 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003108 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3109 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3110 // For X86 it is more complicated and some kind of target specific routine
3111 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003112 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003113 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003114 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3115 llvm::APInt(IntSize, 8),
3116 Context->IntTy,
3117 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003118 BinaryOperator *lessThanExpr =
3119 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3120 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003121 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003122 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003123 new (Context) ConditionalOperator(lessThanExpr,
3124 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003125 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003126 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003127 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3128 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003129 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003130 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003131 return ReplacingStmt;
3132}
3133
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003134Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003135 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3136 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003137
Steve Naroff574440f2007-10-24 22:48:43 +00003138 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003139 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003140
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003141 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003142 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003143}
3144
Steve Naroffd9803712009-04-29 16:37:50 +00003145// typedef struct objc_object Protocol;
3146QualType RewriteObjC::getProtocolType() {
3147 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003148 TypeSourceInfo *TInfo
3149 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003150 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003151 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003152 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003153 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003154 }
3155 return Context->getTypeDeclType(ProtocolTypeDecl);
3156}
3157
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003158/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003159/// a synthesized/forward data reference (to the protocol's metadata).
3160/// The forward references (and metadata) are generated in
3161/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003162Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003163 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3164 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003165 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003166 ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003167 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003168 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3169 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003170 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003171 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003172 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003173 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003174 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003175 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003176 ReplaceStmt(Exp, castExpr);
3177 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003178 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003179 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003181}
3182
Mike Stump11289f42009-09-09 15:08:12 +00003183bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003184 const char *endBuf) {
3185 while (startBuf < endBuf) {
3186 if (*startBuf == '#') {
3187 // Skip whitespace.
3188 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3189 ;
3190 if (!strncmp(startBuf, "if", strlen("if")) ||
3191 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3192 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3193 !strncmp(startBuf, "define", strlen("define")) ||
3194 !strncmp(startBuf, "undef", strlen("undef")) ||
3195 !strncmp(startBuf, "else", strlen("else")) ||
3196 !strncmp(startBuf, "elif", strlen("elif")) ||
3197 !strncmp(startBuf, "endif", strlen("endif")) ||
3198 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3199 !strncmp(startBuf, "include", strlen("include")) ||
3200 !strncmp(startBuf, "import", strlen("import")) ||
3201 !strncmp(startBuf, "include_next", strlen("include_next")))
3202 return true;
3203 }
3204 startBuf++;
3205 }
3206 return false;
3207}
3208
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003209/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003210/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003211void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003212 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003213 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003214 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003215 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003216 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003217 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003218 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003219 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003220 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003221 SourceLocation LocStart = CDecl->getLocStart();
3222 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003223
Steve Naroffdde78982007-11-14 19:25:57 +00003224 const char *startBuf = SM->getCharacterData(LocStart);
3225 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003226
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003227 // If no ivars and no root or if its root, directly or indirectly,
3228 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003229 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3230 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003231 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003232 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003233 return;
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235
3236 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003237 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003238 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003239 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003240 if (LangOpts.Microsoft)
3241 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003242
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003243 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003244 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003245 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003246 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003247 // If the buffer contains preprocessor directives, we do more fine-grained
3248 // rewrites. This is intended to fix code that looks like (which occurs in
3249 // NSURL.h, for example):
3250 //
3251 // #ifdef XYZ
3252 // @interface Foo : NSObject
3253 // #else
3254 // @interface FooBar : NSObject
3255 // #endif
3256 // {
3257 // int i;
3258 // }
3259 // @end
3260 //
3261 // This clause is segregated to avoid breaking the common case.
3262 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003263 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003264 CDecl->getClassLoc();
3265 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003266 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003267
Chris Lattnerf5b77512009-02-20 18:18:36 +00003268 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003269 // advance to the end of the referenced protocols.
3270 while (endHeader < cursor && *endHeader != '>') endHeader++;
3271 endHeader++;
3272 }
3273 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003274 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003275 } else {
3276 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003277 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003278 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003279 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003280 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003281 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003282 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003283 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003284 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003285
Steve Naroffdde78982007-11-14 19:25:57 +00003286 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003287 SourceLocation OnePastCurly =
3288 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003289 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003290 }
3291 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003292
Steve Naroffdde78982007-11-14 19:25:57 +00003293 // Now comment out any visibility specifiers.
3294 while (cursor < endBuf) {
3295 if (*cursor == '@') {
3296 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003297 // Skip whitespace.
3298 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3299 /*scan*/;
3300
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003301 // FIXME: presence of @public, etc. inside comment results in
3302 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003303 if (!strncmp(cursor, "public", strlen("public")) ||
3304 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003305 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003306 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003307 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003308 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003309 // FIXME: If there are cases where '<' is used in ivar declaration part
3310 // of user code, then scan the ivar list and use needToScanForQualifiers
3311 // for type checking.
3312 else if (*cursor == '<') {
3313 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003314 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003315 cursor = strchr(cursor, '>');
3316 cursor++;
3317 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003318 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003319 } else if (*cursor == '^') { // rewrite block specifier.
3320 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003321 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003322 }
Steve Naroffdde78982007-11-14 19:25:57 +00003323 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003324 }
Steve Naroffdde78982007-11-14 19:25:57 +00003325 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003326 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003327 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003328 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003329 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003330 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003331 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003332 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003333 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003334 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003335 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003336 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003337 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003338 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003339}
3340
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003341// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003342/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003343template<typename MethodIterator>
3344void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3345 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003346 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003347 llvm::StringRef prefix,
3348 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003349 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003350 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003351
Chris Lattner31bc07e2007-12-12 07:46:12 +00003352 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003353 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003354 SEL _cmd;
3355 char *method_types;
3356 void *_imp;
3357 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003358 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003359 Result += "\nstruct _objc_method {\n";
3360 Result += "\tSEL _cmd;\n";
3361 Result += "\tchar *method_types;\n";
3362 Result += "\tvoid *_imp;\n";
3363 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003364
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003365 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003366 }
Mike Stump11289f42009-09-09 15:08:12 +00003367
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003368 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003369
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003370 /* struct {
3371 struct _objc_method_list *next_method;
3372 int method_count;
3373 struct _objc_method method_list[];
3374 }
3375 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003376 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003377 Result += "\nstatic struct {\n";
3378 Result += "\tstruct _objc_method_list *next_method;\n";
3379 Result += "\tint method_count;\n";
3380 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003381 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003382 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003383 Result += prefix;
3384 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3385 Result += "_METHODS_";
3386 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003387 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003388 Result += IsInstanceMethod ? "inst" : "cls";
3389 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003390 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003391
Chris Lattner31bc07e2007-12-12 07:46:12 +00003392 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003393 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003394 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003395 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003396 Result += "\", \"";
3397 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003398 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003399 Result += MethodInternalNames[*MethodBegin];
3400 Result += "}\n";
3401 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3402 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003403 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003404 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003405 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003406 Result += "\", \"";
3407 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003408 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003409 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003410 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003411 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003412 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003413}
3414
Steve Naroffd9803712009-04-29 16:37:50 +00003415/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003416void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003417RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3418 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003419 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003420
3421 // Output struct protocol_methods holder of method selector and type.
3422 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3423 /* struct protocol_methods {
3424 SEL _cmd;
3425 char *method_types;
3426 }
3427 */
3428 Result += "\nstruct _protocol_methods {\n";
3429 Result += "\tstruct objc_selector *_cmd;\n";
3430 Result += "\tchar *method_types;\n";
3431 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003432
Steve Naroffd9803712009-04-29 16:37:50 +00003433 objc_protocol_methods = true;
3434 }
3435 // Do not synthesize the protocol more than once.
3436 if (ObjCSynthesizedProtocols.count(PDecl))
3437 return;
Mike Stump11289f42009-09-09 15:08:12 +00003438
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003439 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3440 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3441 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003442 /* struct _objc_protocol_method_list {
3443 int protocol_method_count;
3444 struct protocol_methods protocols[];
3445 }
Steve Naroff251084d2008-03-12 01:06:30 +00003446 */
Steve Naroffd9803712009-04-29 16:37:50 +00003447 Result += "\nstatic struct {\n";
3448 Result += "\tint protocol_method_count;\n";
3449 Result += "\tstruct _protocol_methods protocol_methods[";
3450 Result += utostr(NumMethods);
3451 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3452 Result += PDecl->getNameAsString();
3453 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3454 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003455
Steve Naroffd9803712009-04-29 16:37:50 +00003456 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003457 for (ObjCProtocolDecl::instmeth_iterator
3458 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003459 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003460 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003461 Result += "\t ,{{(struct objc_selector *)\"";
3462 else
3463 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003464 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003465 std::string MethodTypeString;
3466 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3467 Result += "\", \"";
3468 Result += MethodTypeString;
3469 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003470 }
Steve Naroffd9803712009-04-29 16:37:50 +00003471 Result += "\t }\n};\n";
3472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473
Steve Naroffd9803712009-04-29 16:37:50 +00003474 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003475 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3476 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003477 if (NumMethods > 0) {
3478 /* struct _objc_protocol_method_list {
3479 int protocol_method_count;
3480 struct protocol_methods protocols[];
3481 }
3482 */
3483 Result += "\nstatic struct {\n";
3484 Result += "\tint protocol_method_count;\n";
3485 Result += "\tstruct _protocol_methods protocol_methods[";
3486 Result += utostr(NumMethods);
3487 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3488 Result += PDecl->getNameAsString();
3489 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3490 "{\n\t";
3491 Result += utostr(NumMethods);
3492 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003493
Steve Naroffd9803712009-04-29 16:37:50 +00003494 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003495 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003496 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003497 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003498 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003499 Result += "\t ,{{(struct objc_selector *)\"";
3500 else
3501 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003502 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003503 std::string MethodTypeString;
3504 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3505 Result += "\", \"";
3506 Result += MethodTypeString;
3507 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003508 }
Steve Naroffd9803712009-04-29 16:37:50 +00003509 Result += "\t }\n};\n";
3510 }
3511
3512 // Output:
3513 /* struct _objc_protocol {
3514 // Objective-C 1.0 extensions
3515 struct _objc_protocol_extension *isa;
3516 char *protocol_name;
3517 struct _objc_protocol **protocol_list;
3518 struct _objc_protocol_method_list *instance_methods;
3519 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003520 };
Steve Naroffd9803712009-04-29 16:37:50 +00003521 */
3522 static bool objc_protocol = false;
3523 if (!objc_protocol) {
3524 Result += "\nstruct _objc_protocol {\n";
3525 Result += "\tstruct _objc_protocol_extension *isa;\n";
3526 Result += "\tchar *protocol_name;\n";
3527 Result += "\tstruct _objc_protocol **protocol_list;\n";
3528 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3529 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003530 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003531
Steve Naroffd9803712009-04-29 16:37:50 +00003532 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Steve Naroffd9803712009-04-29 16:37:50 +00003535 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3536 Result += PDecl->getNameAsString();
3537 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3538 "{\n\t0, \"";
3539 Result += PDecl->getNameAsString();
3540 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003541 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003542 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3543 Result += PDecl->getNameAsString();
3544 Result += ", ";
3545 }
3546 else
3547 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003548 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003549 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3550 Result += PDecl->getNameAsString();
3551 Result += "\n";
3552 }
3553 else
3554 Result += "0\n";
3555 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003556
Steve Naroffd9803712009-04-29 16:37:50 +00003557 // Mark this protocol as having been generated.
3558 if (!ObjCSynthesizedProtocols.insert(PDecl))
3559 assert(false && "protocol already synthesized");
3560
3561}
3562
3563void RewriteObjC::
3564RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003565 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003566 std::string &Result) {
3567 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003568
Steve Naroffd9803712009-04-29 16:37:50 +00003569 for (unsigned i = 0; i != Protocols.size(); i++)
3570 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3571
Chris Lattner388f6e92008-07-21 21:33:21 +00003572 // Output the top lovel protocol meta-data for the class.
3573 /* struct _objc_protocol_list {
3574 struct _objc_protocol_list *next;
3575 int protocol_count;
3576 struct _objc_protocol *class_protocols[];
3577 }
3578 */
3579 Result += "\nstatic struct {\n";
3580 Result += "\tstruct _objc_protocol_list *next;\n";
3581 Result += "\tint protocol_count;\n";
3582 Result += "\tstruct _objc_protocol *class_protocols[";
3583 Result += utostr(Protocols.size());
3584 Result += "];\n} _OBJC_";
3585 Result += prefix;
3586 Result += "_PROTOCOLS_";
3587 Result += ClassName;
3588 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3589 "{\n\t0, ";
3590 Result += utostr(Protocols.size());
3591 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003592
Chris Lattner388f6e92008-07-21 21:33:21 +00003593 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003594 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003595 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003596
Chris Lattner388f6e92008-07-21 21:33:21 +00003597 for (unsigned i = 1; i != Protocols.size(); i++) {
3598 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003599 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003600 Result += "\n";
3601 }
3602 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003603}
3604
Steve Naroffd9803712009-04-29 16:37:50 +00003605
Mike Stump11289f42009-09-09 15:08:12 +00003606/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003607/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003608void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003609 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003610 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003611 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003612 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003613 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003614 CDecl = CDecl->getNextClassCategory())
3615 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3616 break;
Mike Stump11289f42009-09-09 15:08:12 +00003617
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003618 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003619 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003620 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003621
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003622 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003623 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003624 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003625
3626 // If any of our property implementations have associated getters or
3627 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003628 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3629 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003630 Prop != PropEnd; ++Prop) {
3631 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3632 continue;
3633 if (!(*Prop)->getPropertyIvarDecl())
3634 continue;
3635 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3636 if (!PD)
3637 continue;
3638 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3639 InstanceMethods.push_back(Getter);
3640 if (PD->isReadOnly())
3641 continue;
3642 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3643 InstanceMethods.push_back(Setter);
3644 }
3645 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003646 true, "CATEGORY_", FullCategoryName.c_str(),
3647 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003648
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003649 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003650 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003651 false, "CATEGORY_", FullCategoryName.c_str(),
3652 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003653
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003654 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003655 // Null CDecl is case of a category implementation with no category interface
3656 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003657 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003658 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003659 /* struct _objc_category {
3660 char *category_name;
3661 char *class_name;
3662 struct _objc_method_list *instance_methods;
3663 struct _objc_method_list *class_methods;
3664 struct _objc_protocol_list *protocols;
3665 // Objective-C 1.0 extensions
3666 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003667 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003668 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003669 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003670 */
Mike Stump11289f42009-09-09 15:08:12 +00003671
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003672 static bool objc_category = false;
3673 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003674 Result += "\nstruct _objc_category {\n";
3675 Result += "\tchar *category_name;\n";
3676 Result += "\tchar *class_name;\n";
3677 Result += "\tstruct _objc_method_list *instance_methods;\n";
3678 Result += "\tstruct _objc_method_list *class_methods;\n";
3679 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003680 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 Result += "\tstruct _objc_property_list *instance_properties;\n";
3682 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003683 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003684 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003685 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3686 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003687 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003688 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003689 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003690 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003691 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003692
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003693 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 Result += "\t, (struct _objc_method_list *)"
3695 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3696 Result += FullCategoryName;
3697 Result += "\n";
3698 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003699 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003700 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003701 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 Result += "\t, (struct _objc_method_list *)"
3703 "&_OBJC_CATEGORY_CLASS_METHODS_";
3704 Result += FullCategoryName;
3705 Result += "\n";
3706 }
3707 else
3708 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003709
Chris Lattnerf5b77512009-02-20 18:18:36 +00003710 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003711 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003712 Result += FullCategoryName;
3713 Result += "\n";
3714 }
3715 else
3716 Result += "\t, 0\n";
3717 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003718}
3719
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003720/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3721/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003722void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003723 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003724 if (ivar->isBitField()) {
3725 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3726 // place all bitfields at offset 0.
3727 Result += "0";
3728 } else {
3729 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003730 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003731 if (LangOpts.Microsoft)
3732 Result += "_IMPL";
3733 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003734 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003735 Result += ")";
3736 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003737}
3738
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003739//===----------------------------------------------------------------------===//
3740// Meta Data Emission
3741//===----------------------------------------------------------------------===//
3742
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003743void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003744 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003745 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003746
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003747 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003748 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003749 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003750 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003751 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003752 }
Mike Stump11289f42009-09-09 15:08:12 +00003753
Chris Lattner30d23e82007-12-12 07:56:42 +00003754 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003755 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003756 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003757 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003758 if (NumIvars > 0) {
3759 static bool objc_ivar = false;
3760 if (!objc_ivar) {
3761 /* struct _objc_ivar {
3762 char *ivar_name;
3763 char *ivar_type;
3764 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003765 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003766 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003767 Result += "\nstruct _objc_ivar {\n";
3768 Result += "\tchar *ivar_name;\n";
3769 Result += "\tchar *ivar_type;\n";
3770 Result += "\tint ivar_offset;\n";
3771 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003772
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003773 objc_ivar = true;
3774 }
3775
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003776 /* struct {
3777 int ivar_count;
3778 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003779 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003780 */
Mike Stump11289f42009-09-09 15:08:12 +00003781 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003782 Result += "\tint ivar_count;\n";
3783 Result += "\tstruct _objc_ivar ivar_list[";
3784 Result += utostr(NumIvars);
3785 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003786 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003787 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003788 "{\n\t";
3789 Result += utostr(NumIvars);
3790 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003791
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003792 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003793 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003794 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003795 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003796 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003797 IV != IVEnd; ++IV)
3798 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003799 IVI = IDecl->ivar_begin();
3800 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003801 } else {
3802 IVI = CDecl->ivar_begin();
3803 IVE = CDecl->ivar_end();
3804 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003805 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003806 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003807 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003808 std::string TmpString, StrEncoding;
3809 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3810 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003811 Result += StrEncoding;
3812 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003813 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003814 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003815 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003816 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003817 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003818 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003819 std::string TmpString, StrEncoding;
3820 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3821 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003822 Result += StrEncoding;
3823 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003824 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003825 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003826 }
Mike Stump11289f42009-09-09 15:08:12 +00003827
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003828 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003831 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003832 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003833 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003834
3835 // If any of our property implementations have associated getters or
3836 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003837 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3838 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003839 Prop != PropEnd; ++Prop) {
3840 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3841 continue;
3842 if (!(*Prop)->getPropertyIvarDecl())
3843 continue;
3844 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3845 if (!PD)
3846 continue;
3847 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003848 if (!Getter->isDefined())
3849 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003850 if (PD->isReadOnly())
3851 continue;
3852 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003853 if (!Setter->isDefined())
3854 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003855 }
3856 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003857 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003858
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003859 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003860 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003861 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003862
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003863 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003864 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003865 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003866
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003867 // Declaration of class/meta-class metadata
3868 /* struct _objc_class {
3869 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003870 const char *super_class_name;
3871 char *name;
3872 long version;
3873 long info;
3874 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003875 struct _objc_ivar_list *ivars;
3876 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003877 struct objc_cache *cache;
3878 struct objc_protocol_list *protocols;
3879 const char *ivar_layout;
3880 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003881 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003882 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003883 static bool objc_class = false;
3884 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003885 Result += "\nstruct _objc_class {\n";
3886 Result += "\tstruct _objc_class *isa;\n";
3887 Result += "\tconst char *super_class_name;\n";
3888 Result += "\tchar *name;\n";
3889 Result += "\tlong version;\n";
3890 Result += "\tlong info;\n";
3891 Result += "\tlong instance_size;\n";
3892 Result += "\tstruct _objc_ivar_list *ivars;\n";
3893 Result += "\tstruct _objc_method_list *methods;\n";
3894 Result += "\tstruct objc_cache *cache;\n";
3895 Result += "\tstruct _objc_protocol_list *protocols;\n";
3896 Result += "\tconst char *ivar_layout;\n";
3897 Result += "\tstruct _objc_class_ext *ext;\n";
3898 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003899 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003900 }
Mike Stump11289f42009-09-09 15:08:12 +00003901
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003902 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003903 ObjCInterfaceDecl *RootClass = 0;
3904 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003905 while (SuperClass) {
3906 RootClass = SuperClass;
3907 SuperClass = SuperClass->getSuperClass();
3908 }
3909 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003910
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003911 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003912 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003913 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003914 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003915 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003916 Result += "\"";
3917
3918 if (SuperClass) {
3919 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003921 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003922 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003923 Result += "\"";
3924 }
3925 else {
3926 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003927 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003928 Result += "\"";
3929 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003930 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003931 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003932 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003933 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003934 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003935 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003936 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003937 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003938 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003939 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003940 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003941 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003942 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003943 Result += ",0,0\n";
3944 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003945 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003946 Result += "\t,0,0,0,0\n";
3947 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003948
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003949 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003950 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003952 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003953 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003954 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003955 if (SuperClass) {
3956 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003957 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003958 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003959 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003960 Result += "\"";
3961 }
3962 else {
3963 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003964 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003965 Result += "\"";
3966 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003967 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003968 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003969 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003970 Result += ",0";
3971 else {
3972 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003973 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003974 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003975 if (LangOpts.Microsoft)
3976 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003977 Result += ")";
3978 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003979 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003980 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003981 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003982 Result += "\n\t";
3983 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003984 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003985 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003986 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003987 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003988 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003989 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003990 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003991 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003992 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003993 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003994 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003995 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003996 Result += ", 0,0\n";
3997 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003998 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003999 Result += ",0,0,0\n";
4000 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004001}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004002
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004003/// RewriteImplementations - This routine rewrites all method implementations
4004/// and emits meta-data.
4005
Steve Narofff8cfd162008-11-13 20:07:04 +00004006void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004007 int ClsDefCount = ClassImplementation.size();
4008 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004009
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004010 // Rewrite implemented methods
4011 for (int i = 0; i < ClsDefCount; i++)
4012 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004013
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004014 for (int i = 0; i < CatDefCount; i++)
4015 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004016}
Mike Stump11289f42009-09-09 15:08:12 +00004017
Steve Narofff8cfd162008-11-13 20:07:04 +00004018void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4019 int ClsDefCount = ClassImplementation.size();
4020 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004021
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004022 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004023 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004024 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004025
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004026 // For each implemented category, write out all its meta data.
4027 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004028 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004029
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004030 // Write objc_symtab metadata
4031 /*
4032 struct _objc_symtab
4033 {
4034 long sel_ref_cnt;
4035 SEL *refs;
4036 short cls_def_cnt;
4037 short cat_def_cnt;
4038 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004039 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004040 */
Mike Stump11289f42009-09-09 15:08:12 +00004041
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004042 Result += "\nstruct _objc_symtab {\n";
4043 Result += "\tlong sel_ref_cnt;\n";
4044 Result += "\tSEL *refs;\n";
4045 Result += "\tshort cls_def_cnt;\n";
4046 Result += "\tshort cat_def_cnt;\n";
4047 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4048 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004049
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004050 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004051 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004052 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004053 + ", " + utostr(CatDefCount) + "\n";
4054 for (int i = 0; i < ClsDefCount; i++) {
4055 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004056 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004057 Result += "\n";
4058 }
Mike Stump11289f42009-09-09 15:08:12 +00004059
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004060 for (int i = 0; i < CatDefCount; i++) {
4061 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004062 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004063 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004064 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004065 Result += "\n";
4066 }
Mike Stump11289f42009-09-09 15:08:12 +00004067
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004068 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004069
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004070 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004071
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004072 /*
4073 struct _objc_module {
4074 long version;
4075 long size;
4076 const char *name;
4077 struct _objc_symtab *symtab;
4078 }
4079 */
Mike Stump11289f42009-09-09 15:08:12 +00004080
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004081 Result += "\nstruct _objc_module {\n";
4082 Result += "\tlong version;\n";
4083 Result += "\tlong size;\n";
4084 Result += "\tconst char *name;\n";
4085 Result += "\tstruct _objc_symtab *symtab;\n";
4086 Result += "};\n\n";
4087 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004088 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004089 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004090 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004091 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004092
4093 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004094 if (ProtocolExprDecls.size()) {
4095 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4096 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004097 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004098 E = ProtocolExprDecls.end(); I != E; ++I) {
4099 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4100 Result += (*I)->getNameAsString();
4101 Result += " = &_OBJC_PROTOCOL_";
4102 Result += (*I)->getNameAsString();
4103 Result += ";\n";
4104 }
4105 Result += "#pragma data_seg(pop)\n\n";
4106 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004107 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004108 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004109 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4110 Result += "&_OBJC_MODULES;\n";
4111 Result += "#pragma data_seg(pop)\n\n";
4112 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004113}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004114
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004115void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4116 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004117 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004118 assert(BlockByRefDeclNo.count(VD) &&
4119 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004120 if (def)
4121 ResultStr += "struct ";
4122 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004123 "_" + utostr(BlockByRefDeclNo[VD]) ;
4124}
4125
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004126static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4127 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4128 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4129 return false;
4130}
4131
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004133 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 std::string Tag) {
4135 const FunctionType *AFT = CE->getFunctionType();
4136 QualType RT = AFT->getResultType();
4137 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004138 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004139 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004140
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004142
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004143 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004144 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004145 // block (to reference imported block decl refs).
4146 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004147 } else if (BD->param_empty()) {
4148 S += "(" + StructRef + " *__cself)";
4149 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004150 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004151 assert(FT && "SynthesizeBlockFunc: No function proto");
4152 S += '(';
4153 // first add the implicit argument.
4154 S += StructRef + " *__cself, ";
4155 std::string ParamStr;
4156 for (BlockDecl::param_iterator AI = BD->param_begin(),
4157 E = BD->param_end(); AI != E; ++AI) {
4158 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004159 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004160 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004161 if (convertBlockPointerToFunctionPointer(QT))
4162 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004163 else
4164 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004165 S += ParamStr;
4166 }
4167 if (FT->isVariadic()) {
4168 if (!BD->param_empty()) S += ", ";
4169 S += "...";
4170 }
4171 S += ')';
4172 }
4173 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004174
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 // Create local declarations to avoid rewriting all closure decl ref exprs.
4176 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004177 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004178 E = BlockByRefDecls.end(); I != E; ++I) {
4179 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004180 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004181 std::string TypeString;
4182 RewriteByRefString(TypeString, Name, (*I));
4183 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004184 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004185 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004186 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004188 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 E = BlockByCopyDecls.end(); I != E; ++I) {
4190 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 // Handle nested closure invocation. For example:
4192 //
4193 // void (^myImportedClosure)(void);
4194 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004195 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 // void (^anotherClosure)(void);
4197 // anotherClosure = ^(void) {
4198 // myImportedClosure(); // import and invoke the closure
4199 // };
4200 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004201 if (isTopLevelBlockPointerType((*I)->getType())) {
4202 RewriteBlockPointerTypeVariable(S, (*I));
4203 S += " = (";
4204 RewriteBlockPointerType(S, (*I)->getType());
4205 S += ")";
4206 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4207 }
4208 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004209 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004210 QualType QT = (*I)->getType();
4211 if (HasLocalVariableExternalStorage(*I))
4212 QT = Context->getPointerType(QT);
4213 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004214 S += Name + " = __cself->" +
4215 (*I)->getNameAsString() + "; // bound by copy\n";
4216 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 }
4218 std::string RewrittenStr = RewrittenBlockExprs[CE];
4219 const char *cstr = RewrittenStr.c_str();
4220 while (*cstr++ != '{') ;
4221 S += cstr;
4222 S += "\n";
4223 return S;
4224}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004225
Steve Naroff677ab3a2008-10-27 17:20:55 +00004226std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004227 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 std::string Tag) {
4229 std::string StructRef = "struct " + Tag;
4230 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004231
Steve Naroff677ab3a2008-10-27 17:20:55 +00004232 S += funcName;
4233 S += "_block_copy_" + utostr(i);
4234 S += "(" + StructRef;
4235 S += "*dst, " + StructRef;
4236 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004237 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004238 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004239 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004240 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004241 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004242 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004243 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004244 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004245 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004246 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004248 S += "}\n";
4249
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250 S += "\nstatic void __";
4251 S += funcName;
4252 S += "_block_dispose_" + utostr(i);
4253 S += "(" + StructRef;
4254 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004255 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004257 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004258 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004259 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004260 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004261 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004262 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004265 return S;
4266}
4267
Steve Naroff30484702009-12-06 21:14:13 +00004268std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4269 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004270 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004272
Steve Naroff677ab3a2008-10-27 17:20:55 +00004273 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004274 S += " struct " + Desc;
4275 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff30484702009-12-06 21:14:13 +00004277 Constructor += "(void *fp, "; // Invoke function pointer.
4278 Constructor += "struct " + Desc; // Descriptor pointer.
4279 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004280
Steve Naroff677ab3a2008-10-27 17:20:55 +00004281 if (BlockDeclRefs.size()) {
4282 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004283 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284 E = BlockByCopyDecls.end(); I != E; ++I) {
4285 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004286 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 std::string ArgName = "_" + FieldName;
4288 // Handle nested closure invocation. For example:
4289 //
4290 // void (^myImportedBlock)(void);
4291 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004292 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 // void (^anotherBlock)(void);
4294 // anotherBlock = ^(void) {
4295 // myImportedBlock(); // import and invoke the closure
4296 // };
4297 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004298 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 S += "struct __block_impl *";
4300 Constructor += ", void *" + ArgName;
4301 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004302 QualType QT = (*I)->getType();
4303 if (HasLocalVariableExternalStorage(*I))
4304 QT = Context->getPointerType(QT);
4305 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4306 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 Constructor += ", " + ArgName;
4308 }
4309 S += FieldName + ";\n";
4310 }
4311 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004312 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 E = BlockByRefDecls.end(); I != E; ++I) {
4314 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004315 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 std::string ArgName = "_" + FieldName;
4317 // Handle nested closure invocation. For example:
4318 //
4319 // void (^myImportedBlock)(void);
4320 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004321 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004322 // void (^anotherBlock)(void);
4323 // anotherBlock = ^(void) {
4324 // myImportedBlock(); // import and invoke the closure
4325 // };
4326 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004327 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 S += "struct __block_impl *";
4329 Constructor += ", void *" + ArgName;
4330 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004331 std::string TypeString;
4332 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004333 TypeString += " *";
4334 FieldName = TypeString + FieldName;
4335 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004336 Constructor += ", " + ArgName;
4337 }
4338 S += FieldName + "; // by ref\n";
4339 }
4340 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004341 Constructor += ", int flags=0)";
4342 // Initialize all "by copy" arguments.
4343 bool firsTime = true;
4344 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4345 E = BlockByCopyDecls.end(); I != E; ++I) {
4346 std::string Name = (*I)->getNameAsString();
4347 if (firsTime) {
4348 Constructor += " : ";
4349 firsTime = false;
4350 }
4351 else
4352 Constructor += ", ";
4353 if (isTopLevelBlockPointerType((*I)->getType()))
4354 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4355 else
4356 Constructor += Name + "(_" + Name + ")";
4357 }
4358 // Initialize all "by ref" arguments.
4359 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4360 E = BlockByRefDecls.end(); I != E; ++I) {
4361 std::string Name = (*I)->getNameAsString();
4362 if (firsTime) {
4363 Constructor += " : ";
4364 firsTime = false;
4365 }
4366 else
4367 Constructor += ", ";
4368 if (isTopLevelBlockPointerType((*I)->getType()))
4369 Constructor += Name + "((struct __block_impl *)_"
4370 + Name + "->__forwarding)";
4371 else
4372 Constructor += Name + "(_" + Name + "->__forwarding)";
4373 }
4374
4375 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004376 if (GlobalVarDecl)
4377 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4378 else
4379 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004380 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004381
Steve Naroff30484702009-12-06 21:14:13 +00004382 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004383 } else {
4384 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004385 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004386 if (GlobalVarDecl)
4387 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4388 else
4389 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004390 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4391 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004392 }
4393 Constructor += " ";
4394 Constructor += "}\n";
4395 S += Constructor;
4396 S += "};\n";
4397 return S;
4398}
4399
Steve Naroff30484702009-12-06 21:14:13 +00004400std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4401 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004402 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004403 unsigned hasCopy) {
4404 std::string S = "\nstatic struct " + DescTag;
4405
4406 S += " {\n unsigned long reserved;\n";
4407 S += " unsigned long Block_size;\n";
4408 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004409 S += " void (*copy)(struct ";
4410 S += ImplTag; S += "*, struct ";
4411 S += ImplTag; S += "*);\n";
4412
4413 S += " void (*dispose)(struct ";
4414 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004415 }
4416 S += "} ";
4417
4418 S += DescTag + "_DATA = { 0, sizeof(struct ";
4419 S += ImplTag + ")";
4420 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004421 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4422 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004423 }
4424 S += "};\n";
4425 return S;
4426}
4427
Steve Naroff677ab3a2008-10-27 17:20:55 +00004428void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004429 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004430 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004431 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004432 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004433 bool RewriteSC = (GlobalVarDecl &&
4434 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004435 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004436 GlobalVarDecl->getType().getCVRQualifiers());
4437 if (RewriteSC) {
4438 std::string SC(" void __");
4439 SC += GlobalVarDecl->getNameAsString();
4440 SC += "() {}";
4441 InsertText(FunLocStart, SC);
4442 }
4443
Steve Naroff677ab3a2008-10-27 17:20:55 +00004444 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004445 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4446 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004447 // Need to copy-in the inner copied-in variables not actually used in this
4448 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004449 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4450 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4451 ValueDecl *VD = Exp->getDecl();
4452 BlockDeclRefs.push_back(Exp);
4453 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4454 BlockByCopyDeclsPtrSet.insert(VD);
4455 BlockByCopyDecls.push_back(VD);
4456 }
4457 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4458 BlockByRefDeclsPtrSet.insert(VD);
4459 BlockByRefDecls.push_back(VD);
4460 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004461 // imported objects in the inner blocks not used in the outer
4462 // blocks must be copied/disposed in the outer block as well.
4463 if (Exp->isByRef() ||
4464 VD->getType()->isObjCObjectPointerType() ||
4465 VD->getType()->isBlockPointerType())
4466 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004467 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004468
Daniel Dunbar56df9772010-08-17 22:39:59 +00004469 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4470 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004471
Steve Naroff30484702009-12-06 21:14:13 +00004472 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004473
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004474 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004475
Steve Naroff30484702009-12-06 21:14:13 +00004476 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004477
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004478 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004479
4480 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004481 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004482 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004483 }
Steve Naroff30484702009-12-06 21:14:13 +00004484 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4485 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004486 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004487
Steve Naroff677ab3a2008-10-27 17:20:55 +00004488 BlockDeclRefs.clear();
4489 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004490 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004491 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004492 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004493 ImportedBlockDecls.clear();
4494 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004495 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004496 // Must insert any 'const/volatile/static here. Since it has been
4497 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004498 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004499 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004500 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004501 if (GlobalVarDecl->getType().isConstQualified())
4502 SC += "const ";
4503 if (GlobalVarDecl->getType().isVolatileQualified())
4504 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004505 if (GlobalVarDecl->getType().isRestrictQualified())
4506 SC += "restrict ";
4507 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004508 }
4509
Steve Naroff677ab3a2008-10-27 17:20:55 +00004510 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004511 InnerDeclRefsCount.clear();
4512 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004513 RewrittenBlockExprs.clear();
4514}
4515
4516void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4517 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004518 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004519
Steve Naroff677ab3a2008-10-27 17:20:55 +00004520 SynthesizeBlockLiterals(FunLocStart, FuncName);
4521}
4522
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004523static void BuildUniqueMethodName(std::string &Name,
4524 ObjCMethodDecl *MD) {
4525 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004526 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004527 Name += "__" + MD->getSelector().getAsString();
4528 // Convert colons to underscores.
4529 std::string::size_type loc = 0;
4530 while ((loc = Name.find(":", loc)) != std::string::npos)
4531 Name.replace(loc, 1, "_");
4532}
4533
Steve Naroff677ab3a2008-10-27 17:20:55 +00004534void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004535 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4536 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004537 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004538 std::string FuncName;
4539 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004540 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004541}
4542
4543void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00004544 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00004545 if (*CI) {
4546 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4547 GetBlockDeclRefExprs(CBE->getBody());
4548 else
4549 GetBlockDeclRefExprs(*CI);
4550 }
4551 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004552 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004553 // FIXME: Handle enums.
4554 if (!isa<FunctionDecl>(CDRE->getDecl()))
4555 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004556 }
4557 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4558 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4559 BlockDeclRefExpr *BDRE =
John McCall351762c2011-02-07 10:33:21 +00004560 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4561 DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004562 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004563 BlockDeclRefs.push_back(BDRE);
4564 }
4565
Steve Naroff677ab3a2008-10-27 17:20:55 +00004566 return;
4567}
4568
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004569void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4570 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004571 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00004572 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004573 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004574 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4575 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004576 GetInnerBlockDeclRefExprs(CBE->getBody(),
4577 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004578 InnerContexts);
4579 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004580 else
4581 GetInnerBlockDeclRefExprs(*CI,
4582 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004583 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004584
4585 }
4586 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004587 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004588 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004589 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004590 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004591 }
4592 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4593 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4594 if (Var->isFunctionOrMethodVarDecl())
4595 ImportedLocalExternalDecls.insert(Var);
4596 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004597
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004598 return;
4599}
4600
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004601/// convertFunctionTypeOfBlocks - This routine converts a function type
4602/// whose result type may be a block pointer or whose argument type(s)
4603/// might be block pointers to an equivalent funtion type replacing
4604/// all block pointers to function pointers.
4605QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4606 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4607 // FTP will be null for closures that don't take arguments.
4608 // Generate a funky cast.
4609 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004610 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004611 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004612
4613 if (FTP) {
4614 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4615 E = FTP->arg_type_end(); I && (I != E); ++I) {
4616 QualType t = *I;
4617 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004618 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004619 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004620 ArgTypes.push_back(t);
4621 }
4622 }
4623 QualType FuncType;
4624 // FIXME. Does this work if block takes no argument but has a return type
4625 // which is of block type?
4626 if (HasBlockType)
John McCalldb40c7f2010-12-14 08:05:40 +00004627 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004628 else FuncType = QualType(FT, 0);
4629 return FuncType;
4630}
4631
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004632Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004633 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004634 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004635
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004636 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004637 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004638 } else if (const BlockDeclRefExpr *CDRE =
4639 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004640 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004641 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004642 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004643 }
4644 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4645 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4646 }
4647 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4648 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4649 else if (const ConditionalOperator *CEXPR =
4650 dyn_cast<ConditionalOperator>(BlockExp)) {
4651 Expr *LHSExp = CEXPR->getLHS();
4652 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4653 Expr *RHSExp = CEXPR->getRHS();
4654 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4655 Expr *CONDExp = CEXPR->getCond();
4656 ConditionalOperator *CondExpr =
4657 new (Context) ConditionalOperator(CONDExp,
4658 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004659 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00004660 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004661 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004662 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4663 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004664 } else {
4665 assert(1 && "RewriteBlockClass: Bad type");
4666 }
4667 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004668 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004669 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004670 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004671 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004672
Abramo Bagnara6150c882010-05-11 21:36:43 +00004673 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004674 SourceLocation(),
4675 &Context->Idents.get("__block_impl"));
4676 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004677
Steve Naroff350b6652008-10-30 10:07:53 +00004678 // Generate a funky cast.
4679 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004680
Steve Naroff350b6652008-10-30 10:07:53 +00004681 // Push the block argument type.
4682 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004683 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004684 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004685 E = FTP->arg_type_end(); I && (I != E); ++I) {
4686 QualType t = *I;
4687 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004688 if (!convertBlockPointerToFunctionPointer(t))
4689 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004690 ArgTypes.push_back(t);
4691 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004692 }
Steve Naroff350b6652008-10-30 10:07:53 +00004693 // Now do the pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00004694 QualType PtrToFuncCastType
4695 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump11289f42009-09-09 15:08:12 +00004696
Steve Naroff350b6652008-10-30 10:07:53 +00004697 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004698
John McCall97513962010-01-15 18:39:57 +00004699 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004700 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004701 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004702 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004703 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4704 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004705 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004706
Douglas Gregor91f84212008-12-11 16:49:14 +00004707 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004708 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004709 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004710 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004711 FD->getType(), VK_LValue,
4712 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004713
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004714
John McCall97513962010-01-15 18:39:57 +00004715 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004716 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004717 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004718
Steve Naroff350b6652008-10-30 10:07:53 +00004719 llvm::SmallVector<Expr*, 8> BlkExprs;
4720 // Add the implicit argument.
4721 BlkExprs.push_back(BlkCast);
4722 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004723 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004724 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004725 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004726 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004727 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4728 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004729 Exp->getType(), VK_RValue,
4730 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004731 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004732}
4733
Steve Naroffd9803712009-04-29 16:37:50 +00004734// We need to return the rewritten expression to handle cases where the
4735// BlockDeclRefExpr is embedded in another expression being rewritten.
4736// For example:
4737//
4738// int main() {
4739// __block Foo *f;
4740// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004741//
Steve Naroffd9803712009-04-29 16:37:50 +00004742// void (^myblock)() = ^() {
4743// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4744// i = 77;
4745// };
4746//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004747Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004748 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004749 // for each DeclRefExp where BYREFVAR is name of the variable.
4750 ValueDecl *VD;
4751 bool isArrow = true;
4752 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4753 VD = BDRE->getDecl();
4754 else {
4755 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4756 isArrow = false;
4757 }
4758
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004759 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4760 &Context->Idents.get("__forwarding"),
4761 Context->VoidPtrTy, 0,
4762 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004763 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4764 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004765 FD->getType(), VK_LValue,
4766 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004767
Daniel Dunbar56df9772010-08-17 22:39:59 +00004768 llvm::StringRef Name = VD->getName();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004769 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4770 &Context->Idents.get(Name),
4771 Context->VoidPtrTy, 0,
4772 /*BitWidth=*/0, /*Mutable=*/true);
4773 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004774 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004775
4776
4777
Steve Narofff26a1d42009-02-02 17:19:26 +00004778 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004779 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4780 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004781 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004782 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004783}
4784
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004785// Rewrites the imported local variable V with external storage
4786// (static, extern, etc.) as *V
4787//
4788Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4789 ValueDecl *VD = DRE->getDecl();
4790 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4791 if (!ImportedLocalExternalDecls.count(Var))
4792 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004793 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4794 VK_LValue, OK_Ordinary,
4795 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004796 // Need parens to enforce precedence.
4797 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4798 Exp);
4799 ReplaceStmt(DRE, PE);
4800 return PE;
4801}
4802
Steve Naroffc989a7b2008-11-03 23:29:32 +00004803void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4804 SourceLocation LocStart = CE->getLParenLoc();
4805 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004806
4807 // Need to avoid trying to rewrite synthesized casts.
4808 if (LocStart.isInvalid())
4809 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004810 // Need to avoid trying to rewrite casts contained in macros.
4811 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4812 return;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Steve Naroff677ab3a2008-10-27 17:20:55 +00004814 const char *startBuf = SM->getCharacterData(LocStart);
4815 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004816 QualType QT = CE->getType();
4817 const Type* TypePtr = QT->getAs<Type>();
4818 if (isa<TypeOfExprType>(TypePtr)) {
4819 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4820 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4821 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004822 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004823 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004824 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004825 return;
4826 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004827 // advance the location to startArgList.
4828 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004829
Steve Naroff677ab3a2008-10-27 17:20:55 +00004830 while (*argPtr++ && (argPtr < endBuf)) {
4831 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004832 case '^':
4833 // Replace the '^' with '*'.
4834 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004835 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004836 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 }
4838 }
4839 return;
4840}
4841
4842void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4843 SourceLocation DeclLoc = FD->getLocation();
4844 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004845
Steve Naroff677ab3a2008-10-27 17:20:55 +00004846 // We have 1 or more arguments that have closure pointers.
4847 const char *startBuf = SM->getCharacterData(DeclLoc);
4848 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004849
Steve Naroff677ab3a2008-10-27 17:20:55 +00004850 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Naroff677ab3a2008-10-27 17:20:55 +00004852 parenCount++;
4853 // advance the location to startArgList.
4854 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4855 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004856
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004858
Steve Naroff677ab3a2008-10-27 17:20:55 +00004859 while (*argPtr++ && parenCount) {
4860 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004861 case '^':
4862 // Replace the '^' with '*'.
4863 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004864 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004865 break;
4866 case '(':
4867 parenCount++;
4868 break;
4869 case ')':
4870 parenCount--;
4871 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004872 }
4873 }
4874 return;
4875}
4876
4877bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004878 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004879 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004880 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004881 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004882 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004883 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004884 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004885 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004886 }
4887 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004888 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004889 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004890 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004891 return true;
4892 }
4893 return false;
4894}
4895
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004896bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4897 const FunctionProtoType *FTP;
4898 const PointerType *PT = QT->getAs<PointerType>();
4899 if (PT) {
4900 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4901 } else {
4902 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4903 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4904 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4905 }
4906 if (FTP) {
4907 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004908 E = FTP->arg_type_end(); I != E; ++I) {
4909 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004910 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004911 if ((*I)->isObjCObjectPointerType() &&
4912 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4913 return true;
4914 }
4915
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004916 }
4917 return false;
4918}
4919
Ted Kremenek5a201952009-02-07 01:47:29 +00004920void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4921 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004922 const char *argPtr = strchr(Name, '(');
4923 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004924
Steve Naroff677ab3a2008-10-27 17:20:55 +00004925 LParen = argPtr; // output the start.
4926 argPtr++; // skip past the left paren.
4927 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004928
Steve Naroff677ab3a2008-10-27 17:20:55 +00004929 while (*argPtr && parenCount) {
4930 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004931 case '(': parenCount++; break;
4932 case ')': parenCount--; break;
4933 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004934 }
4935 if (parenCount) argPtr++;
4936 }
4937 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4938 RParen = argPtr; // output the end
4939}
4940
4941void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4942 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4943 RewriteBlockPointerFunctionArgs(FD);
4944 return;
Mike Stump11289f42009-09-09 15:08:12 +00004945 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004946 // Handle Variables and Typedefs.
4947 SourceLocation DeclLoc = ND->getLocation();
4948 QualType DeclT;
4949 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4950 DeclT = VD->getType();
4951 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4952 DeclT = TDD->getUnderlyingType();
4953 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4954 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004955 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004956 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004957
Steve Naroff677ab3a2008-10-27 17:20:55 +00004958 const char *startBuf = SM->getCharacterData(DeclLoc);
4959 const char *endBuf = startBuf;
4960 // scan backward (from the decl location) for the end of the previous decl.
4961 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4962 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004963 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4964 std::string buf;
4965 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004966 // *startBuf != '^' if we are dealing with a pointer to function that
4967 // may take block argument types (which will be handled below).
4968 if (*startBuf == '^') {
4969 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004970 buf = '*';
4971 startBuf++;
4972 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004973 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004974 while (*startBuf != ')') {
4975 buf += *startBuf;
4976 startBuf++;
4977 OrigLength++;
4978 }
4979 buf += ')';
4980 OrigLength++;
4981
4982 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4983 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004984 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004985 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004986 DeclLoc = ND->getLocation();
4987 startBuf = SM->getCharacterData(DeclLoc);
4988 const char *argListBegin, *argListEnd;
4989 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4990 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004991 if (*argListBegin == '^')
4992 buf += '*';
4993 else if (*argListBegin == '<') {
4994 buf += "/*";
4995 buf += *argListBegin++;
4996 OrigLength++;;
4997 while (*argListBegin != '>') {
4998 buf += *argListBegin++;
4999 OrigLength++;
5000 }
5001 buf += *argListBegin;
5002 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005003 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005004 else
5005 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005006 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005007 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005008 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005009 buf += ')';
5010 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005011 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005012 ReplaceText(Start, OrigLength, buf);
5013
Steve Naroff677ab3a2008-10-27 17:20:55 +00005014 return;
5015}
5016
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005017
5018/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5019/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5020/// struct Block_byref_id_object *src) {
5021/// _Block_object_assign (&_dest->object, _src->object,
5022/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5023/// [|BLOCK_FIELD_IS_WEAK]) // object
5024/// _Block_object_assign(&_dest->object, _src->object,
5025/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5026/// [|BLOCK_FIELD_IS_WEAK]) // block
5027/// }
5028/// And:
5029/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5030/// _Block_object_dispose(_src->object,
5031/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5032/// [|BLOCK_FIELD_IS_WEAK]) // object
5033/// _Block_object_dispose(_src->object,
5034/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5035/// [|BLOCK_FIELD_IS_WEAK]) // block
5036/// }
5037
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005038std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5039 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005040 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005041 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005042 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005043 CopyDestroyCache.insert(flag);
5044 S = "static void __Block_byref_id_object_copy_";
5045 S += utostr(flag);
5046 S += "(void *dst, void *src) {\n";
5047
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005048 // offset into the object pointer is computed as:
5049 // void * + void* + int + int + void* + void *
5050 unsigned IntSize =
5051 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5052 unsigned VoidPtrSize =
5053 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5054
5055 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5056 S += " _Block_object_assign((char*)dst + ";
5057 S += utostr(offset);
5058 S += ", *(void * *) ((char*)src + ";
5059 S += utostr(offset);
5060 S += "), ";
5061 S += utostr(flag);
5062 S += ");\n}\n";
5063
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005064 S += "static void __Block_byref_id_object_dispose_";
5065 S += utostr(flag);
5066 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005067 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5068 S += utostr(offset);
5069 S += "), ";
5070 S += utostr(flag);
5071 S += ");\n}\n";
5072 return S;
5073}
5074
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005075/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5076/// the declaration into:
5077/// struct __Block_byref_ND {
5078/// void *__isa; // NULL for everything except __weak pointers
5079/// struct __Block_byref_ND *__forwarding;
5080/// int32_t __flags;
5081/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005082/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5083/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005084/// typex ND;
5085/// };
5086///
5087/// It then replaces declaration of ND variable with:
5088/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5089/// __size=sizeof(struct __Block_byref_ND),
5090/// ND=initializer-if-any};
5091///
5092///
5093void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005094 // Insert declaration for the function in which block literal is
5095 // used.
5096 if (CurFunctionDeclToDeclareForBlock)
5097 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005098 int flag = 0;
5099 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005100 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005101 if (DeclLoc.isInvalid())
5102 // If type location is missing, it is because of missing type (a warning).
5103 // Use variable's location which is good for this case.
5104 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005105 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005106 SourceLocation X = ND->getLocEnd();
5107 X = SM->getInstantiationLoc(X);
5108 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005109 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005110 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005111 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005112 ByrefType += " {\n";
5113 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005114 RewriteByRefString(ByrefType, Name, ND);
5115 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005116 ByrefType += " int __flags;\n";
5117 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005118 // Add void *__Block_byref_id_object_copy;
5119 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005120 QualType Ty = ND->getType();
5121 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5122 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005123 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5124 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005125 }
5126
5127 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005128 ByrefType += " " + Name + ";\n";
5129 ByrefType += "};\n";
5130 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005131 SourceLocation FunLocStart;
5132 if (CurFunctionDef)
5133 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5134 else {
5135 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5136 FunLocStart = CurMethodDef->getLocStart();
5137 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005138 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005139 if (Ty.isObjCGCWeak()) {
5140 flag |= BLOCK_FIELD_IS_WEAK;
5141 isa = 1;
5142 }
5143
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005144 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005145 flag = BLOCK_BYREF_CALLER;
5146 QualType Ty = ND->getType();
5147 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5148 if (Ty->isBlockPointerType())
5149 flag |= BLOCK_FIELD_IS_BLOCK;
5150 else
5151 flag |= BLOCK_FIELD_IS_OBJECT;
5152 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005153 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005154 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005155 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005156
5157 // struct __Block_byref_ND ND =
5158 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5159 // initializer-if-any};
5160 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005161 unsigned flags = 0;
5162 if (HasCopyAndDispose)
5163 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005164 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005165 ByrefType.clear();
5166 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005167 std::string ForwardingCastType("(");
5168 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005169 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005170 ByrefType += " " + Name + " = {(void*)";
5171 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005172 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005173 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005174 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005175 ByrefType += "sizeof(";
5176 RewriteByRefString(ByrefType, Name, ND);
5177 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005178 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005179 ByrefType += ", __Block_byref_id_object_copy_";
5180 ByrefType += utostr(flag);
5181 ByrefType += ", __Block_byref_id_object_dispose_";
5182 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005183 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005184 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005185 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005186 }
5187 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005188 SourceLocation startLoc;
5189 Expr *E = ND->getInit();
5190 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5191 startLoc = ECE->getLParenLoc();
5192 else
5193 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005194 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005195 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005196 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005197 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005198 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005199 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005200 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005201 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005202 ByrefType += "sizeof(";
5203 RewriteByRefString(ByrefType, Name, ND);
5204 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005205 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005206 ByrefType += "__Block_byref_id_object_copy_";
5207 ByrefType += utostr(flag);
5208 ByrefType += ", __Block_byref_id_object_dispose_";
5209 ByrefType += utostr(flag);
5210 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005211 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005212 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005213
5214 // Complete the newly synthesized compound expression by inserting a right
5215 // curly brace before the end of the declaration.
5216 // FIXME: This approach avoids rewriting the initializer expression. It
5217 // also assumes there is only one declarator. For example, the following
5218 // isn't currently supported by this routine (in general):
5219 //
5220 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5221 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005222 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5223 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005224 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5225 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005226 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005227
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005228 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005229 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005230 return;
5231}
5232
Mike Stump11289f42009-09-09 15:08:12 +00005233void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005234 // Add initializers for any closure decl refs.
5235 GetBlockDeclRefExprs(Exp->getBody());
5236 if (BlockDeclRefs.size()) {
5237 // Unique all "by copy" declarations.
5238 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005239 if (!BlockDeclRefs[i]->isByRef()) {
5240 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5241 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5242 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5243 }
5244 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005245 // Unique all "by ref" declarations.
5246 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5247 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005248 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5249 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5250 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5251 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005252 }
5253 // Find any imported blocks...they will need special attention.
5254 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005255 if (BlockDeclRefs[i]->isByRef() ||
5256 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005257 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005258 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005259 }
5260}
5261
Daniel Dunbar56df9772010-08-17 22:39:59 +00005262FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005263 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005264 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005265 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCall8e7d6562010-08-26 03:08:43 +00005266 ID, FType, 0, SC_Extern,
5267 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005268}
5269
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005270Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5271 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00005272 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00005273 Blocks.push_back(Exp);
5274
5275 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005276
5277 // Add inner imported variables now used in current block.
5278 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005279 if (!InnerBlockDeclRefs.empty()) {
5280 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5281 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5282 ValueDecl *VD = Exp->getDecl();
5283 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005284 // We need to save the copied-in variables in nested
5285 // blocks because it is needed at the end for some of the API generations.
5286 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005287 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5288 BlockDeclRefs.push_back(Exp);
5289 BlockByCopyDeclsPtrSet.insert(VD);
5290 BlockByCopyDecls.push_back(VD);
5291 }
5292 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5293 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5294 BlockDeclRefs.push_back(Exp);
5295 BlockByRefDeclsPtrSet.insert(VD);
5296 BlockByRefDecls.push_back(VD);
5297 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005298 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005299 // Find any imported blocks...they will need special attention.
5300 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5301 if (InnerBlockDeclRefs[i]->isByRef() ||
5302 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5303 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5304 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005305 }
5306 InnerDeclRefsCount.push_back(countOfInnerDecls);
5307
Steve Narofff4b992a2008-10-28 20:29:00 +00005308 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005309
Steve Narofff4b992a2008-10-28 20:29:00 +00005310 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005311 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005312 else if (CurMethodDef)
5313 BuildUniqueMethodName(FuncName, CurMethodDef);
5314 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005315 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005316
Steve Narofff4b992a2008-10-28 20:29:00 +00005317 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005318
Steve Narofff4b992a2008-10-28 20:29:00 +00005319 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5320 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005321
Steve Narofff4b992a2008-10-28 20:29:00 +00005322 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005323 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5324 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005325
5326 FunctionDecl *FD;
5327 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005328
Steve Narofff4b992a2008-10-28 20:29:00 +00005329 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005330 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005331 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5332 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005333
Steve Narofff4b992a2008-10-28 20:29:00 +00005334 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005335
Steve Naroffe2514232008-10-29 21:23:59 +00005336 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005337 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005338 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005339 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005340 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005341 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005342 InitExprs.push_back(castExpr);
5343
Steve Naroff30484702009-12-06 21:14:13 +00005344 // Initialize the block descriptor.
5345 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005346
Steve Naroff30484702009-12-06 21:14:13 +00005347 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5348 &Context->Idents.get(DescData.c_str()),
5349 Context->VoidPtrTy, 0,
John McCall8e7d6562010-08-26 03:08:43 +00005350 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005351 UnaryOperator *DescRefExpr =
5352 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5353 Context->VoidPtrTy,
5354 VK_LValue,
5355 SourceLocation()),
5356 UO_AddrOf,
5357 Context->getPointerType(Context->VoidPtrTy),
5358 VK_RValue, OK_Ordinary,
5359 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005360 InitExprs.push_back(DescRefExpr);
5361
Steve Narofff4b992a2008-10-28 20:29:00 +00005362 // Add initializers for any closure decl refs.
5363 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005364 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005365 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005366 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005367 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005368 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005369 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005370 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005371 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5372 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005373 if (HasLocalVariableExternalStorage(*I)) {
5374 QualType QT = (*I)->getType();
5375 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005376 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5377 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005378 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005379 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005380 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005381 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5382 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005383 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005384 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005385 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005386 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005387 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5388 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005389 if (HasLocalVariableExternalStorage(*I)) {
5390 QualType QT = (*I)->getType();
5391 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005392 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5393 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005394 }
5395
Steve Narofff4b992a2008-10-28 20:29:00 +00005396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005398 }
5399 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005400 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005401 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005402 ValueDecl *ND = (*I);
5403 std::string Name(ND->getNameAsString());
5404 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005405 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005406 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5407 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005408 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005409 SourceLocation(), II);
5410 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5411 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5412
Daniel Dunbar56df9772010-08-17 22:39:59 +00005413 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005414 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5415 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00005416 bool isNestedCapturedVar = false;
5417 if (block)
5418 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5419 ce = block->capture_end(); ci != ce; ++ci) {
5420 const VarDecl *variable = ci->getVariable();
5421 if (variable == ND && ci->isNested()) {
5422 assert (ci->isByRef() &&
5423 "SynthBlockInitExpr - captured block variable is not byref");
5424 isNestedCapturedVar = true;
5425 break;
5426 }
5427 }
5428 // captured nested byref variable has its address passed. Do not take
5429 // its address again.
5430 if (!isNestedCapturedVar)
5431 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005432 Context->getPointerType(Exp->getType()),
5433 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005434 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005435 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005436 }
5437 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005438 if (ImportedBlockDecls.size()) {
5439 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5440 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005441 unsigned IntSize =
5442 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005443 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5444 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005445 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005446 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005447 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005448 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005449 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005450 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005451 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005452 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005453 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005454 BlockDeclRefs.clear();
5455 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005456 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005457 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005458 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 ImportedBlockDecls.clear();
5460 return NewRep;
5461}
5462
Fariborz Jahanian74405b02011-02-24 21:29:21 +00005463bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5464 if (const ObjCForCollectionStmt * CS =
5465 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5466 return CS->getElement() == DS;
5467 return false;
5468}
5469
Steve Narofff4b992a2008-10-28 20:29:00 +00005470//===----------------------------------------------------------------------===//
5471// Function Body / Expression rewriting
5472//===----------------------------------------------------------------------===//
5473
Steve Naroff4588d0f2008-12-04 16:24:46 +00005474// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5475// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5476// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5477// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5478// Since the rewriter isn't capable of rewriting rewritten code, it's important
5479// we get this right.
5480void RewriteObjC::CollectPropertySetters(Stmt *S) {
5481 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00005482 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff4588d0f2008-12-04 16:24:46 +00005483 if (*CI)
5484 CollectPropertySetters(*CI);
5485
5486 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5487 if (BinOp->isAssignmentOp()) {
John McCallb7bd14f2010-12-02 01:19:52 +00005488 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5489 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005490 }
5491 }
5492}
5493
Steve Narofff4b992a2008-10-28 20:29:00 +00005494Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005495 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005496 isa<DoStmt>(S) || isa<ForStmt>(S))
5497 Stmts.push_back(S);
5498 else if (isa<ObjCForCollectionStmt>(S)) {
5499 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005500 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005501 }
Mike Stump11289f42009-09-09 15:08:12 +00005502
Steve Narofff4b992a2008-10-28 20:29:00 +00005503 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005504
Steve Narofff4b992a2008-10-28 20:29:00 +00005505 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00005506 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00005507 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005508 Stmt *newStmt;
5509 Stmt *S = (*CI);
5510 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5511 Expr *OldBase = IvarRefExpr->getBase();
5512 bool replaced = false;
5513 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5514 if (replaced) {
5515 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5516 ReplaceStmt(OldBase, IRE->getBase());
5517 else
5518 ReplaceStmt(S, newStmt);
5519 }
5520 }
5521 else
5522 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005523 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005524 *CI = newStmt;
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005525 // If dealing with an assignment with LHS being a property reference
5526 // expression, the entire assignment tree is rewritten into a property
5527 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5528 // RHS again.
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005529 if (Expr *Exp = dyn_cast<Expr>(S))
John McCallb7bd14f2010-12-02 01:19:52 +00005530 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005531 if (PropSetters[Exp]) {
5532 ++CI;
5533 continue;
5534 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005535 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537
Steve Narofff4b992a2008-10-28 20:29:00 +00005538 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005539 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005540 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5541 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005542 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005543 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005544 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005545 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005546 Stmt *SaveCurrentBody = CurrentBody;
5547 CurrentBody = BE->getBody();
5548 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005549 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005550 CurrentBody = SaveCurrentBody;
5551 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005552 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005553 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005554 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005555 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005556
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005557 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5558
Steve Narofff4b992a2008-10-28 20:29:00 +00005559 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005560 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005561 return blockTranscribed;
5562 }
5563 // Handle specific things.
5564 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5565 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005566
John McCallb7bd14f2010-12-02 01:19:52 +00005567 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005568 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5569 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5570
5571 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005572 if (BinOp) {
5573 // Because the rewriter doesn't allow us to rewrite rewritten code,
5574 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005575 DisableReplaceStmt = true;
5576 // Save the source range. Even if we disable the replacement, the
5577 // rewritten node will have been inserted into the tree. If the synthesized
5578 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005579 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005580 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5581 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005582 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005583 // Need to rewrite the ivar access expression if need be.
5584 if (isa<ObjCIvarRefExpr>(newStmt)) {
5585 bool replaced = false;
5586 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5587 }
5588
Steve Naroff08628db2008-12-09 12:56:34 +00005589 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005590 //
5591 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5592 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5593 // to see the original expression). Consider this example:
5594 //
5595 // Foo *obj1, *obj2;
5596 //
5597 // obj1.i = [obj2 rrrr];
5598 //
5599 // 'BinOp' for the previous expression looks like:
5600 //
5601 // (BinaryOperator 0x231ccf0 'int' '='
5602 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5603 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5604 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5605 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5606 //
5607 // 'newStmt' represents the rewritten message expression. For example:
5608 //
5609 // (CallExpr 0x231d300 'id':'struct objc_object *'
5610 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5611 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5612 // (CStyleCastExpr 0x231d220 'void *'
5613 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5614 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005615 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005616 // can be used as the setter argument. ReplaceStmt() will still 'see'
5617 // the original RHS (since we haven't altered BinOp).
5618 //
Mike Stump11289f42009-09-09 15:08:12 +00005619 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005620 // node. As a result, we now leak the original AST nodes.
5621 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005622 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005623 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005624 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005625 }
5626 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005627
Steve Narofff4b992a2008-10-28 20:29:00 +00005628 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5629 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005630
Steve Narofff4b992a2008-10-28 20:29:00 +00005631 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5632 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005633
Steve Narofff4b992a2008-10-28 20:29:00 +00005634 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005635#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005636 // Before we rewrite it, put the original message expression in a comment.
5637 SourceLocation startLoc = MessExpr->getLocStart();
5638 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005639
Steve Narofff4b992a2008-10-28 20:29:00 +00005640 const char *startBuf = SM->getCharacterData(startLoc);
5641 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005642
Steve Narofff4b992a2008-10-28 20:29:00 +00005643 std::string messString;
5644 messString += "// ";
5645 messString.append(startBuf, endBuf-startBuf+1);
5646 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005647
5648 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005649 // InsertText(clang::SourceLocation, char const*, unsigned int).
5650 // InsertText(startLoc, messString.c_str(), messString.size());
5651 // Tried this, but it didn't work either...
5652 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005653#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005654 return RewriteMessageExpr(MessExpr);
5655 }
Mike Stump11289f42009-09-09 15:08:12 +00005656
Steve Narofff4b992a2008-10-28 20:29:00 +00005657 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5658 return RewriteObjCTryStmt(StmtTry);
5659
5660 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5661 return RewriteObjCSynchronizedStmt(StmtTry);
5662
5663 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5664 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005665
Steve Narofff4b992a2008-10-28 20:29:00 +00005666 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5667 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005668
5669 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005670 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005671 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005672 OrigStmtRange.getEnd());
5673 if (BreakStmt *StmtBreakStmt =
5674 dyn_cast<BreakStmt>(S))
5675 return RewriteBreakStmt(StmtBreakStmt);
5676 if (ContinueStmt *StmtContinueStmt =
5677 dyn_cast<ContinueStmt>(S))
5678 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005679
5680 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 // and cast exprs.
5682 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5683 // FIXME: What we're doing here is modifying the type-specifier that
5684 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005685 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005686 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5687 // the context of an ObjCForCollectionStmt. For example:
5688 // NSArray *someArray;
5689 // for (id <FooProtocol> index in someArray) ;
5690 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5691 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00005692 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005693 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005694
Steve Narofff4b992a2008-10-28 20:29:00 +00005695 // Blocks rewrite rules.
5696 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5697 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005698 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005699 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005700 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005701 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005702 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005703 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005704 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005705 if (VD->hasAttr<BlocksAttr>()) {
5706 static unsigned uniqueByrefDeclCount = 0;
5707 assert(!BlockByRefDeclNo.count(ND) &&
5708 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5709 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005710 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005711 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005712 else
5713 RewriteTypeOfDecl(VD);
5714 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005715 }
5716 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005717 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005718 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005719 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005720 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5721 }
5722 }
5723 }
Mike Stump11289f42009-09-09 15:08:12 +00005724
Steve Narofff4b992a2008-10-28 20:29:00 +00005725 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5726 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005727
5728 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005729 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5730 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005731 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5732 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005733 && "Statement stack mismatch");
5734 Stmts.pop_back();
5735 }
5736 // Handle blocks rewriting.
5737 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5738 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005739 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005740 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005741 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5742 ValueDecl *VD = DRE->getDecl();
5743 if (VD->hasAttr<BlocksAttr>())
5744 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005745 if (HasLocalVariableExternalStorage(VD))
5746 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005747 }
5748
Steve Narofff4b992a2008-10-28 20:29:00 +00005749 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005750 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005751 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005752 ReplaceStmt(S, BlockCall);
5753 return BlockCall;
5754 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005755 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005756 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005757 RewriteCastExpr(CE);
5758 }
5759#if 0
5760 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005761 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5762 ICE->getSubExpr(),
5763 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005764 // Get the new text.
5765 std::string SStr;
5766 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005767 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005768 const std::string &Str = Buf.str();
5769
5770 printf("CAST = %s\n", &Str[0]);
5771 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5772 delete S;
5773 return Replacement;
5774 }
5775#endif
5776 // Return this stmt unmodified.
5777 return S;
5778}
5779
Steve Naroffe70a52a2009-12-05 15:55:59 +00005780void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5781 for (RecordDecl::field_iterator i = RD->field_begin(),
5782 e = RD->field_end(); i != e; ++i) {
5783 FieldDecl *FD = *i;
5784 if (isTopLevelBlockPointerType(FD->getType()))
5785 RewriteBlockPointerDecl(FD);
5786 if (FD->getType()->isObjCQualifiedIdType() ||
5787 FD->getType()->isObjCQualifiedInterfaceType())
5788 RewriteObjCQualifiedInterfaceTypes(FD);
5789 }
5790}
5791
Steve Narofff4b992a2008-10-28 20:29:00 +00005792/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5793/// main file of the input.
5794void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5795 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005796 if (FD->isOverloadedOperator())
5797 return;
Mike Stump11289f42009-09-09 15:08:12 +00005798
Steve Narofff4b992a2008-10-28 20:29:00 +00005799 // Since function prototypes don't have ParmDecl's, we check the function
5800 // prototype. This enables us to rewrite function declarations and
5801 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005802 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005803
Sebastian Redla7b98a72009-04-26 20:35:05 +00005804 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005805 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005806 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005807 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005808 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005809 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005810 Body =
5811 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5812 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005813 CurrentBody = 0;
5814 if (PropParentMap) {
5815 delete PropParentMap;
5816 PropParentMap = 0;
5817 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005818 // This synthesizes and inserts the block "impl" struct, invoke function,
5819 // and any copy/dispose helper functions.
5820 InsertBlockLiteralsWithinFunction(FD);
5821 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005822 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005823 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005824 return;
5825 }
5826 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005827 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005828 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005829 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005830 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005831 Body =
5832 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5833 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005834 CurrentBody = 0;
5835 if (PropParentMap) {
5836 delete PropParentMap;
5837 PropParentMap = 0;
5838 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005839 InsertBlockLiteralsWithinMethod(MD);
5840 CurMethodDef = 0;
5841 }
5842 }
5843 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5844 ClassImplementation.push_back(CI);
5845 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5846 CategoryImplementation.push_back(CI);
5847 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5848 RewriteForwardClassDecl(CD);
5849 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5850 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005851 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005852 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005853 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005854 CheckFunctionPointerDecl(VD->getType(), VD);
5855 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005856 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005857 RewriteCastExpr(CE);
5858 }
5859 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005860 } else if (VD->getType()->isRecordType()) {
5861 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5862 if (RD->isDefinition())
5863 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005864 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005865 if (VD->getInit()) {
5866 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005867 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005868 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005869 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005870 CurrentBody = 0;
5871 if (PropParentMap) {
5872 delete PropParentMap;
5873 PropParentMap = 0;
5874 }
Mike Stump11289f42009-09-09 15:08:12 +00005875 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005876 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005877 GlobalVarDecl = 0;
5878
5879 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005880 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005881 RewriteCastExpr(CE);
5882 }
5883 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005884 return;
5885 }
5886 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005887 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005888 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005889 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005890 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5891 return;
5892 }
5893 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005894 if (RD->isDefinition())
5895 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005896 return;
5897 }
5898 // Nothing yet.
5899}
5900
Chris Lattnercf169832009-03-28 04:11:33 +00005901void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005902 if (Diags.hasErrorOccurred())
5903 return;
Mike Stump11289f42009-09-09 15:08:12 +00005904
Steve Narofff4b992a2008-10-28 20:29:00 +00005905 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005906
Steve Naroffd9803712009-04-29 16:37:50 +00005907 // Here's a great place to add any extra declarations that may be needed.
5908 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005909 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005910 E = ProtocolExprDecls.end(); I != E; ++I)
5911 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5912
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005913 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005914 if (ClassImplementation.size() || CategoryImplementation.size())
5915 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005916
Steve Narofff4b992a2008-10-28 20:29:00 +00005917 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5918 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005919 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005920 Rewrite.getRewriteBufferFor(MainFileID)) {
5921 //printf("Changed:\n");
5922 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5923 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005924 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005925 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005926
Steve Naroffd9803712009-04-29 16:37:50 +00005927 if (ClassImplementation.size() || CategoryImplementation.size() ||
5928 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005929 // Rewrite Objective-c meta data*
5930 std::string ResultStr;
5931 SynthesizeMetaDataIntoBuffer(ResultStr);
5932 // Emit metadata.
5933 *OutFile << ResultStr;
5934 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005935 OutFile->flush();
5936}