blob: 45c707fe29f203e508e03541a5fd1c6daa7bef43 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarc1b17292010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000239
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner9cc55f52008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattner3c799d72007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000278 bool isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000279 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000280 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000281 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000282 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattner3c799d72007-10-24 17:06:59 +0000284 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000285 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000286 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000287
Steve Naroff1042ff32008-12-08 16:43:47 +0000288 Stmt *CurrentBody;
289 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000290
Chris Lattner69534692007-10-24 16:57:36 +0000291 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000292 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
293 bool &replaced);
294 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000295 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000296 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000297 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000298 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000299 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000300 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000301 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000302 void WarnAboutReturnGotoStmts(Stmt *S);
303 void HasReturnStmts(Stmt *S, bool &hasReturns);
304 void RewriteTryReturnStmts(Stmt *S);
305 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000306 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000307 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000308 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
309 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000313 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000314 Expr **args, unsigned nargs,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
317 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
318 SourceLocation StartLoc=SourceLocation(),
319 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000320 Stmt *RewriteBreakStmt(BreakStmt *S);
321 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000322 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000324 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000325 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000326 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000327 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000328 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000329 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000330 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000331 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000332 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000333 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000334
Chris Lattner3c799d72007-10-24 17:06:59 +0000335 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000336 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000339 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000340 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000342 template<typename MethodIterator>
343 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
344 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000345 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000346 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000347 const char *ClassName,
348 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Steve Naroffd9803712009-04-29 16:37:50 +0000350 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
351 const char *prefix,
352 const char *ClassName,
353 std::string &Result);
354 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000355 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000356 const char *ClassName,
357 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000358 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000359 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000360 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000361 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000362 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000363 void RewriteImplementations();
364 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000365
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000367 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000369
Steve Naroff677ab3a2008-10-27 17:20:55 +0000370 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
371 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000372
373 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000374 void RewriteBlockCall(CallExpr *Exp);
375 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000376 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000377 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000378 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000379 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000380 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000381
382 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000384 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000386 std::string SynthesizeBlockImpl(BlockExpr *CE,
387 std::string Tag, std::string Desc);
388 std::string SynthesizeBlockDescriptor(std::string DescTag,
389 std::string ImplTag,
390 int i, const char *funcName,
391 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000392 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000393 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000394 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000395 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000398 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000399 void GetInnerBlockDeclRefExprs(Stmt *S,
400 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000401 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 // We avoid calling Type::isBlockPointerType(), since it operates on the
404 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000405 bool isTopLevelBlockPointerType(QualType T) {
406 return isa<BlockPointerType>(T);
407 }
Mike Stump11289f42009-09-09 15:08:12 +0000408
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000409 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
410 /// to a function pointer type and upon success, returns true; false
411 /// otherwise.
412 bool convertBlockPointerToFunctionPointer(QualType &T) {
413 if (isTopLevelBlockPointerType(T)) {
414 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
415 T = Context->getPointerType(BPT->getPointeeType());
416 return true;
417 }
418 return false;
419 }
420
Steve Naroff677ab3a2008-10-27 17:20:55 +0000421 // FIXME: This predicate seems like it would be useful to add to ASTContext.
422 bool isObjCType(QualType T) {
423 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
424 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000425
Steve Naroff677ab3a2008-10-27 17:20:55 +0000426 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000427
Steve Naroff677ab3a2008-10-27 17:20:55 +0000428 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
429 OCT == Context->getCanonicalType(Context->getObjCClassType()))
430 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000431
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000432 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000433 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000434 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000435 return true;
436 }
437 return false;
438 }
439 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000440 void GetExtentOfArgList(const char *Name, const char *&LParen,
441 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000442 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000443
Steve Narofff4b992a2008-10-28 20:29:00 +0000444 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000445 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
446 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000447
Steve Naroffd9803712009-04-29 16:37:50 +0000448 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000449 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000450 if (From[i] == '"')
451 To += "\\\"";
452 else
453 To += From[i];
454 }
455 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000456 };
John McCall97513962010-01-15 18:39:57 +0000457
458 // Helper function: create a CStyleCastExpr with trivial type source info.
459 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
460 CastExpr::CastKind Kind, Expr *E) {
461 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallcf142162010-08-07 06:22:56 +0000462 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
463 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000464 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000465}
466
Mike Stump11289f42009-09-09 15:08:12 +0000467void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
468 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000469 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000470 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000471 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000472 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000473 // All the args are checked/rewritten. Don't call twice!
474 RewriteBlockPointerDecl(D);
475 break;
476 }
477 }
478}
479
480void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000481 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000482 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000483 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000484}
485
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000486static bool IsHeaderFile(const std::string &Filename) {
487 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000488
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000489 if (DotPos == std::string::npos) {
490 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000491 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000492 }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000494 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
495 // C header: .h
496 // C++ header: .hh or .H;
497 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000498}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000499
Eli Friedman94cf21e2009-05-18 22:20:00 +0000500RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000501 Diagnostic &D, const LangOptions &LOpts,
502 bool silenceMacroWarn)
503 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
504 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000505 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000506 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000507 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000508 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000509 "rewriter doesn't support user-specified control flow semantics "
510 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000511}
512
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000513ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
514 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000515 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000516 const LangOptions &LOpts,
517 bool SilenceRewriteMacroWarning) {
518 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000519}
Chris Lattnere99c8322007-10-11 00:43:27 +0000520
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000521void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000522 Context = &context;
523 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000524 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000525 MsgSendFunctionDecl = 0;
526 MsgSendSuperFunctionDecl = 0;
527 MsgSendStretFunctionDecl = 0;
528 MsgSendSuperStretFunctionDecl = 0;
529 MsgSendFpretFunctionDecl = 0;
530 GetClassFunctionDecl = 0;
531 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000532 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000533 SelGetUidFunctionDecl = 0;
534 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000535 ConstantStringClassReference = 0;
536 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000537 CurMethodDef = 0;
538 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000539 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000540 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000541 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000542 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000543 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000544 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000545 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000546 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000547 PropParentMap = 0;
548 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000549 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000550 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner187f6262008-01-31 19:38:44 +0000552 // Get the ID and start/end of the main file.
553 MainFileID = SM->getMainFileID();
554 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
555 MainFileStart = MainBuf->getBufferStart();
556 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattner184e65d2009-04-14 23:22:57 +0000558 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner187f6262008-01-31 19:38:44 +0000560 // declaring objc_selector outside the parameter list removes a silly
561 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000562 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000563 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000565 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000566 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000567 if (LangOpts.Microsoft) {
568 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000569 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
570 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000572 }
Steve Naroff00a31762008-03-27 22:29:16 +0000573 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
575 Preamble += "typedef struct objc_object Protocol;\n";
576 Preamble += "#define _REWRITER_typedef_Protocol\n";
577 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000578 if (LangOpts.Microsoft) {
579 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
580 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
581 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000582 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000584 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000586 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000588 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000589 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000590 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
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_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000594 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
596 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000598 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
601 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
603 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000604 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000605 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
607 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000609 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
610 Preamble += "struct __objcFastEnumerationState {\n\t";
611 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000612 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000613 Preamble += "unsigned long *mutationsPtr;\n\t";
614 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000616 Preamble += "#define __FASTENUMERATIONSTATE\n";
617 Preamble += "#endif\n";
618 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
619 Preamble += "struct __NSConstantStringImpl {\n";
620 Preamble += " int *isa;\n";
621 Preamble += " int flags;\n";
622 Preamble += " char *str;\n";
623 Preamble += " long length;\n";
624 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000625 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
626 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
627 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000628 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000629 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000630 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
631 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000632 // Blocks preamble.
633 Preamble += "#ifndef BLOCK_IMPL\n";
634 Preamble += "#define BLOCK_IMPL\n";
635 Preamble += "struct __block_impl {\n";
636 Preamble += " void *isa;\n";
637 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000638 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000639 Preamble += " void *FuncPtr;\n";
640 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000641 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000642 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000643 Preamble += "extern \"C\" __declspec(dllexport) "
644 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000645 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
646 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
647 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
648 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000649 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
650 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000651 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
652 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
653 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000654 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000655 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000656 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
657 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000658 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000659 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000660 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000661 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000662 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000663 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000664 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000665 Preamble += "#define __weak\n";
666 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000667 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
668 // as this avoids warning in any 64bit/32bit compilation model.
669 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000670}
671
672
Chris Lattner3c799d72007-10-24 17:06:59 +0000673//===----------------------------------------------------------------------===//
674// Top Level Driver Code
675//===----------------------------------------------------------------------===//
676
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000677void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000678 if (Diags.hasErrorOccurred())
679 return;
680
Chris Lattner0bd1c972007-10-16 21:07:07 +0000681 // Two cases: either the decl could be in the main file, or it could be in a
682 // #included file. If the former, rewrite it now. If the later, check to see
683 // if we rewrote the #include/#import.
684 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000685 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattner0bd1c972007-10-16 21:07:07 +0000687 // If this is for a builtin, ignore it.
688 if (Loc.isInvalid()) return;
689
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000690 // Look for built-in declarations that we need to refer during the rewrite.
691 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000692 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000693 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000694 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000695 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000696 ConstantStringClassReference = FVD;
697 return;
698 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000699 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000700 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000701 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000702 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000703 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000704 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000705 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000706 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000707 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000708 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
709 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000710 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
711 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000712 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000713 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000714 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000716 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000717 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000718}
719
Chris Lattner3c799d72007-10-24 17:06:59 +0000720//===----------------------------------------------------------------------===//
721// Syntactic (non-AST) Rewriting Code
722//===----------------------------------------------------------------------===//
723
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000724void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000725 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000726 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
727 const char *MainBufStart = MainBuf.begin();
728 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000729 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000730
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000731 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000732 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
733 if (*BufPtr == '#') {
734 if (++BufPtr == MainBufEnd)
735 return;
736 while (*BufPtr == ' ' || *BufPtr == '\t')
737 if (++BufPtr == MainBufEnd)
738 return;
739 if (!strncmp(BufPtr, "import", ImportLen)) {
740 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000741 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000742 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000743 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000744 BufPtr += ImportLen;
745 }
746 }
747 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000748}
749
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000750void RewriteObjC::RewriteTabs() {
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000751 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
752 const char *MainBufStart = MainBuf.begin();
753 const char *MainBufEnd = MainBuf.end();
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattner3c799d72007-10-24 17:06:59 +0000755 // Loop over the whole file, looking for tabs.
756 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
757 if (*BufPtr != '\t')
758 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000759
Chris Lattner3c799d72007-10-24 17:06:59 +0000760 // Okay, we found a tab. This tab will turn into at least one character,
761 // but it depends on which 'virtual column' it is in. Compute that now.
762 unsigned VCol = 0;
763 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
764 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
765 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattner3c799d72007-10-24 17:06:59 +0000767 // Okay, now that we know the virtual column, we know how many spaces to
768 // insert. We assume 8-character tab-stops.
769 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattner3c799d72007-10-24 17:06:59 +0000771 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000772 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
773 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattner3c799d72007-10-24 17:06:59 +0000775 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000776 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000777 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000778}
779
Steve Naroff9af94912008-12-02 15:48:25 +0000780static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
781 ObjCIvarDecl *OID) {
782 std::string S;
783 S = "((struct ";
784 S += ClassDecl->getIdentifier()->getName();
785 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000786 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000787 return S;
788}
789
Steve Naroffc038b3a2008-12-02 17:36:43 +0000790void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
791 ObjCImplementationDecl *IMD,
792 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000793 static bool objcGetPropertyDefined = false;
794 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000795 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000796 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000797 const char *startBuf = SM->getCharacterData(startLoc);
798 assert((*startBuf == '@') && "bogus @synthesize location");
799 const char *semiBuf = strchr(startBuf, ';');
800 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000801 SourceLocation onePastSemiLoc =
802 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000803
804 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
805 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000806
Steve Naroff9af94912008-12-02 15:48:25 +0000807 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000808 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000809 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000810 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000811
Steve Naroff003d00e2008-12-02 16:05:55 +0000812 if (!OID)
813 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000814 unsigned Attributes = PD->getPropertyAttributes();
815 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
816 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
817 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000818 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000819 if (GenGetProperty && !objcGetPropertyDefined) {
820 objcGetPropertyDefined = true;
821 // FIXME. Is this attribute correct in all cases?
822 Getr = "\nextern \"C\" __declspec(dllimport) "
823 "id objc_getProperty(id, SEL, long, bool);\n";
824 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000825 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
826 Getr += "{ ";
827 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000828 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000829 if (GenGetProperty) {
830 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
831 Getr += "typedef ";
832 const FunctionType *FPRetType = 0;
833 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
834 FPRetType);
835 Getr += " _TYPE";
836 if (FPRetType) {
837 Getr += ")"; // close the precedence "scope" for "*".
838
839 // Now, emit the argument types (if any).
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000840 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000841 Getr += "(";
842 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
843 if (i) Getr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000844 std::string ParamStr = FT->getArgType(i).getAsString(
845 Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000846 Getr += ParamStr;
847 }
848 if (FT->isVariadic()) {
849 if (FT->getNumArgs()) Getr += ", ";
850 Getr += "...";
851 }
852 Getr += ")";
853 } else
854 Getr += "()";
855 }
856 Getr += ";\n";
857 Getr += "return (_TYPE)";
858 Getr += "objc_getProperty(self, _cmd, ";
859 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
860 Getr += ", 1)";
861 }
862 else
863 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000864 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000865 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000866 if (PD->isReadOnly())
867 return;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Steve Naroff9af94912008-12-02 15:48:25 +0000869 // Generate the 'setter' function.
870 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000871 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
872 ObjCPropertyDecl::OBJC_PR_copy);
873 if (GenSetProperty && !objcSetPropertyDefined) {
874 objcSetPropertyDefined = true;
875 // FIXME. Is this attribute correct in all cases?
876 Setr = "\nextern \"C\" __declspec(dllimport) "
877 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
878 }
879
Steve Naroff9af94912008-12-02 15:48:25 +0000880 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000881 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000882 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000883 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000884 if (GenSetProperty) {
885 Setr += "objc_setProperty (self, _cmd, ";
886 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
887 Setr += ", (id)";
888 Setr += PD->getNameAsCString();
889 Setr += ", ";
890 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
891 Setr += "0, ";
892 else
893 Setr += "1, ";
894 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
895 Setr += "1)";
896 else
897 Setr += "0)";
898 }
899 else {
900 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
901 Setr += PD->getNameAsCString();
902 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000903 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000904 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000905}
Chris Lattner16a0de42007-10-11 18:38:32 +0000906
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000907void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000908 // Get the start location and compute the semi location.
909 SourceLocation startLoc = ClassDecl->getLocation();
910 const char *startBuf = SM->getCharacterData(startLoc);
911 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner3c799d72007-10-24 17:06:59 +0000913 // Translate to typedef's that forward reference structs with the same name
914 // as the class. As a convenience, we include the original declaration
915 // as a comment.
916 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000917 typedefString += "// @class ";
918 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
919 I != E; ++I) {
920 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
921 typedefString += ForwardDecl->getNameAsString();
922 if (I+1 != E)
923 typedefString += ", ";
924 else
925 typedefString += ";\n";
926 }
927
Chris Lattner9ee23b72009-02-20 18:04:31 +0000928 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
929 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000930 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000931 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000932 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000933 typedefString += "\n";
934 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000935 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000936 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000937 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000938 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000939 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941
Steve Naroff574440f2007-10-24 22:48:43 +0000942 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000943 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000944}
945
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000946void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000947 // When method is a synthesized one, such as a getter/setter there is
948 // nothing to rewrite.
949 if (Method->isSynthesized())
950 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000951 SourceLocation LocStart = Method->getLocStart();
952 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chris Lattner88ea93e2009-02-04 01:06:56 +0000954 if (SM->getInstantiationLineNumber(LocEnd) >
955 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000956 InsertText(LocStart, "#if 0\n");
957 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000959 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000960 }
961}
962
Mike Stump11289f42009-09-09 15:08:12 +0000963void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000964 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000965
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000966 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000967 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000968}
969
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000970void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000971 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Steve Naroff5448cf62007-10-30 13:30:57 +0000973 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000974 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000975
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000976 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
977 E = CatDecl->prop_end(); I != E; ++I)
978 RewriteProperty(*I);
979
Mike Stump11289f42009-09-09 15:08:12 +0000980 for (ObjCCategoryDecl::instmeth_iterator
981 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000982 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000983 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000984 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000985 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000986 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000987 RewriteMethodDeclaration(*I);
988
Steve Naroff5448cf62007-10-30 13:30:57 +0000989 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000990 ReplaceText(CatDecl->getAtEndRange().getBegin(),
991 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000992}
993
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000994void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000995 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000996
Steve Narofff921385f2007-10-30 16:42:30 +0000997 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000999
1000 for (ObjCProtocolDecl::instmeth_iterator
1001 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001002 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001003 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001004 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001005 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001006 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001007 RewriteMethodDeclaration(*I);
1008
Steve Narofff921385f2007-10-30 16:42:30 +00001009 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001010 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001011 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001012
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001013 // Must comment out @optional/@required
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
1016 for (const char *p = startBuf; p < endBuf; p++) {
1017 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001018 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001019 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001021 }
1022 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001023 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001024 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001025
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001026 }
1027 }
Steve Narofff921385f2007-10-30 16:42:30 +00001028}
1029
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001030void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001031 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001032 if (LocStart.isInvalid())
1033 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001034 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001035 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001036}
1037
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001038void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1039 const FunctionType *&FPRetType) {
1040 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001041 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001042 else if (T->isFunctionPointerType() ||
1043 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001044 // needs special handling, since pointer-to-functions have special
1045 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001046 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001047 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001048 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001049 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001050 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001051 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001052 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001053 ResultStr += FPRetType->getResultType().getAsString(
1054 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001055 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001056 }
1057 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001058 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001059}
1060
1061void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1062 std::string &ResultStr) {
1063 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1064 const FunctionType *FPRetType = 0;
1065 ResultStr += "\nstatic ";
1066 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001067 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001068
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregorffca3a22009-01-09 17:18:27 +00001072 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001073 NameStr += "_I_";
1074 else
1075 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001076
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001077 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001078 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001079
1080 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001081 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001082 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001083 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001086 {
1087 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 int len = selString.size();
1089 for (int i = 0; i < len; i++)
1090 if (selString[i] == ':')
1091 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001092 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001094 // Remember this name for metadata emission
1095 MethodInternalNames[OMD] = NameStr;
1096 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 // Rewrite arguments
1099 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001100
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001101 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001102 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001103 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001104 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001105 if (!LangOpts.Microsoft) {
1106 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1107 ResultStr += "struct ";
1108 }
1109 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001110 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001111 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 }
1113 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001114 ResultStr += Context->getObjCClassType().getAsString(
1115 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001116
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001117 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001118 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001119 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001120
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001121 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001122 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1123 E = OMD->param_end(); PI != E; ++PI) {
1124 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001125 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001126 if (PDecl->getType()->isObjCQualifiedIdType()) {
1127 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001128 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001129 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001130 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001131 QualType QT = PDecl->getType();
1132 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1133 if (convertBlockPointerToFunctionPointer(QT))
1134 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1135 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001136 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001137 ResultStr += Name;
1138 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001139 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001140 if (OMD->isVariadic())
1141 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001142 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001143
Steve Naroffb067bbd2008-07-16 14:40:40 +00001144 if (FPRetType) {
1145 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001146
Steve Naroffb067bbd2008-07-16 14:40:40 +00001147 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001148 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001149 ResultStr += "(";
1150 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1151 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001152 std::string ParamStr = FT->getArgType(i).getAsString(
1153 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001154 ResultStr += ParamStr;
1155 }
1156 if (FT->isVariadic()) {
1157 if (FT->getNumArgs()) ResultStr += ", ";
1158 ResultStr += "...";
1159 }
1160 ResultStr += ")";
1161 } else {
1162 ResultStr += "()";
1163 }
1164 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001165}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001166void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001167 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1168 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001170 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001171
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001172 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001173 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1174 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001175 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001176 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001177 ObjCMethodDecl *OMD = *I;
1178 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001179 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001180 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001181
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001184 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001188 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1189 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001190 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001191 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001192 ObjCMethodDecl *OMD = *I;
1193 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001194 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001195 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001196
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001197 const char *startBuf = SM->getCharacterData(LocStart);
1198 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001199 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001200 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001201 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001202 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001203 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001204 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001205 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001206 }
1207
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001208 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001209}
1210
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001211void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001212 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001213 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001214 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001215 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001216 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001217 ResultStr += "\n";
1218 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001219 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001220 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001221 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001222 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001223 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001224 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001225 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001226 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001227 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001228
1229 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001230 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001231 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001232 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001233 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001234 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001235 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001236 for (ObjCInterfaceDecl::classmeth_iterator
1237 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001238 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001239 RewriteMethodDeclaration(*I);
1240
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001241 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001242 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1243 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001244}
1245
Steve Naroff08628db2008-12-09 12:56:34 +00001246Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1247 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001248 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1249 // This allows us to reuse all the fun and games in SynthMessageExpr().
1250 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1251 ObjCMessageExpr *MsgExpr;
1252 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1253 llvm::SmallVector<Expr *, 1> ExprVec;
1254 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001255
Steve Naroff1042ff32008-12-08 16:43:47 +00001256 Stmt *Receiver = PropRefExpr->getBase();
1257 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1258 if (PRE && PropGetters[PRE]) {
1259 // This allows us to handle chain/nested property getters.
1260 Receiver = PropGetters[PRE];
1261 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001262 if (isa<ObjCSuperExpr>(Receiver))
1263 MsgExpr = ObjCMessageExpr::Create(*Context,
1264 PDecl->getType().getNonReferenceType(),
1265 /*FIXME?*/SourceLocation(),
1266 Receiver->getLocStart(),
1267 /*IsInstanceSuper=*/true,
1268 cast<Expr>(Receiver)->getType(),
1269 PDecl->getSetterName(),
1270 PDecl->getSetterMethodDecl(),
1271 &ExprVec[0], 1,
1272 /*FIXME:*/SourceLocation());
1273 else
1274 MsgExpr = ObjCMessageExpr::Create(*Context,
1275 PDecl->getType().getNonReferenceType(),
1276 /*FIXME: */SourceLocation(),
1277 cast<Expr>(Receiver),
1278 PDecl->getSetterName(),
1279 PDecl->getSetterMethodDecl(),
1280 &ExprVec[0], 1,
1281 /*FIXME:*/SourceLocation());
Steve Naroff4588d0f2008-12-04 16:24:46 +00001282 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001283
Steve Naroff4588d0f2008-12-04 16:24:46 +00001284 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001285 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001286 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001290 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001291}
1292
Steve Naroff4588d0f2008-12-04 16:24:46 +00001293Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1295 // This allows us to reuse all the fun and games in SynthMessageExpr().
1296 ObjCMessageExpr *MsgExpr;
1297 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001298
Steve Naroff1042ff32008-12-08 16:43:47 +00001299 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001300
Steve Naroff1042ff32008-12-08 16:43:47 +00001301 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1302 if (PRE && PropGetters[PRE]) {
1303 // This allows us to handle chain/nested property getters.
1304 Receiver = PropGetters[PRE];
1305 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001306
1307 if (isa<ObjCSuperExpr>(Receiver))
1308 MsgExpr = ObjCMessageExpr::Create(*Context,
1309 PDecl->getType().getNonReferenceType(),
1310 /*FIXME:*/SourceLocation(),
1311 Receiver->getLocStart(),
1312 /*IsInstanceSuper=*/true,
1313 cast<Expr>(Receiver)->getType(),
1314 PDecl->getGetterName(),
1315 PDecl->getGetterMethodDecl(),
1316 0, 0,
1317 /*FIXME:*/SourceLocation());
1318 else
1319 MsgExpr = ObjCMessageExpr::Create(*Context,
1320 PDecl->getType().getNonReferenceType(),
1321 /*FIXME:*/SourceLocation(),
1322 cast<Expr>(Receiver),
1323 PDecl->getGetterName(),
1324 PDecl->getGetterMethodDecl(),
1325 0, 0,
1326 /*FIXME:*/SourceLocation());
Steve Narofff326f402008-12-03 00:56:33 +00001327
Steve Naroff22216db2008-12-04 23:50:32 +00001328 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001329
1330 if (!PropParentMap)
1331 PropParentMap = new ParentMap(CurrentBody);
1332
1333 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1334 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1335 // We stash away the ReplacingStmt since actually doing the
1336 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1337 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001338 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1339 // to things that stay around.
1340 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001341 return PropRefExpr; // return the original...
1342 } else {
1343 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001344 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001345 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1346 // to things that stay around.
1347 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001348 return ReplacingStmt;
1349 }
Steve Narofff326f402008-12-03 00:56:33 +00001350}
1351
Mike Stump11289f42009-09-09 15:08:12 +00001352Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001353 SourceLocation OrigStart,
1354 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001355 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001356 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001357 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001358 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001359 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001360 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001361 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001362 // lookup which class implements the instance variable.
1363 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001365 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001366 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001367
Steve Naroffb1c02372008-05-08 17:52:16 +00001368 // Synthesize an explicit cast to gain access to the ivar.
1369 std::string RecName = clsDeclared->getIdentifier()->getName();
1370 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001371 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001372 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001373 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001374 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1375 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001376 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1377 CastExpr::CK_Unknown,
1378 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001379 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001380 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1381 IV->getBase()->getLocEnd(),
1382 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001383 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001384 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001385 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001386 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1387 IV->getLocation(),
1388 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001389 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001390 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001391 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001392 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001393 // Cannot delete IV->getBase(), since PE points to it.
1394 // Replace the old base with the cast. This is important when doing
1395 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001396 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001397 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001398 }
Steve Naroff24840f62008-04-18 21:55:08 +00001399 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001400 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001401
Steve Naroff29ce4e52008-05-06 23:20:07 +00001402 // Explicit ivar refs need to have a cast inserted.
1403 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001404 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001405 ObjCInterfaceType *iFaceDecl =
1406 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001407 // lookup which class implements the instance variable.
1408 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001409 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001410 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001411 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001412
Steve Naroff29ce4e52008-05-06 23:20:07 +00001413 // Synthesize an explicit cast to gain access to the ivar.
1414 std::string RecName = clsDeclared->getIdentifier()->getName();
1415 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001416 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001417 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001418 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001419 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1420 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001421 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1422 CastExpr::CK_Unknown,
1423 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001424 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001425 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001426 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001427 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001428 // Cannot delete IV->getBase(), since PE points to it.
1429 // Replace the old base with the cast. This is important when doing
1430 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001431 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001432 return IV;
1433 }
Steve Naroff05caa482007-11-15 11:33:00 +00001434 }
Steve Naroff24840f62008-04-18 21:55:08 +00001435 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001436}
1437
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001438Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1439 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1440 CI != E; ++CI) {
1441 if (*CI) {
1442 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1443 if (newStmt)
1444 *CI = newStmt;
1445 }
1446 }
1447 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1448 SourceRange OrigStmtRange = S->getSourceRange();
1449 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1450 replaced);
1451 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001452 }
1453 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1454 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1455 return newStmt;
1456 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001457 return S;
1458}
1459
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001460/// SynthCountByEnumWithState - To print:
1461/// ((unsigned int (*)
1462/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001463/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001465/// "countByEnumeratingWithState:objects:count:"),
1466/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467/// (id *)items, (unsigned int)16)
1468///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001469void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001470 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1471 "id *, unsigned int))(void *)objc_msgSend)";
1472 buf += "\n\t\t";
1473 buf += "((id)l_collection,\n\t\t";
1474 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1475 buf += "\n\t\t";
1476 buf += "&enumState, "
1477 "(id *)items, (unsigned int)16)";
1478}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001479
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001480/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1481/// statement to exit to its outer synthesized loop.
1482///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001483Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1485 return S;
1486 // replace break with goto __break_label
1487 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001488
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001489 SourceLocation startLoc = S->getLocStart();
1490 buf = "goto __break_label_";
1491 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001492 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001493
1494 return 0;
1495}
1496
1497/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1498/// statement to continue with its inner synthesized loop.
1499///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001500Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001501 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1502 return S;
1503 // replace continue with goto __continue_label
1504 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001506 SourceLocation startLoc = S->getLocStart();
1507 buf = "goto __continue_label_";
1508 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001509 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001510
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001511 return 0;
1512}
1513
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001514/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001515/// It rewrites:
1516/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001518/// Into:
1519/// {
Mike Stump11289f42009-09-09 15:08:12 +00001520/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001521/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001522/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001523/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001524/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001525/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001526/// if (limit) {
1527/// unsigned long startMutations = *enumState.mutationsPtr;
1528/// do {
1529/// unsigned long counter = 0;
1530/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001531/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001532/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001533/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001534/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001535/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001536/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001537/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001538/// objects:items count:16]);
1539/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001540/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001541/// }
1542/// else
1543/// elem = nil;
1544/// }
1545///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001546Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001547 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001548 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001549 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001550 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001551 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001552 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001553
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001555 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001557 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001558 std::string buf;
1559 buf = "\n{\n\t";
1560 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1561 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001562 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001563 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001564 if (ElementType->isObjCQualifiedIdType() ||
1565 ElementType->isObjCQualifiedInterfaceType())
1566 // Simply use 'id' for all qualified types.
1567 elementTypeAsString = "id";
1568 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001569 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001570 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001571 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001572 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001573 buf += elementName;
1574 buf += ";\n\t";
1575 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001576 else {
1577 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001578 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001579 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1580 if (VD->getType()->isObjCQualifiedIdType() ||
1581 VD->getType()->isObjCQualifiedInterfaceType())
1582 // Simply use 'id' for all qualified types.
1583 elementTypeAsString = "id";
1584 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001585 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001588 // struct __objcFastEnumerationState enumState = { 0 };
1589 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1590 // id items[16];
1591 buf += "id items[16];\n\t";
1592 // id l_collection = (id)
1593 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001594 // Find start location of 'collection' the hard way!
1595 const char *startCollectionBuf = startBuf;
1596 startCollectionBuf += 3; // skip 'for'
1597 startCollectionBuf = strchr(startCollectionBuf, '(');
1598 startCollectionBuf++; // skip '('
1599 // find 'in' and skip it.
1600 while (*startCollectionBuf != ' ' ||
1601 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1602 (*(startCollectionBuf+3) != ' ' &&
1603 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1604 startCollectionBuf++;
1605 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001606
1607 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001608 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001610 SourceLocation rightParenLoc = S->getRParenLoc();
1611 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1612 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001614
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001615 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1616 // objects:items count:16];
1617 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001618 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001619 // ((unsigned int (*)
1620 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001621 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001622 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001623 // "countByEnumeratingWithState:objects:count:"),
1624 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001625 // (id *)items, (unsigned int)16);
1626 buf += "unsigned long limit =\n\t\t";
1627 SynthCountByEnumWithState(buf);
1628 buf += ";\n\t";
1629 /// if (limit) {
1630 /// unsigned long startMutations = *enumState.mutationsPtr;
1631 /// do {
1632 /// unsigned long counter = 0;
1633 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001634 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001635 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001636 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001637 buf += "if (limit) {\n\t";
1638 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1639 buf += "do {\n\t\t";
1640 buf += "unsigned long counter = 0;\n\t\t";
1641 buf += "do {\n\t\t\t";
1642 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1643 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1644 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001645 buf += " = (";
1646 buf += elementTypeAsString;
1647 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001649 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001651 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001652 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001653 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001654 /// objects:items count:16]);
1655 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001656 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001657 /// }
1658 /// else
1659 /// elem = nil;
1660 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001661 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001662 buf = ";\n\t";
1663 buf += "__continue_label_";
1664 buf += utostr(ObjCBcLabelNo.back());
1665 buf += ": ;";
1666 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001667 buf += "} while (counter < limit);\n\t";
1668 buf += "} while (limit = ";
1669 SynthCountByEnumWithState(buf);
1670 buf += ");\n\t";
1671 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001672 buf += " = ((";
1673 buf += elementTypeAsString;
1674 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001675 buf += "__break_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001678 buf += "}\n\t";
1679 buf += "else\n\t\t";
1680 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001681 buf += " = ((";
1682 buf += elementTypeAsString;
1683 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001684 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001685
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001686 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001687 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001688 if (isa<CompoundStmt>(S->getBody())) {
1689 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001690 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001691 } else {
1692 /* Need to treat single statements specially. For example:
1693 *
1694 * for (A *a in b) if (stuff()) break;
1695 * for (A *a in b) xxxyy;
1696 *
1697 * The following code simply scans ahead to the semi to find the actual end.
1698 */
1699 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1700 const char *semiBuf = strchr(stmtBuf, ';');
1701 assert(semiBuf && "Can't find ';'");
1702 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001703 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001704 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001705 Stmts.pop_back();
1706 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001707 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001708}
1709
Mike Stump11289f42009-09-09 15:08:12 +00001710/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001711/// This routine rewrites @synchronized(expr) stmt;
1712/// into:
1713/// objc_sync_enter(expr);
1714/// @try stmt @finally { objc_sync_exit(expr); }
1715///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001716Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001717 // Get the start location and compute the semi location.
1718 SourceLocation startLoc = S->getLocStart();
1719 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001720
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001721 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001722
1723 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001724 buf = "objc_sync_enter((id)";
1725 const char *lparenBuf = startBuf;
1726 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001727 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001728 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1729 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001730 // been rewritten! (which implies the SourceLocation's are invalid).
1731 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001732 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001733 while (*endBuf != ')') endBuf--;
1734 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001735 buf = ");\n";
1736 // declare a new scope with two variables, _stack and _rethrow.
1737 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1738 buf += "int buf[18/*32-bit i386*/];\n";
1739 buf += "char *pointers[4];} _stack;\n";
1740 buf += "id volatile _rethrow = 0;\n";
1741 buf += "objc_exception_try_enter(&_stack);\n";
1742 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001743 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001744 startLoc = S->getSynchBody()->getLocEnd();
1745 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroffad7013b2008-08-19 13:04:19 +00001747 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001748 SourceLocation lastCurlyLoc = startLoc;
1749 buf = "}\nelse {\n";
1750 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001751 buf += "}\n";
1752 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001753 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001754
1755 std::string syncBuf;
1756 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001757 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1758 CastExpr::CK_Unknown,
1759 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001760 std::string syncExprBufS;
1761 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001762 syncExpr->printPretty(syncExprBuf, *Context, 0,
1763 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001764 syncBuf += syncExprBuf.str();
1765 syncBuf += ");";
1766
1767 buf += syncBuf;
1768 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001769 buf += "}\n";
1770 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001771
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001772 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001773
1774 bool hasReturns = false;
1775 HasReturnStmts(S->getSynchBody(), hasReturns);
1776 if (hasReturns)
1777 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1778
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001779 return 0;
1780}
1781
Steve Naroffec60b432009-12-05 21:43:12 +00001782void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1783{
Steve Naroff6d6da252008-12-05 17:03:39 +00001784 // Perform a bottom up traversal of all children.
1785 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1786 CI != E; ++CI)
1787 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001788 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001789
Steve Naroffec60b432009-12-05 21:43:12 +00001790 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001791 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001792 TryFinallyContainsReturnDiag);
1793 }
1794 return;
1795}
1796
Steve Naroffec60b432009-12-05 21:43:12 +00001797void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1798{
1799 // Perform a bottom up traversal of all children.
1800 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1801 CI != E; ++CI)
1802 if (*CI)
1803 HasReturnStmts(*CI, hasReturns);
1804
1805 if (isa<ReturnStmt>(S))
1806 hasReturns = true;
1807 return;
1808}
1809
1810void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1811 // Perform a bottom up traversal of all children.
1812 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1813 CI != E; ++CI)
1814 if (*CI) {
1815 RewriteTryReturnStmts(*CI);
1816 }
1817 if (isa<ReturnStmt>(S)) {
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
1820
1821 const char *semiBuf = strchr(startBuf, ';');
1822 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1823 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1824
1825 std::string buf;
1826 buf = "{ objc_exception_try_exit(&_stack); return";
1827
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001828 ReplaceText(startLoc, 6, buf);
1829 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001830 }
1831 return;
1832}
1833
1834void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1835 // Perform a bottom up traversal of all children.
1836 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1837 CI != E; ++CI)
1838 if (*CI) {
1839 RewriteSyncReturnStmts(*CI, syncExitBuf);
1840 }
1841 if (isa<ReturnStmt>(S)) {
1842 SourceLocation startLoc = S->getLocStart();
1843 const char *startBuf = SM->getCharacterData(startLoc);
1844
1845 const char *semiBuf = strchr(startBuf, ';');
1846 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1847 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1848
1849 std::string buf;
1850 buf = "{ objc_exception_try_exit(&_stack);";
1851 buf += syncExitBuf;
1852 buf += " return";
1853
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001854 ReplaceText(startLoc, 6, buf);
1855 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001856 }
1857 return;
1858}
1859
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001860Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001861 // Get the start location and compute the semi location.
1862 SourceLocation startLoc = S->getLocStart();
1863 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001864
Steve Naroffbf478ec2007-11-07 04:08:17 +00001865 assert((*startBuf == '@') && "bogus @try location");
1866
1867 std::string buf;
1868 // declare a new scope with two variables, _stack and _rethrow.
1869 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1870 buf += "int buf[18/*32-bit i386*/];\n";
1871 buf += "char *pointers[4];} _stack;\n";
1872 buf += "id volatile _rethrow = 0;\n";
1873 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001874 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001875
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001876 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Steve Naroffbf478ec2007-11-07 04:08:17 +00001878 startLoc = S->getTryBody()->getLocEnd();
1879 startBuf = SM->getCharacterData(startLoc);
1880
1881 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001882
Steve Naroffbf478ec2007-11-07 04:08:17 +00001883 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001884 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001885 startLoc = startLoc.getFileLocWithOffset(1);
1886 buf = " /* @catch begin */ else {\n";
1887 buf += " id _caught = objc_exception_extract(&_stack);\n";
1888 buf += " objc_exception_try_enter (&_stack);\n";
1889 buf += " if (_setjmp(_stack.buf))\n";
1890 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1891 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001892
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001893 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001894 } else { /* no catch list */
1895 buf = "}\nelse {\n";
1896 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1897 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001898 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001899 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001900 bool sawIdTypedCatch = false;
1901 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001902 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1903 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001904 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001905
Douglas Gregor96c79492010-04-23 22:50:49 +00001906 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001907 buf = "if ("; // we are generating code for the first catch clause
1908 else
1909 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001910 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001911 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Steve Naroffbf478ec2007-11-07 04:08:17 +00001913 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001914
Steve Naroffbf478ec2007-11-07 04:08:17 +00001915 const char *lParenLoc = strchr(startBuf, '(');
1916
Douglas Gregor96c79492010-04-23 22:50:49 +00001917 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001918 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001919 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001920 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1921 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001922 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001923 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001924 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001925
Steve Naroffedb5bc62008-02-01 20:02:07 +00001926 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001927 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001928 } else if (catchDecl) {
1929 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001930 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001931 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001932 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001933 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001934 } else if (const ObjCObjectPointerType *Ptr =
1935 t->getAs<ObjCObjectPointerType>()) {
1936 // Should be a pointer to a class.
1937 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1938 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001939 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001940 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001941 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001942 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001943 }
1944 }
1945 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001946 lastCatchBody = Catch->getCatchBody();
1947 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001948 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1949 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1950 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1951 assert((*rParenBuf == ')') && "bogus @catch paren location");
1952 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001953
Mike Stump11289f42009-09-09 15:08:12 +00001954 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001955 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001956 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001957 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001959 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001960 }
1961 // Complete the catch list...
1962 if (lastCatchBody) {
1963 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001964 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1965 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001966
Steve Naroff4adbe312008-09-11 15:29:03 +00001967 // Insert the last (implicit) else clause *before* the right curly brace.
1968 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1969 buf = "} /* last catch end */\n";
1970 buf += "else {\n";
1971 buf += " _rethrow = _caught;\n";
1972 buf += " objc_exception_try_exit(&_stack);\n";
1973 buf += "} } /* @catch end */\n";
1974 if (!S->getFinallyStmt())
1975 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001976 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001977
Steve Naroffbf478ec2007-11-07 04:08:17 +00001978 // Set lastCurlyLoc
1979 lastCurlyLoc = lastCatchBody->getLocEnd();
1980 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001981 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001982 startLoc = finalStmt->getLocStart();
1983 startBuf = SM->getCharacterData(startLoc);
1984 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001985
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001986 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001987
Steve Naroffbf478ec2007-11-07 04:08:17 +00001988 Stmt *body = finalStmt->getFinallyBody();
1989 SourceLocation startLoc = body->getLocStart();
1990 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001991 assert(*SM->getCharacterData(startLoc) == '{' &&
1992 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001993 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001994 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001995
Steve Naroffbf478ec2007-11-07 04:08:17 +00001996 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001997 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001998 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001999 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002000
Steve Naroffbf478ec2007-11-07 04:08:17 +00002001 // Set lastCurlyLoc
2002 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002003
Steve Naroff6d6da252008-12-05 17:03:39 +00002004 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002005 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002006 } else { /* no finally clause - make sure we synthesize an implicit one */
2007 buf = "{ /* implicit finally clause */\n";
2008 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2009 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2010 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002011 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002012
2013 // Now check for any return/continue/go statements within the @try.
2014 // The implicit finally clause won't called if the @try contains any
2015 // jump statements.
2016 bool hasReturns = false;
2017 HasReturnStmts(S->getTryBody(), hasReturns);
2018 if (hasReturns)
2019 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002020 }
2021 // Now emit the final closing curly brace...
2022 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002023 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002024 return 0;
2025}
2026
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002027Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002028 return 0;
2029}
2030
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002031Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002032 return 0;
2033}
2034
Mike Stump11289f42009-09-09 15:08:12 +00002035// This can't be done with ReplaceStmt(S, ThrowExpr), since
2036// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002037// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002038Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002039 // Get the start location and compute the semi location.
2040 SourceLocation startLoc = S->getLocStart();
2041 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002042
Steve Naroffa733c7f2007-11-07 15:32:26 +00002043 assert((*startBuf == '@') && "bogus @throw location");
2044
2045 std::string buf;
2046 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002047 if (S->getThrowExpr())
2048 buf = "objc_exception_throw(";
2049 else // add an implicit argument
2050 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002051
Steve Naroff29788342008-07-25 15:41:30 +00002052 // handle "@ throw" correctly.
2053 const char *wBuf = strchr(startBuf, 'w');
2054 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002055 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Steve Naroffa733c7f2007-11-07 15:32:26 +00002057 const char *semiBuf = strchr(startBuf, ';');
2058 assert((*semiBuf == ';') && "@throw: can't find ';'");
2059 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002060 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002061 return 0;
2062}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002063
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002064Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002065 // Create a new string expression.
2066 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002067 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002068 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002069 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2070 StrEncoding.length(), false,StrType,
2071 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002072 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattner4431a1b2007-11-30 22:53:43 +00002074 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002075 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002076 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002077}
2078
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002079Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002080 if (!SelGetUidFunctionDecl)
2081 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002082 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2083 // Create a call to sel_registerName("selName").
2084 llvm::SmallVector<Expr*, 8> SelExprs;
2085 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002086 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002087 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002088 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002089 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002090 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2091 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002092 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002093 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002094 return SelExp;
2095}
2096
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002097CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002098 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2099 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002100 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002101 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002102
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002103 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002104 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002105
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002106 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002107 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002108 ImplicitCastExpr *ICE =
John McCallcf142162010-08-07 06:22:56 +00002109 ImplicitCastExpr::Create(*Context, pToFunc, CastExpr::CK_Unknown,
2110 DRE, 0, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002111
John McCall9dd450b2009-09-21 23:43:11 +00002112 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002113
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002114 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002115 new (Context) CallExpr(*Context, ICE, args, nargs,
2116 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002117 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002118}
2119
Steve Naroff50d42052007-11-01 13:24:47 +00002120static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2121 const char *&startRef, const char *&endRef) {
2122 while (startBuf < endBuf) {
2123 if (*startBuf == '<')
2124 startRef = startBuf; // mark the start.
2125 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002126 if (startRef && *startRef == '<') {
2127 endRef = startBuf; // mark the end.
2128 return true;
2129 }
2130 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002131 }
2132 startBuf++;
2133 }
2134 return false;
2135}
2136
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002137static void scanToNextArgument(const char *&argRef) {
2138 int angle = 0;
2139 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2140 if (*argRef == '<')
2141 angle++;
2142 else if (*argRef == '>')
2143 angle--;
2144 argRef++;
2145 }
2146 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2147}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002148
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002149bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002150 if (T->isObjCQualifiedIdType())
2151 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002152 if (const PointerType *PT = T->getAs<PointerType>()) {
2153 if (PT->getPointeeType()->isObjCQualifiedIdType())
2154 return true;
2155 }
2156 if (T->isObjCObjectPointerType()) {
2157 T = T->getPointeeType();
2158 return T->isObjCQualifiedInterfaceType();
2159 }
2160 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002161}
2162
Steve Naroff873bd842008-07-29 18:15:38 +00002163void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2164 QualType Type = E->getType();
2165 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002166 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002167
Steve Naroffdbfc6932008-11-19 21:15:47 +00002168 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2169 Loc = ECE->getLParenLoc();
2170 EndLoc = ECE->getRParenLoc();
2171 } else {
2172 Loc = E->getLocStart();
2173 EndLoc = E->getLocEnd();
2174 }
2175 // This will defend against trying to rewrite synthesized expressions.
2176 if (Loc.isInvalid() || EndLoc.isInvalid())
2177 return;
2178
Steve Naroff873bd842008-07-29 18:15:38 +00002179 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002180 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002181 const char *startRef = 0, *endRef = 0;
2182 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183 // Get the locations of the startRef, endRef.
2184 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2185 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2186 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002187 InsertText(LessLoc, "/*");
2188 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002189 }
2190 }
2191}
2192
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002193void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002194 SourceLocation Loc;
2195 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002196 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002197 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2198 Loc = VD->getLocation();
2199 Type = VD->getType();
2200 }
2201 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2202 Loc = FD->getLocation();
2203 // Check for ObjC 'id' and class types that have been adorned with protocol
2204 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002205 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002206 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002207 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002208 if (!proto)
2209 return;
2210 Type = proto->getResultType();
2211 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002212 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2213 Loc = FD->getLocation();
2214 Type = FD->getType();
2215 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002216 else
2217 return;
Mike Stump11289f42009-09-09 15:08:12 +00002218
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002219 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002220 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002221
Steve Naroff50d42052007-11-01 13:24:47 +00002222 const char *endBuf = SM->getCharacterData(Loc);
2223 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002224 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002225 startBuf--; // scan backward (from the decl location) for return type.
2226 const char *startRef = 0, *endRef = 0;
2227 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2228 // Get the locations of the startRef, endRef.
2229 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2230 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2231 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002232 InsertText(LessLoc, "/*");
2233 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002234 }
2235 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002236 if (!proto)
2237 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002238 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002239 const char *startBuf = SM->getCharacterData(Loc);
2240 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002241 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2242 if (needToScanForQualifiers(proto->getArgType(i))) {
2243 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002244
Steve Naroff50d42052007-11-01 13:24:47 +00002245 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002246 // scan forward (from the decl location) for argument types.
2247 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002248 const char *startRef = 0, *endRef = 0;
2249 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2250 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002251 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002252 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002253 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002254 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002255 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002256 InsertText(LessLoc, "/*");
2257 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002258 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002259 startBuf = ++endBuf;
2260 }
2261 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002262 // If the function name is derived from a macro expansion, then the
2263 // argument buffer will not follow the name. Need to speak with Chris.
2264 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002265 startBuf++; // scan forward (from the decl location) for argument types.
2266 startBuf++;
2267 }
Steve Naroff50d42052007-11-01 13:24:47 +00002268 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002269}
2270
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002271void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2272 QualType QT = ND->getType();
2273 const Type* TypePtr = QT->getAs<Type>();
2274 if (!isa<TypeOfExprType>(TypePtr))
2275 return;
2276 while (isa<TypeOfExprType>(TypePtr)) {
2277 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2278 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2279 TypePtr = QT->getAs<Type>();
2280 }
2281 // FIXME. This will not work for multiple declarators; as in:
2282 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002283 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002284 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2285 const char *startBuf = SM->getCharacterData(DeclLoc);
2286 if (ND->getInit()) {
2287 std::string Name(ND->getNameAsString());
2288 TypeAsString += " " + Name + " = ";
2289 Expr *E = ND->getInit();
2290 SourceLocation startLoc;
2291 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2292 startLoc = ECE->getLParenLoc();
2293 else
2294 startLoc = E->getLocStart();
2295 startLoc = SM->getInstantiationLoc(startLoc);
2296 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002297 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002298 }
2299 else {
2300 SourceLocation X = ND->getLocEnd();
2301 X = SM->getInstantiationLoc(X);
2302 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002303 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002304 }
2305}
2306
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002307// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002308void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002309 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2310 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002311 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002312 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002313 &ArgTys[0], ArgTys.size(),
2314 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002315 false, false, 0, 0,
2316 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002317 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002318 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002319 SelGetUidIdent, getFuncType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002320 FunctionDecl::Extern,
2321 FunctionDecl::None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002322}
2323
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002324void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002325 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002326 if (FD->getIdentifier() &&
2327 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002328 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002329 return;
2330 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002331 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002332}
2333
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002334void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2335 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002336 const char *argPtr = TypeString.c_str();
2337 if (!strchr(argPtr, '^')) {
2338 Str += TypeString;
2339 return;
2340 }
2341 while (*argPtr) {
2342 Str += (*argPtr == '^' ? '*' : *argPtr);
2343 argPtr++;
2344 }
2345}
2346
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002347// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002348void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2349 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002350 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002351 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002352 const char *argPtr = TypeString.c_str();
2353 int paren = 0;
2354 while (*argPtr) {
2355 switch (*argPtr) {
2356 case '(':
2357 Str += *argPtr;
2358 paren++;
2359 break;
2360 case ')':
2361 Str += *argPtr;
2362 paren--;
2363 break;
2364 case '^':
2365 Str += '*';
2366 if (paren == 1)
2367 Str += VD->getNameAsString();
2368 break;
2369 default:
2370 Str += *argPtr;
2371 break;
2372 }
2373 argPtr++;
2374 }
2375}
2376
2377
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002378void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2379 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2380 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2381 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2382 if (!proto)
2383 return;
2384 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002385 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002386 FdStr += " ";
2387 FdStr += FD->getNameAsCString();
2388 FdStr += "(";
2389 unsigned numArgs = proto->getNumArgs();
2390 for (unsigned i = 0; i < numArgs; i++) {
2391 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002392 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002393 if (i+1 < numArgs)
2394 FdStr += ", ";
2395 }
2396 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002397 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002398 CurFunctionDeclToDeclareForBlock = 0;
2399}
2400
Steve Naroff17978c42008-03-11 17:37:02 +00002401// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002402void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002403 if (SuperContructorFunctionDecl)
2404 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002405 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002406 llvm::SmallVector<QualType, 16> ArgTys;
2407 QualType argT = Context->getObjCIdType();
2408 assert(!argT.isNull() && "Can't find 'id' type");
2409 ArgTys.push_back(argT);
2410 ArgTys.push_back(argT);
2411 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2412 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002413 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002414 false, false, 0, 0,
2415 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002416 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002417 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002418 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002419 FunctionDecl::Extern,
2420 FunctionDecl::None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002421}
2422
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002423// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002424void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002425 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2426 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002427 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002428 assert(!argT.isNull() && "Can't find 'id' type");
2429 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002430 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002431 assert(!argT.isNull() && "Can't find 'SEL' type");
2432 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002433 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002434 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002435 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002436 false, false, 0, 0,
2437 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002438 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002439 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002440 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002441 FunctionDecl::Extern,
2442 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002443}
2444
Steve Naroff7fa2f042007-11-15 10:28:18 +00002445// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002446void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002447 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2448 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002449 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002450 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002451 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002452 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2453 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2454 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002455 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002456 assert(!argT.isNull() && "Can't find 'SEL' type");
2457 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002458 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002459 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002460 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002461 false, false, 0, 0,
2462 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002463 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002464 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002465 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002466 FunctionDecl::Extern,
2467 FunctionDecl::None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002468}
2469
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002470// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002471void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002472 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2473 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002474 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002477 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002478 assert(!argT.isNull() && "Can't find 'SEL' type");
2479 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002480 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002481 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002482 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002483 false, false, 0, 0,
2484 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002485 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002486 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002487 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002488 FunctionDecl::Extern,
2489 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002490}
2491
Mike Stump11289f42009-09-09 15:08:12 +00002492// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002493// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002494void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002495 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002496 &Context->Idents.get("objc_msgSendSuper_stret");
2497 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002498 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002499 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002500 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002501 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2502 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2503 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002504 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002505 assert(!argT.isNull() && "Can't find 'SEL' type");
2506 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002507 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002508 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002509 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002510 false, false, 0, 0,
2511 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002512 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002513 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002514 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002515 FunctionDecl::Extern,
2516 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002517}
2518
Steve Naroff2e4e3852008-05-08 22:02:18 +00002519// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002520void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002521 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2522 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002523 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002524 assert(!argT.isNull() && "Can't find 'id' type");
2525 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002526 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002527 assert(!argT.isNull() && "Can't find 'SEL' type");
2528 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002529 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002530 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002531 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002532 false, false, 0, 0,
2533 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002534 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002535 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002536 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002537 FunctionDecl::Extern,
2538 FunctionDecl::None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002539}
2540
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002541// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002542void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002543 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2544 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002545 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002546 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002547 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002548 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002549 false, false, 0, 0,
2550 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002551 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002552 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002553 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002554 FunctionDecl::Extern,
2555 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002556}
2557
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002558// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2559void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2560 IdentifierInfo *getSuperClassIdent =
2561 &Context->Idents.get("class_getSuperclass");
2562 llvm::SmallVector<QualType, 16> ArgTys;
2563 ArgTys.push_back(Context->getObjCClassType());
2564 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2565 &ArgTys[0], ArgTys.size(),
2566 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002567 false, false, 0, 0,
2568 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002569 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002570 SourceLocation(),
2571 getSuperClassIdent,
2572 getClassType, 0,
2573 FunctionDecl::Extern,
2574 FunctionDecl::None,
2575 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002576}
2577
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002578// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002579void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002580 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2581 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002582 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002583 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002584 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002585 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002586 false, false, 0, 0,
2587 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002588 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002589 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002590 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002591 FunctionDecl::Extern,
2592 FunctionDecl::None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002593}
2594
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002595Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002596 QualType strType = getConstantStringStructType();
2597
2598 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002599
2600 std::string tmpName = InFileName;
2601 unsigned i;
2602 for (i=0; i < tmpName.length(); i++) {
2603 char c = tmpName.at(i);
2604 // replace any non alphanumeric characters with '_'.
2605 if (!isalpha(c) && (c < '0' || c > '9'))
2606 tmpName[i] = '_';
2607 }
2608 S += tmpName;
2609 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002610 S += utostr(NumObjCStringLiterals++);
2611
Steve Naroff00a31762008-03-27 22:29:16 +00002612 Preamble += "static __NSConstantStringImpl " + S;
2613 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2614 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002615 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002616 std::string prettyBufS;
2617 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002618 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2619 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002620 Preamble += prettyBuf.str();
2621 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002622 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002623
2624 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002625 &Context->Idents.get(S), strType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002626 VarDecl::Static, VarDecl::None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002627 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2628 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002629 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002630 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002631 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002632 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2633 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002634 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002635 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002636 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002637}
2638
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002639bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002640 // check if we are sending a message to 'super'
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002641 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2642 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002643}
2644
2645// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002646QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002647 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002648 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002649 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002650 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002651 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002652
Steve Naroff7fa2f042007-11-15 10:28:18 +00002653 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002654 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002655 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002656 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002657
Steve Naroff7fa2f042007-11-15 10:28:18 +00002658 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002659 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002660 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2661 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002662 FieldTypes[i], 0,
2663 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002664 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Douglas Gregord5058122010-02-11 01:19:42 +00002667 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002668 }
2669 return Context->getTagDeclType(SuperStructDecl);
2670}
2671
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002672QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002673 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002674 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002675 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002676 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002677 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002678
Steve Naroffce8e8862008-03-15 00:55:56 +00002679 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002680 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002681 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002682 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002683 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002684 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002685 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002686 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002687
Steve Naroffce8e8862008-03-15 00:55:56 +00002688 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002689 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002690 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2691 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002692 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002693 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002694 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002695 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002696 }
2697
Douglas Gregord5058122010-02-11 01:19:42 +00002698 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002699 }
2700 return Context->getTagDeclType(ConstantStringDecl);
2701}
2702
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002703Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2704 SourceLocation StartLoc,
2705 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002706 if (!SelGetUidFunctionDecl)
2707 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002708 if (!MsgSendFunctionDecl)
2709 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002710 if (!MsgSendSuperFunctionDecl)
2711 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002712 if (!MsgSendStretFunctionDecl)
2713 SynthMsgSendStretFunctionDecl();
2714 if (!MsgSendSuperStretFunctionDecl)
2715 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002716 if (!MsgSendFpretFunctionDecl)
2717 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002718 if (!GetClassFunctionDecl)
2719 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002720 if (!GetSuperClassFunctionDecl)
2721 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002722 if (!GetMetaClassFunctionDecl)
2723 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002724
Steve Naroff7fa2f042007-11-15 10:28:18 +00002725 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002726 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2727 // May need to use objc_msgSend_stret() as well.
2728 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002729 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2730 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002731 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002732 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002733 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002734 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
Steve Naroff574440f2007-10-24 22:48:43 +00002737 // Synthesize a call to objc_msgSend().
2738 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002739 switch (Exp->getReceiverKind()) {
2740 case ObjCMessageExpr::SuperClass: {
2741 MsgSendFlavor = MsgSendSuperFunctionDecl;
2742 if (MsgSendStretFlavor)
2743 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2744 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002745
Douglas Gregor9a129192010-04-21 00:45:42 +00002746 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregor9a129192010-04-21 00:45:42 +00002748 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002749
Douglas Gregor9a129192010-04-21 00:45:42 +00002750 // set the receiver to self, the first argument to all methods.
2751 InitExprs.push_back(
2752 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2753 CastExpr::CK_Unknown,
2754 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2755 Context->getObjCIdType(),
2756 SourceLocation()))
2757 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregor9a129192010-04-21 00:45:42 +00002759 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2760 llvm::SmallVector<Expr*, 8> ClsExprs;
2761 QualType argType = Context->getPointerType(Context->CharTy);
2762 ClsExprs.push_back(StringLiteral::Create(*Context,
2763 ClassDecl->getIdentifier()->getNameStart(),
2764 ClassDecl->getIdentifier()->getLength(),
2765 false, argType, SourceLocation()));
2766 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2767 &ClsExprs[0],
2768 ClsExprs.size(),
2769 StartLoc,
2770 EndLoc);
2771 // (Class)objc_getClass("CurrentClass")
2772 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2773 Context->getObjCClassType(),
2774 CastExpr::CK_Unknown, Cls);
2775 ClsExprs.clear();
2776 ClsExprs.push_back(ArgExpr);
2777 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2778 &ClsExprs[0], ClsExprs.size(),
2779 StartLoc, EndLoc);
2780
2781 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2782 // To turn off a warning, type-cast to 'id'
2783 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2784 NoTypeInfoCStyleCastExpr(Context,
2785 Context->getObjCIdType(),
2786 CastExpr::CK_Unknown, Cls));
2787 // struct objc_super
2788 QualType superType = getSuperStructType();
2789 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002790
Douglas Gregor9a129192010-04-21 00:45:42 +00002791 if (LangOpts.Microsoft) {
2792 SynthSuperContructorFunctionDecl();
2793 // Simulate a contructor call...
2794 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2795 superType, SourceLocation());
2796 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2797 InitExprs.size(),
2798 superType, SourceLocation());
2799 // The code for super is a little tricky to prevent collision with
2800 // the structure definition in the header. The rewriter has it's own
2801 // internal definition (__rw_objc_super) that is uses. This is why
2802 // we need the cast below. For example:
2803 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2804 //
2805 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2806 Context->getPointerType(SuperRep->getType()),
2807 SourceLocation());
2808 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2809 Context->getPointerType(superType),
2810 CastExpr::CK_Unknown, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002811 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002812 // (struct objc_super) { <exprs from above> }
2813 InitListExpr *ILE =
2814 new (Context) InitListExpr(*Context, SourceLocation(),
2815 &InitExprs[0], InitExprs.size(),
2816 SourceLocation());
2817 TypeSourceInfo *superTInfo
2818 = Context->getTrivialTypeSourceInfo(superType);
2819 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2820 superType, ILE, false);
2821 // struct objc_super *
2822 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2823 Context->getPointerType(SuperRep->getType()),
2824 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002825 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002826 MsgExprs.push_back(SuperRep);
2827 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002828 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002829
2830 case ObjCMessageExpr::Class: {
2831 llvm::SmallVector<Expr*, 8> ClsExprs;
2832 QualType argType = Context->getPointerType(Context->CharTy);
2833 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002834 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002835 IdentifierInfo *clsName = Class->getIdentifier();
2836 ClsExprs.push_back(StringLiteral::Create(*Context,
2837 clsName->getNameStart(),
2838 clsName->getLength(),
2839 false, argType,
2840 SourceLocation()));
2841 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2842 &ClsExprs[0],
2843 ClsExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(Cls);
2846 break;
2847 }
2848
2849 case ObjCMessageExpr::SuperInstance:{
2850 MsgSendFlavor = MsgSendSuperFunctionDecl;
2851 if (MsgSendStretFlavor)
2852 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2853 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2854 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2855 llvm::SmallVector<Expr*, 4> InitExprs;
2856
2857 InitExprs.push_back(
2858 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2859 CastExpr::CK_Unknown,
2860 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2861 Context->getObjCIdType(),
2862 SourceLocation()))
2863 ); // set the 'receiver'.
2864
2865 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2866 llvm::SmallVector<Expr*, 8> ClsExprs;
2867 QualType argType = Context->getPointerType(Context->CharTy);
2868 ClsExprs.push_back(StringLiteral::Create(*Context,
2869 ClassDecl->getIdentifier()->getNameStart(),
2870 ClassDecl->getIdentifier()->getLength(),
2871 false, argType, SourceLocation()));
2872 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2873 &ClsExprs[0],
2874 ClsExprs.size(),
2875 StartLoc, EndLoc);
2876 // (Class)objc_getClass("CurrentClass")
2877 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2878 Context->getObjCClassType(),
2879 CastExpr::CK_Unknown, Cls);
2880 ClsExprs.clear();
2881 ClsExprs.push_back(ArgExpr);
2882 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2883 &ClsExprs[0], ClsExprs.size(),
2884 StartLoc, EndLoc);
2885
2886 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2887 // To turn off a warning, type-cast to 'id'
2888 InitExprs.push_back(
2889 // set 'super class', using class_getSuperclass().
2890 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2891 CastExpr::CK_Unknown, Cls));
2892 // struct objc_super
2893 QualType superType = getSuperStructType();
2894 Expr *SuperRep;
2895
2896 if (LangOpts.Microsoft) {
2897 SynthSuperContructorFunctionDecl();
2898 // Simulate a contructor call...
2899 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2900 superType, SourceLocation());
2901 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2902 InitExprs.size(),
2903 superType, SourceLocation());
2904 // The code for super is a little tricky to prevent collision with
2905 // the structure definition in the header. The rewriter has it's own
2906 // internal definition (__rw_objc_super) that is uses. This is why
2907 // we need the cast below. For example:
2908 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2909 //
2910 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2911 Context->getPointerType(SuperRep->getType()),
2912 SourceLocation());
2913 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2914 Context->getPointerType(superType),
2915 CastExpr::CK_Unknown, SuperRep);
2916 } else {
2917 // (struct objc_super) { <exprs from above> }
2918 InitListExpr *ILE =
2919 new (Context) InitListExpr(*Context, SourceLocation(),
2920 &InitExprs[0], InitExprs.size(),
2921 SourceLocation());
2922 TypeSourceInfo *superTInfo
2923 = Context->getTrivialTypeSourceInfo(superType);
2924 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2925 superType, ILE, false);
2926 }
2927 MsgExprs.push_back(SuperRep);
2928 break;
2929 }
2930
2931 case ObjCMessageExpr::Instance: {
2932 // Remove all type-casts because it may contain objc-style types; e.g.
2933 // Foo<Proto> *.
2934 Expr *recExpr = Exp->getInstanceReceiver();
2935 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2936 recExpr = CE->getSubExpr();
2937 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2938 CastExpr::CK_Unknown, recExpr);
2939 MsgExprs.push_back(recExpr);
2940 break;
2941 }
2942 }
2943
Steve Naroffa397efd2007-11-03 11:27:19 +00002944 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002945 llvm::SmallVector<Expr*, 8> SelExprs;
2946 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002947 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002948 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002949 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002950 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002951 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002952 &SelExprs[0], SelExprs.size(),
2953 StartLoc,
2954 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002955 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002956
Steve Naroff574440f2007-10-24 22:48:43 +00002957 // Now push any user supplied arguments.
2958 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002959 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002960 // Make all implicit casts explicit...ICE comes in handy:-)
2961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2962 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002963 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002964 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002965 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002966 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002967 (void)convertBlockPointerToFunctionPointer(type);
John McCall97513962010-01-15 18:39:57 +00002968 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2969 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002970 }
2971 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002972 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002973 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002974 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002975 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002976 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2977 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002980 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002981 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2982 // out the argument in the original expression (since we aren't deleting
2983 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2984 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002985 }
Steve Narofff36987c2007-11-04 22:37:50 +00002986 // Generate the funky cast.
2987 CastExpr *cast;
2988 llvm::SmallVector<QualType, 8> ArgTypes;
2989 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002990
Steve Narofff36987c2007-11-04 22:37:50 +00002991 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002992 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2993 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2994 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002995 ArgTypes.push_back(Context->getObjCIdType());
2996 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002997 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002998 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002999 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3000 E = OMD->param_end(); PI != E; ++PI) {
3001 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003002 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003003 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003004 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003005 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003006 ArgTypes.push_back(t);
3007 }
Chris Lattnera4997152009-02-20 18:43:26 +00003008 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3009 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003010 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003011 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003012 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003013 }
3014 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003015 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Narofff36987c2007-11-04 22:37:50 +00003017 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003018 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003019 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003020
Mike Stump11289f42009-09-09 15:08:12 +00003021 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003022 // If we don't do this cast, we get the following bizarre warning/note:
3023 // xx.m:13: warning: function called through a non-compatible type
3024 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003025 cast = NoTypeInfoCStyleCastExpr(Context,
3026 Context->getPointerType(Context->VoidTy),
3027 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003028
Steve Narofff36987c2007-11-04 22:37:50 +00003029 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003030 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003031 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003032 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003033 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003034 false, false, 0, 0,
3035 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003036 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00003037 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3038 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003039
3040 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003041 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003042
John McCall9dd450b2009-09-21 23:43:11 +00003043 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003044 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003045 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003046 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003047 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003048 if (MsgSendStretFlavor) {
3049 // We have the method which returns a struct/union. Must also generate
3050 // call to objc_msgSend_stret and hang both varieties on a conditional
3051 // expression which dictate which one to envoke depending on size of
3052 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003053
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003054 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003055 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003056 SourceLocation());
3057 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003058 cast = NoTypeInfoCStyleCastExpr(Context,
3059 Context->getPointerType(Context->VoidTy),
3060 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003061 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003062 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003063 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003064 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003065 false, false, 0, 0,
3066 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003067 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00003068 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3069 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003070
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003071 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003072 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003073
John McCall9dd450b2009-09-21 23:43:11 +00003074 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003075 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003076 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003077 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003078
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003079 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003080 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003081 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003082 Context->getSizeType(),
3083 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003084 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3085 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3086 // For X86 it is more complicated and some kind of target specific routine
3087 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003088 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003089 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00003090 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003091 Context->IntTy,
3092 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003093 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3094 BinaryOperator::LE,
3095 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003096 SourceLocation());
3097 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003098 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003099 new (Context) ConditionalOperator(lessThanExpr,
3100 SourceLocation(), CE,
3101 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00003102 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003103 }
Mike Stump11289f42009-09-09 15:08:12 +00003104 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003105 return ReplacingStmt;
3106}
3107
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003108Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003109 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3110 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003111
Steve Naroff574440f2007-10-24 22:48:43 +00003112 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003113 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003114
3115 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003116 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003117}
3118
Steve Naroffd9803712009-04-29 16:37:50 +00003119// typedef struct objc_object Protocol;
3120QualType RewriteObjC::getProtocolType() {
3121 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003122 TypeSourceInfo *TInfo
3123 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003124 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003125 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003126 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003127 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003128 }
3129 return Context->getTypeDeclType(ProtocolTypeDecl);
3130}
3131
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003132/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003133/// a synthesized/forward data reference (to the protocol's metadata).
3134/// The forward references (and metadata) are generated in
3135/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003136Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003137 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3138 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003139 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003140 ID, getProtocolType(), 0,
3141 VarDecl::Extern, VarDecl::None);
Steve Naroffd9803712009-04-29 16:37:50 +00003142 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3143 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3144 Context->getPointerType(DRE->getType()),
3145 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003146 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3147 CastExpr::CK_Unknown,
3148 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003149 ReplaceStmt(Exp, castExpr);
3150 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003151 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003152 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003153
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003154}
3155
Mike Stump11289f42009-09-09 15:08:12 +00003156bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003157 const char *endBuf) {
3158 while (startBuf < endBuf) {
3159 if (*startBuf == '#') {
3160 // Skip whitespace.
3161 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3162 ;
3163 if (!strncmp(startBuf, "if", strlen("if")) ||
3164 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3165 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3166 !strncmp(startBuf, "define", strlen("define")) ||
3167 !strncmp(startBuf, "undef", strlen("undef")) ||
3168 !strncmp(startBuf, "else", strlen("else")) ||
3169 !strncmp(startBuf, "elif", strlen("elif")) ||
3170 !strncmp(startBuf, "endif", strlen("endif")) ||
3171 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3172 !strncmp(startBuf, "include", strlen("include")) ||
3173 !strncmp(startBuf, "import", strlen("import")) ||
3174 !strncmp(startBuf, "include_next", strlen("include_next")))
3175 return true;
3176 }
3177 startBuf++;
3178 }
3179 return false;
3180}
3181
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003182/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003183/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003184void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003185 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003186 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00003187 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003188 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003189 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003190 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003191 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003192 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003193 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003194 SourceLocation LocStart = CDecl->getLocStart();
3195 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003196
Steve Naroffdde78982007-11-14 19:25:57 +00003197 const char *startBuf = SM->getCharacterData(LocStart);
3198 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003199
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003200 // If no ivars and no root or if its root, directly or indirectly,
3201 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003202 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3203 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003204 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003205 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003206 return;
3207 }
Mike Stump11289f42009-09-09 15:08:12 +00003208
3209 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003210 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003211 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003212 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003213 if (LangOpts.Microsoft)
3214 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003215
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003216 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003217 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003218 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003219 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003220 // If the buffer contains preprocessor directives, we do more fine-grained
3221 // rewrites. This is intended to fix code that looks like (which occurs in
3222 // NSURL.h, for example):
3223 //
3224 // #ifdef XYZ
3225 // @interface Foo : NSObject
3226 // #else
3227 // @interface FooBar : NSObject
3228 // #endif
3229 // {
3230 // int i;
3231 // }
3232 // @end
3233 //
3234 // This clause is segregated to avoid breaking the common case.
3235 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003236 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003237 CDecl->getClassLoc();
3238 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003239 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003240
Chris Lattnerf5b77512009-02-20 18:18:36 +00003241 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003242 // advance to the end of the referenced protocols.
3243 while (endHeader < cursor && *endHeader != '>') endHeader++;
3244 endHeader++;
3245 }
3246 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003247 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003248 } else {
3249 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003250 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003251 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003252 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003253 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003254 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003255 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003256 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003257 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003258
Steve Naroffdde78982007-11-14 19:25:57 +00003259 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003260 SourceLocation OnePastCurly =
3261 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003262 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003263 }
3264 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003265
Steve Naroffdde78982007-11-14 19:25:57 +00003266 // Now comment out any visibility specifiers.
3267 while (cursor < endBuf) {
3268 if (*cursor == '@') {
3269 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003270 // Skip whitespace.
3271 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3272 /*scan*/;
3273
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003274 // FIXME: presence of @public, etc. inside comment results in
3275 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003276 if (!strncmp(cursor, "public", strlen("public")) ||
3277 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003278 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003279 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003280 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003281 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003282 // FIXME: If there are cases where '<' is used in ivar declaration part
3283 // of user code, then scan the ivar list and use needToScanForQualifiers
3284 // for type checking.
3285 else if (*cursor == '<') {
3286 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003287 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003288 cursor = strchr(cursor, '>');
3289 cursor++;
3290 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003291 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003292 } else if (*cursor == '^') { // rewrite block specifier.
3293 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003294 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003295 }
Steve Naroffdde78982007-11-14 19:25:57 +00003296 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003297 }
Steve Naroffdde78982007-11-14 19:25:57 +00003298 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003299 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003300 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003301 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003302 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003303 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003304 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003305 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003306 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003307 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003308 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003309 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003310 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003311 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003312}
3313
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003314// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003315/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003316template<typename MethodIterator>
3317void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3318 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003319 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003320 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003321 const char *ClassName,
3322 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003323 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003324
Chris Lattner31bc07e2007-12-12 07:46:12 +00003325 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003326 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003327 SEL _cmd;
3328 char *method_types;
3329 void *_imp;
3330 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003331 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003332 Result += "\nstruct _objc_method {\n";
3333 Result += "\tSEL _cmd;\n";
3334 Result += "\tchar *method_types;\n";
3335 Result += "\tvoid *_imp;\n";
3336 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003337
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003338 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003339 }
Mike Stump11289f42009-09-09 15:08:12 +00003340
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003341 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003342
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003343 /* struct {
3344 struct _objc_method_list *next_method;
3345 int method_count;
3346 struct _objc_method method_list[];
3347 }
3348 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003349 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003350 Result += "\nstatic struct {\n";
3351 Result += "\tstruct _objc_method_list *next_method;\n";
3352 Result += "\tint method_count;\n";
3353 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003354 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003355 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003356 Result += prefix;
3357 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3358 Result += "_METHODS_";
3359 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003360 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003361 Result += IsInstanceMethod ? "inst" : "cls";
3362 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003363 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003364
Chris Lattner31bc07e2007-12-12 07:46:12 +00003365 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003366 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003367 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003368 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003369 Result += "\", \"";
3370 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003371 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003372 Result += MethodInternalNames[*MethodBegin];
3373 Result += "}\n";
3374 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3375 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003376 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003377 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003378 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003379 Result += "\", \"";
3380 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003381 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003382 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003383 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003384 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003385 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003386}
3387
Steve Naroffd9803712009-04-29 16:37:50 +00003388/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003389void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003390RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3391 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003392 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003393
3394 // Output struct protocol_methods holder of method selector and type.
3395 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3396 /* struct protocol_methods {
3397 SEL _cmd;
3398 char *method_types;
3399 }
3400 */
3401 Result += "\nstruct _protocol_methods {\n";
3402 Result += "\tstruct objc_selector *_cmd;\n";
3403 Result += "\tchar *method_types;\n";
3404 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003405
Steve Naroffd9803712009-04-29 16:37:50 +00003406 objc_protocol_methods = true;
3407 }
3408 // Do not synthesize the protocol more than once.
3409 if (ObjCSynthesizedProtocols.count(PDecl))
3410 return;
Mike Stump11289f42009-09-09 15:08:12 +00003411
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003412 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3413 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3414 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003415 /* struct _objc_protocol_method_list {
3416 int protocol_method_count;
3417 struct protocol_methods protocols[];
3418 }
Steve Naroff251084d2008-03-12 01:06:30 +00003419 */
Steve Naroffd9803712009-04-29 16:37:50 +00003420 Result += "\nstatic struct {\n";
3421 Result += "\tint protocol_method_count;\n";
3422 Result += "\tstruct _protocol_methods protocol_methods[";
3423 Result += utostr(NumMethods);
3424 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3425 Result += PDecl->getNameAsString();
3426 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3427 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003428
Steve Naroffd9803712009-04-29 16:37:50 +00003429 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003430 for (ObjCProtocolDecl::instmeth_iterator
3431 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003432 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003433 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003434 Result += "\t ,{{(struct objc_selector *)\"";
3435 else
3436 Result += "\t ,{(struct objc_selector *)\"";
3437 Result += (*I)->getSelector().getAsString().c_str();
3438 std::string MethodTypeString;
3439 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3440 Result += "\", \"";
3441 Result += MethodTypeString;
3442 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003443 }
Steve Naroffd9803712009-04-29 16:37:50 +00003444 Result += "\t }\n};\n";
3445 }
Mike Stump11289f42009-09-09 15:08:12 +00003446
Steve Naroffd9803712009-04-29 16:37:50 +00003447 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003448 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3449 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003450 if (NumMethods > 0) {
3451 /* struct _objc_protocol_method_list {
3452 int protocol_method_count;
3453 struct protocol_methods protocols[];
3454 }
3455 */
3456 Result += "\nstatic struct {\n";
3457 Result += "\tint protocol_method_count;\n";
3458 Result += "\tstruct _protocol_methods protocol_methods[";
3459 Result += utostr(NumMethods);
3460 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3461 Result += PDecl->getNameAsString();
3462 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3463 "{\n\t";
3464 Result += utostr(NumMethods);
3465 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003466
Steve Naroffd9803712009-04-29 16:37:50 +00003467 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003468 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003469 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003470 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003471 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003472 Result += "\t ,{{(struct objc_selector *)\"";
3473 else
3474 Result += "\t ,{(struct objc_selector *)\"";
3475 Result += (*I)->getSelector().getAsString().c_str();
3476 std::string MethodTypeString;
3477 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3478 Result += "\", \"";
3479 Result += MethodTypeString;
3480 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003481 }
Steve Naroffd9803712009-04-29 16:37:50 +00003482 Result += "\t }\n};\n";
3483 }
3484
3485 // Output:
3486 /* struct _objc_protocol {
3487 // Objective-C 1.0 extensions
3488 struct _objc_protocol_extension *isa;
3489 char *protocol_name;
3490 struct _objc_protocol **protocol_list;
3491 struct _objc_protocol_method_list *instance_methods;
3492 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003493 };
Steve Naroffd9803712009-04-29 16:37:50 +00003494 */
3495 static bool objc_protocol = false;
3496 if (!objc_protocol) {
3497 Result += "\nstruct _objc_protocol {\n";
3498 Result += "\tstruct _objc_protocol_extension *isa;\n";
3499 Result += "\tchar *protocol_name;\n";
3500 Result += "\tstruct _objc_protocol **protocol_list;\n";
3501 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3502 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003503 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003504
Steve Naroffd9803712009-04-29 16:37:50 +00003505 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003506 }
Mike Stump11289f42009-09-09 15:08:12 +00003507
Steve Naroffd9803712009-04-29 16:37:50 +00003508 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3509 Result += PDecl->getNameAsString();
3510 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3511 "{\n\t0, \"";
3512 Result += PDecl->getNameAsString();
3513 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003514 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003515 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3516 Result += PDecl->getNameAsString();
3517 Result += ", ";
3518 }
3519 else
3520 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003521 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003522 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3523 Result += PDecl->getNameAsString();
3524 Result += "\n";
3525 }
3526 else
3527 Result += "0\n";
3528 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003529
Steve Naroffd9803712009-04-29 16:37:50 +00003530 // Mark this protocol as having been generated.
3531 if (!ObjCSynthesizedProtocols.insert(PDecl))
3532 assert(false && "protocol already synthesized");
3533
3534}
3535
3536void RewriteObjC::
3537RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3538 const char *prefix, const char *ClassName,
3539 std::string &Result) {
3540 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Steve Naroffd9803712009-04-29 16:37:50 +00003542 for (unsigned i = 0; i != Protocols.size(); i++)
3543 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3544
Chris Lattner388f6e92008-07-21 21:33:21 +00003545 // Output the top lovel protocol meta-data for the class.
3546 /* struct _objc_protocol_list {
3547 struct _objc_protocol_list *next;
3548 int protocol_count;
3549 struct _objc_protocol *class_protocols[];
3550 }
3551 */
3552 Result += "\nstatic struct {\n";
3553 Result += "\tstruct _objc_protocol_list *next;\n";
3554 Result += "\tint protocol_count;\n";
3555 Result += "\tstruct _objc_protocol *class_protocols[";
3556 Result += utostr(Protocols.size());
3557 Result += "];\n} _OBJC_";
3558 Result += prefix;
3559 Result += "_PROTOCOLS_";
3560 Result += ClassName;
3561 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3562 "{\n\t0, ";
3563 Result += utostr(Protocols.size());
3564 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003565
Chris Lattner388f6e92008-07-21 21:33:21 +00003566 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003567 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003568 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003569
Chris Lattner388f6e92008-07-21 21:33:21 +00003570 for (unsigned i = 1; i != Protocols.size(); i++) {
3571 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003572 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003573 Result += "\n";
3574 }
3575 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003576}
3577
Steve Naroffd9803712009-04-29 16:37:50 +00003578
Mike Stump11289f42009-09-09 15:08:12 +00003579/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003580/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003581void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003582 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003583 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003584 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003585 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003586 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003587 CDecl = CDecl->getNextClassCategory())
3588 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3589 break;
Mike Stump11289f42009-09-09 15:08:12 +00003590
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003591 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003592 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003593 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003594
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003595 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003596 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003597 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003598
3599 // If any of our property implementations have associated getters or
3600 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003601 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3602 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003603 Prop != PropEnd; ++Prop) {
3604 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3605 continue;
3606 if (!(*Prop)->getPropertyIvarDecl())
3607 continue;
3608 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3609 if (!PD)
3610 continue;
3611 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3612 InstanceMethods.push_back(Getter);
3613 if (PD->isReadOnly())
3614 continue;
3615 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3616 InstanceMethods.push_back(Setter);
3617 }
3618 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003619 true, "CATEGORY_", FullCategoryName.c_str(),
3620 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003621
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003622 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003623 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003624 false, "CATEGORY_", FullCategoryName.c_str(),
3625 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003626
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003627 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003628 // Null CDecl is case of a category implementation with no category interface
3629 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003630 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3631 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003632 /* struct _objc_category {
3633 char *category_name;
3634 char *class_name;
3635 struct _objc_method_list *instance_methods;
3636 struct _objc_method_list *class_methods;
3637 struct _objc_protocol_list *protocols;
3638 // Objective-C 1.0 extensions
3639 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003640 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003641 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003642 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003643 */
Mike Stump11289f42009-09-09 15:08:12 +00003644
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003645 static bool objc_category = false;
3646 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003647 Result += "\nstruct _objc_category {\n";
3648 Result += "\tchar *category_name;\n";
3649 Result += "\tchar *class_name;\n";
3650 Result += "\tstruct _objc_method_list *instance_methods;\n";
3651 Result += "\tstruct _objc_method_list *class_methods;\n";
3652 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003653 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003654 Result += "\tstruct _objc_property_list *instance_properties;\n";
3655 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003656 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003657 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003658 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3659 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003660 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003661 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003663 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003664 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003665
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003666 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 Result += "\t, (struct _objc_method_list *)"
3668 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3669 Result += FullCategoryName;
3670 Result += "\n";
3671 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003672 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003673 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003674 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003675 Result += "\t, (struct _objc_method_list *)"
3676 "&_OBJC_CATEGORY_CLASS_METHODS_";
3677 Result += FullCategoryName;
3678 Result += "\n";
3679 }
3680 else
3681 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003682
Chris Lattnerf5b77512009-02-20 18:18:36 +00003683 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003684 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003685 Result += FullCategoryName;
3686 Result += "\n";
3687 }
3688 else
3689 Result += "\t, 0\n";
3690 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003691}
3692
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003693/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3694/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003695void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003696 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003697 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003698 if (ivar->isBitField()) {
3699 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3700 // place all bitfields at offset 0.
3701 Result += "0";
3702 } else {
3703 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003705 if (LangOpts.Microsoft)
3706 Result += "_IMPL";
3707 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003708 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003709 Result += ")";
3710 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003711}
3712
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003713//===----------------------------------------------------------------------===//
3714// Meta Data Emission
3715//===----------------------------------------------------------------------===//
3716
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003717void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003718 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003719 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003720
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003721 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003722 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003723 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003724 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003725 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
Chris Lattner30d23e82007-12-12 07:56:42 +00003728 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003729 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003730 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003731 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003732 if (NumIvars > 0) {
3733 static bool objc_ivar = false;
3734 if (!objc_ivar) {
3735 /* struct _objc_ivar {
3736 char *ivar_name;
3737 char *ivar_type;
3738 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003739 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003740 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003741 Result += "\nstruct _objc_ivar {\n";
3742 Result += "\tchar *ivar_name;\n";
3743 Result += "\tchar *ivar_type;\n";
3744 Result += "\tint ivar_offset;\n";
3745 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003746
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003747 objc_ivar = true;
3748 }
3749
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003750 /* struct {
3751 int ivar_count;
3752 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003753 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003754 */
Mike Stump11289f42009-09-09 15:08:12 +00003755 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003756 Result += "\tint ivar_count;\n";
3757 Result += "\tstruct _objc_ivar ivar_list[";
3758 Result += utostr(NumIvars);
3759 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003760 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003761 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003762 "{\n\t";
3763 Result += utostr(NumIvars);
3764 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003765
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003766 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003767 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003768 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003769 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003770 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003771 IV != IVEnd; ++IV)
3772 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003773 IVI = IDecl->ivar_begin();
3774 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003775 } else {
3776 IVI = CDecl->ivar_begin();
3777 IVE = CDecl->ivar_end();
3778 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003779 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003780 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003781 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003782 std::string TmpString, StrEncoding;
3783 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3784 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003785 Result += StrEncoding;
3786 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003787 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003788 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003789 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003790 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003791 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003792 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003793 std::string TmpString, StrEncoding;
3794 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3795 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003796 Result += StrEncoding;
3797 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003798 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003799 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003802 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003803 }
Mike Stump11289f42009-09-09 15:08:12 +00003804
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003805 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003806 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003807 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003808
3809 // If any of our property implementations have associated getters or
3810 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003811 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3812 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003813 Prop != PropEnd; ++Prop) {
3814 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3815 continue;
3816 if (!(*Prop)->getPropertyIvarDecl())
3817 continue;
3818 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3819 if (!PD)
3820 continue;
3821 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3822 InstanceMethods.push_back(Getter);
3823 if (PD->isReadOnly())
3824 continue;
3825 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3826 InstanceMethods.push_back(Setter);
3827 }
3828 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003829 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003830
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003831 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003832 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003833 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003834
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003835 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003836 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3837 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003838
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003839 // Declaration of class/meta-class metadata
3840 /* struct _objc_class {
3841 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003842 const char *super_class_name;
3843 char *name;
3844 long version;
3845 long info;
3846 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003847 struct _objc_ivar_list *ivars;
3848 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003849 struct objc_cache *cache;
3850 struct objc_protocol_list *protocols;
3851 const char *ivar_layout;
3852 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003853 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003854 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003855 static bool objc_class = false;
3856 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003857 Result += "\nstruct _objc_class {\n";
3858 Result += "\tstruct _objc_class *isa;\n";
3859 Result += "\tconst char *super_class_name;\n";
3860 Result += "\tchar *name;\n";
3861 Result += "\tlong version;\n";
3862 Result += "\tlong info;\n";
3863 Result += "\tlong instance_size;\n";
3864 Result += "\tstruct _objc_ivar_list *ivars;\n";
3865 Result += "\tstruct _objc_method_list *methods;\n";
3866 Result += "\tstruct objc_cache *cache;\n";
3867 Result += "\tstruct _objc_protocol_list *protocols;\n";
3868 Result += "\tconst char *ivar_layout;\n";
3869 Result += "\tstruct _objc_class_ext *ext;\n";
3870 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003871 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003872 }
Mike Stump11289f42009-09-09 15:08:12 +00003873
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003874 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003875 ObjCInterfaceDecl *RootClass = 0;
3876 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003877 while (SuperClass) {
3878 RootClass = SuperClass;
3879 SuperClass = SuperClass->getSuperClass();
3880 }
3881 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003882
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003883 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003884 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003885 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003886 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003887 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003888 Result += "\"";
3889
3890 if (SuperClass) {
3891 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003892 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003893 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003894 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003895 Result += "\"";
3896 }
3897 else {
3898 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003899 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003900 Result += "\"";
3901 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003902 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003903 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003904 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003905 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003906 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003907 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003908 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003909 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003910 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003911 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003912 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003913 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003914 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003915 Result += ",0,0\n";
3916 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003917 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003918 Result += "\t,0,0,0,0\n";
3919 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003920
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003921 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003922 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003923 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003924 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003925 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003926 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003927 if (SuperClass) {
3928 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003929 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003930 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003931 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003932 Result += "\"";
3933 }
3934 else {
3935 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003936 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003937 Result += "\"";
3938 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003939 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003940 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003941 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003942 Result += ",0";
3943 else {
3944 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003945 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003947 if (LangOpts.Microsoft)
3948 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003949 Result += ")";
3950 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003951 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003952 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003953 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003954 Result += "\n\t";
3955 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003956 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003957 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003958 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003959 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003960 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003961 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003962 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003963 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003964 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003965 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003966 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003967 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003968 Result += ", 0,0\n";
3969 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003970 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003971 Result += ",0,0,0\n";
3972 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003973}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003974
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003975/// RewriteImplementations - This routine rewrites all method implementations
3976/// and emits meta-data.
3977
Steve Narofff8cfd162008-11-13 20:07:04 +00003978void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003979 int ClsDefCount = ClassImplementation.size();
3980 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003981
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003982 // Rewrite implemented methods
3983 for (int i = 0; i < ClsDefCount; i++)
3984 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003985
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003986 for (int i = 0; i < CatDefCount; i++)
3987 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003988}
Mike Stump11289f42009-09-09 15:08:12 +00003989
Steve Narofff8cfd162008-11-13 20:07:04 +00003990void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3991 int ClsDefCount = ClassImplementation.size();
3992 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003993
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003994 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003995 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003996 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003997
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003998 // For each implemented category, write out all its meta data.
3999 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004000 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004001
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004002 // Write objc_symtab metadata
4003 /*
4004 struct _objc_symtab
4005 {
4006 long sel_ref_cnt;
4007 SEL *refs;
4008 short cls_def_cnt;
4009 short cat_def_cnt;
4010 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004011 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004012 */
Mike Stump11289f42009-09-09 15:08:12 +00004013
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004014 Result += "\nstruct _objc_symtab {\n";
4015 Result += "\tlong sel_ref_cnt;\n";
4016 Result += "\tSEL *refs;\n";
4017 Result += "\tshort cls_def_cnt;\n";
4018 Result += "\tshort cat_def_cnt;\n";
4019 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4020 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004021
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004022 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004023 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004024 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004025 + ", " + utostr(CatDefCount) + "\n";
4026 for (int i = 0; i < ClsDefCount; i++) {
4027 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004028 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004029 Result += "\n";
4030 }
Mike Stump11289f42009-09-09 15:08:12 +00004031
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004032 for (int i = 0; i < CatDefCount; i++) {
4033 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004034 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004035 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004036 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004037 Result += "\n";
4038 }
Mike Stump11289f42009-09-09 15:08:12 +00004039
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004040 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004041
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004042 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004043
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004044 /*
4045 struct _objc_module {
4046 long version;
4047 long size;
4048 const char *name;
4049 struct _objc_symtab *symtab;
4050 }
4051 */
Mike Stump11289f42009-09-09 15:08:12 +00004052
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004053 Result += "\nstruct _objc_module {\n";
4054 Result += "\tlong version;\n";
4055 Result += "\tlong size;\n";
4056 Result += "\tconst char *name;\n";
4057 Result += "\tstruct _objc_symtab *symtab;\n";
4058 Result += "};\n\n";
4059 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004060 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004061 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004062 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004063 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004064
4065 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004066 if (ProtocolExprDecls.size()) {
4067 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4068 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004069 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004070 E = ProtocolExprDecls.end(); I != E; ++I) {
4071 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4072 Result += (*I)->getNameAsString();
4073 Result += " = &_OBJC_PROTOCOL_";
4074 Result += (*I)->getNameAsString();
4075 Result += ";\n";
4076 }
4077 Result += "#pragma data_seg(pop)\n\n";
4078 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004079 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004080 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004081 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4082 Result += "&_OBJC_MODULES;\n";
4083 Result += "#pragma data_seg(pop)\n\n";
4084 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004085}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004086
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004087void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4088 const std::string &Name,
4089 ValueDecl *VD) {
4090 assert(BlockByRefDeclNo.count(VD) &&
4091 "RewriteByRefString: ByRef decl missing");
4092 ResultStr += "struct __Block_byref_" + Name +
4093 "_" + utostr(BlockByRefDeclNo[VD]) ;
4094}
4095
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004096static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4097 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4098 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4099 return false;
4100}
4101
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4103 const char *funcName,
4104 std::string Tag) {
4105 const FunctionType *AFT = CE->getFunctionType();
4106 QualType RT = AFT->getResultType();
4107 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004108 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004110
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004113 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004114 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004115 // block (to reference imported block decl refs).
4116 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117 } else if (BD->param_empty()) {
4118 S += "(" + StructRef + " *__cself)";
4119 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004120 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004121 assert(FT && "SynthesizeBlockFunc: No function proto");
4122 S += '(';
4123 // first add the implicit argument.
4124 S += StructRef + " *__cself, ";
4125 std::string ParamStr;
4126 for (BlockDecl::param_iterator AI = BD->param_begin(),
4127 E = BD->param_end(); AI != E; ++AI) {
4128 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004129 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004130 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004131 if (convertBlockPointerToFunctionPointer(QT))
4132 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004133 else
4134 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004135 S += ParamStr;
4136 }
4137 if (FT->isVariadic()) {
4138 if (!BD->param_empty()) S += ", ";
4139 S += "...";
4140 }
4141 S += ')';
4142 }
4143 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004144
Steve Naroff677ab3a2008-10-27 17:20:55 +00004145 // Create local declarations to avoid rewriting all closure decl ref exprs.
4146 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004147 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004148 E = BlockByRefDecls.end(); I != E; ++I) {
4149 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004150 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004151 std::string TypeString;
4152 RewriteByRefString(TypeString, Name, (*I));
4153 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004154 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004155 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004156 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004157 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004158 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004159 E = BlockByCopyDecls.end(); I != E; ++I) {
4160 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004161 // Handle nested closure invocation. For example:
4162 //
4163 // void (^myImportedClosure)(void);
4164 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004165 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004166 // void (^anotherClosure)(void);
4167 // anotherClosure = ^(void) {
4168 // myImportedClosure(); // import and invoke the closure
4169 // };
4170 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004171 if (isTopLevelBlockPointerType((*I)->getType())) {
4172 RewriteBlockPointerTypeVariable(S, (*I));
4173 S += " = (";
4174 RewriteBlockPointerType(S, (*I)->getType());
4175 S += ")";
4176 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4177 }
4178 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004179 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004180 QualType QT = (*I)->getType();
4181 if (HasLocalVariableExternalStorage(*I))
4182 QT = Context->getPointerType(QT);
4183 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004184 S += Name + " = __cself->" +
4185 (*I)->getNameAsString() + "; // bound by copy\n";
4186 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 }
4188 std::string RewrittenStr = RewrittenBlockExprs[CE];
4189 const char *cstr = RewrittenStr.c_str();
4190 while (*cstr++ != '{') ;
4191 S += cstr;
4192 S += "\n";
4193 return S;
4194}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4197 const char *funcName,
4198 std::string Tag) {
4199 std::string StructRef = "struct " + Tag;
4200 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004201
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 S += funcName;
4203 S += "_block_copy_" + utostr(i);
4204 S += "(" + StructRef;
4205 S += "*dst, " + StructRef;
4206 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004207 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004209 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004210 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004211 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004212 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004213 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004214 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004215 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004216 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004218 S += "}\n";
4219
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 S += "\nstatic void __";
4221 S += funcName;
4222 S += "_block_dispose_" + utostr(i);
4223 S += "(" + StructRef;
4224 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004225 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004226 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004227 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004228 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004229 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004230 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004231 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004232 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 return S;
4236}
4237
Steve Naroff30484702009-12-06 21:14:13 +00004238std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4239 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004240 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004242
Steve Naroff677ab3a2008-10-27 17:20:55 +00004243 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004244 S += " struct " + Desc;
4245 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004246
Steve Naroff30484702009-12-06 21:14:13 +00004247 Constructor += "(void *fp, "; // Invoke function pointer.
4248 Constructor += "struct " + Desc; // Descriptor pointer.
4249 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004250
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 if (BlockDeclRefs.size()) {
4252 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004253 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 E = BlockByCopyDecls.end(); I != E; ++I) {
4255 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004256 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004257 std::string ArgName = "_" + FieldName;
4258 // Handle nested closure invocation. For example:
4259 //
4260 // void (^myImportedBlock)(void);
4261 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004262 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004263 // void (^anotherBlock)(void);
4264 // anotherBlock = ^(void) {
4265 // myImportedBlock(); // import and invoke the closure
4266 // };
4267 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004268 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 S += "struct __block_impl *";
4270 Constructor += ", void *" + ArgName;
4271 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004272 QualType QT = (*I)->getType();
4273 if (HasLocalVariableExternalStorage(*I))
4274 QT = Context->getPointerType(QT);
4275 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4276 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 Constructor += ", " + ArgName;
4278 }
4279 S += FieldName + ";\n";
4280 }
4281 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004282 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004283 E = BlockByRefDecls.end(); I != E; ++I) {
4284 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004285 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286 std::string ArgName = "_" + FieldName;
4287 // Handle nested closure invocation. For example:
4288 //
4289 // void (^myImportedBlock)(void);
4290 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004291 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004292 // void (^anotherBlock)(void);
4293 // anotherBlock = ^(void) {
4294 // myImportedBlock(); // import and invoke the closure
4295 // };
4296 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004297 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298 S += "struct __block_impl *";
4299 Constructor += ", void *" + ArgName;
4300 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004301 std::string TypeString;
4302 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004303 TypeString += " *";
4304 FieldName = TypeString + FieldName;
4305 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004306 Constructor += ", " + ArgName;
4307 }
4308 S += FieldName + "; // by ref\n";
4309 }
4310 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004311 Constructor += ", int flags=0)";
4312 // Initialize all "by copy" arguments.
4313 bool firsTime = true;
4314 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4315 E = BlockByCopyDecls.end(); I != E; ++I) {
4316 std::string Name = (*I)->getNameAsString();
4317 if (firsTime) {
4318 Constructor += " : ";
4319 firsTime = false;
4320 }
4321 else
4322 Constructor += ", ";
4323 if (isTopLevelBlockPointerType((*I)->getType()))
4324 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4325 else
4326 Constructor += Name + "(_" + Name + ")";
4327 }
4328 // Initialize all "by ref" arguments.
4329 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4330 E = BlockByRefDecls.end(); I != E; ++I) {
4331 std::string Name = (*I)->getNameAsString();
4332 if (firsTime) {
4333 Constructor += " : ";
4334 firsTime = false;
4335 }
4336 else
4337 Constructor += ", ";
4338 if (isTopLevelBlockPointerType((*I)->getType()))
4339 Constructor += Name + "((struct __block_impl *)_"
4340 + Name + "->__forwarding)";
4341 else
4342 Constructor += Name + "(_" + Name + "->__forwarding)";
4343 }
4344
4345 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004346 if (GlobalVarDecl)
4347 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4348 else
4349 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004350 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004351
Steve Naroff30484702009-12-06 21:14:13 +00004352 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004353 } else {
4354 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004355 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004356 if (GlobalVarDecl)
4357 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4358 else
4359 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004360 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4361 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 }
4363 Constructor += " ";
4364 Constructor += "}\n";
4365 S += Constructor;
4366 S += "};\n";
4367 return S;
4368}
4369
Steve Naroff30484702009-12-06 21:14:13 +00004370std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4371 std::string ImplTag, int i,
4372 const char *FunName,
4373 unsigned hasCopy) {
4374 std::string S = "\nstatic struct " + DescTag;
4375
4376 S += " {\n unsigned long reserved;\n";
4377 S += " unsigned long Block_size;\n";
4378 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004379 S += " void (*copy)(struct ";
4380 S += ImplTag; S += "*, struct ";
4381 S += ImplTag; S += "*);\n";
4382
4383 S += " void (*dispose)(struct ";
4384 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004385 }
4386 S += "} ";
4387
4388 S += DescTag + "_DATA = { 0, sizeof(struct ";
4389 S += ImplTag + ")";
4390 if (hasCopy) {
4391 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4392 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4393 }
4394 S += "};\n";
4395 return S;
4396}
4397
Steve Naroff677ab3a2008-10-27 17:20:55 +00004398void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004399 const char *FunName) {
4400 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004401 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004402 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004403 bool RewriteSC = (GlobalVarDecl &&
4404 !Blocks.empty() &&
4405 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4406 GlobalVarDecl->getType().getCVRQualifiers());
4407 if (RewriteSC) {
4408 std::string SC(" void __");
4409 SC += GlobalVarDecl->getNameAsString();
4410 SC += "() {}";
4411 InsertText(FunLocStart, SC);
4412 }
4413
Steve Naroff677ab3a2008-10-27 17:20:55 +00004414 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004415 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4416 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004417 // Need to copy-in the inner copied-in variables not actually used in this
4418 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004419 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4420 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4421 ValueDecl *VD = Exp->getDecl();
4422 BlockDeclRefs.push_back(Exp);
4423 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4424 BlockByCopyDeclsPtrSet.insert(VD);
4425 BlockByCopyDecls.push_back(VD);
4426 }
4427 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4428 BlockByRefDeclsPtrSet.insert(VD);
4429 BlockByRefDecls.push_back(VD);
4430 }
4431 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004432
Steve Naroff30484702009-12-06 21:14:13 +00004433 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4434 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004435
Steve Naroff30484702009-12-06 21:14:13 +00004436 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004437
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004438 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004439
Steve Naroff30484702009-12-06 21:14:13 +00004440 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004441
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004442 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004443
4444 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004445 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004446 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004447 }
Steve Naroff30484702009-12-06 21:14:13 +00004448 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4449 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004450 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004451
Steve Naroff677ab3a2008-10-27 17:20:55 +00004452 BlockDeclRefs.clear();
4453 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004454 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004455 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004456 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004457 ImportedBlockDecls.clear();
4458 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004459 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004460 // Must insert any 'const/volatile/static here. Since it has been
4461 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004462 std::string SC;
4463 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4464 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004465 if (GlobalVarDecl->getType().isConstQualified())
4466 SC += "const ";
4467 if (GlobalVarDecl->getType().isVolatileQualified())
4468 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004469 if (GlobalVarDecl->getType().isRestrictQualified())
4470 SC += "restrict ";
4471 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004472 }
4473
Steve Naroff677ab3a2008-10-27 17:20:55 +00004474 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004475 InnerDeclRefsCount.clear();
4476 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004477 RewrittenBlockExprs.clear();
4478}
4479
4480void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4481 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004482 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004483
Steve Naroff677ab3a2008-10-27 17:20:55 +00004484 SynthesizeBlockLiterals(FunLocStart, FuncName);
4485}
4486
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004487static void BuildUniqueMethodName(std::string &Name,
4488 ObjCMethodDecl *MD) {
4489 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4490 Name = IFace->getNameAsCString();
4491 Name += "__" + MD->getSelector().getAsString();
4492 // Convert colons to underscores.
4493 std::string::size_type loc = 0;
4494 while ((loc = Name.find(":", loc)) != std::string::npos)
4495 Name.replace(loc, 1, "_");
4496}
4497
Steve Naroff677ab3a2008-10-27 17:20:55 +00004498void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004499 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4500 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004501 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004502 std::string FuncName;
4503 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004504 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4505}
4506
4507void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4508 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4509 CI != E; ++CI)
4510 if (*CI) {
4511 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4512 GetBlockDeclRefExprs(CBE->getBody());
4513 else
4514 GetBlockDeclRefExprs(*CI);
4515 }
4516 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004517 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004518 // FIXME: Handle enums.
4519 if (!isa<FunctionDecl>(CDRE->getDecl()))
4520 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004521 }
4522 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4523 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4524 BlockDeclRefExpr *BDRE =
4525 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4526 DRE->getLocation(), false);
4527 BlockDeclRefs.push_back(BDRE);
4528 }
4529
Steve Naroff677ab3a2008-10-27 17:20:55 +00004530 return;
4531}
4532
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004533void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4534 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004535 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004536 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4537 CI != E; ++CI)
4538 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004539 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4540 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004541 GetInnerBlockDeclRefExprs(CBE->getBody(),
4542 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004543 InnerContexts);
4544 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004545 else
4546 GetInnerBlockDeclRefExprs(*CI,
4547 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004548 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004549
4550 }
4551 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004552 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004553 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004554 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004555 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004556 }
4557 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4558 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4559 if (Var->isFunctionOrMethodVarDecl())
4560 ImportedLocalExternalDecls.insert(Var);
4561 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004562
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004563 return;
4564}
4565
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004566/// convertFunctionTypeOfBlocks - This routine converts a function type
4567/// whose result type may be a block pointer or whose argument type(s)
4568/// might be block pointers to an equivalent funtion type replacing
4569/// all block pointers to function pointers.
4570QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4571 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4572 // FTP will be null for closures that don't take arguments.
4573 // Generate a funky cast.
4574 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004575 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004576 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004577
4578 if (FTP) {
4579 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4580 E = FTP->arg_type_end(); I && (I != E); ++I) {
4581 QualType t = *I;
4582 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004583 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004584 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004585 ArgTypes.push_back(t);
4586 }
4587 }
4588 QualType FuncType;
4589 // FIXME. Does this work if block takes no argument but has a return type
4590 // which is of block type?
4591 if (HasBlockType)
4592 FuncType = Context->getFunctionType(Res,
4593 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4594 false, false, 0, 0, FunctionType::ExtInfo());
4595 else FuncType = QualType(FT, 0);
4596 return FuncType;
4597}
4598
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004599Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004600 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004601 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004602
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004603 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004604 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004605 } else if (const BlockDeclRefExpr *CDRE =
4606 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004607 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004608 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004609 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004610 }
4611 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4612 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4613 }
4614 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4615 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4616 else if (const ConditionalOperator *CEXPR =
4617 dyn_cast<ConditionalOperator>(BlockExp)) {
4618 Expr *LHSExp = CEXPR->getLHS();
4619 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4620 Expr *RHSExp = CEXPR->getRHS();
4621 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4622 Expr *CONDExp = CEXPR->getCond();
4623 ConditionalOperator *CondExpr =
4624 new (Context) ConditionalOperator(CONDExp,
4625 SourceLocation(), cast<Expr>(LHSStmt),
4626 SourceLocation(), cast<Expr>(RHSStmt),
4627 Exp->getType());
4628 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004629 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4630 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004631 } else {
4632 assert(1 && "RewriteBlockClass: Bad type");
4633 }
4634 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004635 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004636 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004637 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004638 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004639
Abramo Bagnara6150c882010-05-11 21:36:43 +00004640 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004641 SourceLocation(),
4642 &Context->Idents.get("__block_impl"));
4643 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004644
Steve Naroff350b6652008-10-30 10:07:53 +00004645 // Generate a funky cast.
4646 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004647
Steve Naroff350b6652008-10-30 10:07:53 +00004648 // Push the block argument type.
4649 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004650 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004651 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004652 E = FTP->arg_type_end(); I && (I != E); ++I) {
4653 QualType t = *I;
4654 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004655 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004656 ArgTypes.push_back(t);
4657 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004658 }
Steve Naroff350b6652008-10-30 10:07:53 +00004659 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004660 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004661 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4662 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004663 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004664
Steve Naroff350b6652008-10-30 10:07:53 +00004665 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004666
John McCall97513962010-01-15 18:39:57 +00004667 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4668 CastExpr::CK_Unknown,
4669 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004670 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004671 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4672 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004673 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004674
Douglas Gregor91f84212008-12-11 16:49:14 +00004675 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004676 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004677 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004678 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4679 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004680
John McCall97513962010-01-15 18:39:57 +00004681 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4682 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004683 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004684
Steve Naroff350b6652008-10-30 10:07:53 +00004685 llvm::SmallVector<Expr*, 8> BlkExprs;
4686 // Add the implicit argument.
4687 BlkExprs.push_back(BlkCast);
4688 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004689 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004690 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004691 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004692 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004693 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4694 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004695 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004696 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004697}
4698
4699void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004700 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004701 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004702}
4703
Steve Naroffd9803712009-04-29 16:37:50 +00004704// We need to return the rewritten expression to handle cases where the
4705// BlockDeclRefExpr is embedded in another expression being rewritten.
4706// For example:
4707//
4708// int main() {
4709// __block Foo *f;
4710// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004711//
Steve Naroffd9803712009-04-29 16:37:50 +00004712// void (^myblock)() = ^() {
4713// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4714// i = 77;
4715// };
4716//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004717Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004718 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004719 // for each DeclRefExp where BYREFVAR is name of the variable.
4720 ValueDecl *VD;
4721 bool isArrow = true;
4722 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4723 VD = BDRE->getDecl();
4724 else {
4725 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4726 isArrow = false;
4727 }
4728
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004729 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4730 &Context->Idents.get("__forwarding"),
4731 Context->VoidPtrTy, 0,
4732 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004733 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4734 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004735 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004736
4737 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004738 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4739 &Context->Idents.get(Name),
4740 Context->VoidPtrTy, 0,
4741 /*BitWidth=*/0, /*Mutable=*/true);
4742 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004743 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004744
4745
4746
Steve Narofff26a1d42009-02-02 17:19:26 +00004747 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004748 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4749 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004750 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004751 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004752}
4753
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004754// Rewrites the imported local variable V with external storage
4755// (static, extern, etc.) as *V
4756//
4757Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4758 ValueDecl *VD = DRE->getDecl();
4759 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4760 if (!ImportedLocalExternalDecls.count(Var))
4761 return DRE;
4762 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4763 DRE->getType(), DRE->getLocation());
4764 // Need parens to enforce precedence.
4765 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4766 Exp);
4767 ReplaceStmt(DRE, PE);
4768 return PE;
4769}
4770
Steve Naroffc989a7b2008-11-03 23:29:32 +00004771void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4772 SourceLocation LocStart = CE->getLParenLoc();
4773 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004774
4775 // Need to avoid trying to rewrite synthesized casts.
4776 if (LocStart.isInvalid())
4777 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004778 // Need to avoid trying to rewrite casts contained in macros.
4779 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4780 return;
Mike Stump11289f42009-09-09 15:08:12 +00004781
Steve Naroff677ab3a2008-10-27 17:20:55 +00004782 const char *startBuf = SM->getCharacterData(LocStart);
4783 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004784 QualType QT = CE->getType();
4785 const Type* TypePtr = QT->getAs<Type>();
4786 if (isa<TypeOfExprType>(TypePtr)) {
4787 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4788 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4789 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004790 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004791 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004792 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004793 return;
4794 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004795 // advance the location to startArgList.
4796 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Steve Naroff677ab3a2008-10-27 17:20:55 +00004798 while (*argPtr++ && (argPtr < endBuf)) {
4799 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004800 case '^':
4801 // Replace the '^' with '*'.
4802 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004803 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004804 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004805 }
4806 }
4807 return;
4808}
4809
4810void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4811 SourceLocation DeclLoc = FD->getLocation();
4812 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Steve Naroff677ab3a2008-10-27 17:20:55 +00004814 // We have 1 or more arguments that have closure pointers.
4815 const char *startBuf = SM->getCharacterData(DeclLoc);
4816 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004817
Steve Naroff677ab3a2008-10-27 17:20:55 +00004818 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004819
Steve Naroff677ab3a2008-10-27 17:20:55 +00004820 parenCount++;
4821 // advance the location to startArgList.
4822 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4823 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004824
Steve Naroff677ab3a2008-10-27 17:20:55 +00004825 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004826
Steve Naroff677ab3a2008-10-27 17:20:55 +00004827 while (*argPtr++ && parenCount) {
4828 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004829 case '^':
4830 // Replace the '^' with '*'.
4831 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004832 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004833 break;
4834 case '(':
4835 parenCount++;
4836 break;
4837 case ')':
4838 parenCount--;
4839 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004840 }
4841 }
4842 return;
4843}
4844
4845bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004846 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004848 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004849 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004850 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004851 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004852 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004853 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004854 }
4855 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004856 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004857 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004858 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004859 return true;
4860 }
4861 return false;
4862}
4863
Ted Kremenek5a201952009-02-07 01:47:29 +00004864void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4865 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004866 const char *argPtr = strchr(Name, '(');
4867 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004868
Steve Naroff677ab3a2008-10-27 17:20:55 +00004869 LParen = argPtr; // output the start.
4870 argPtr++; // skip past the left paren.
4871 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004872
Steve Naroff677ab3a2008-10-27 17:20:55 +00004873 while (*argPtr && parenCount) {
4874 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004875 case '(': parenCount++; break;
4876 case ')': parenCount--; break;
4877 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004878 }
4879 if (parenCount) argPtr++;
4880 }
4881 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4882 RParen = argPtr; // output the end
4883}
4884
4885void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4886 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4887 RewriteBlockPointerFunctionArgs(FD);
4888 return;
Mike Stump11289f42009-09-09 15:08:12 +00004889 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004890 // Handle Variables and Typedefs.
4891 SourceLocation DeclLoc = ND->getLocation();
4892 QualType DeclT;
4893 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4894 DeclT = VD->getType();
4895 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4896 DeclT = TDD->getUnderlyingType();
4897 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4898 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004899 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004900 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004901
Steve Naroff677ab3a2008-10-27 17:20:55 +00004902 const char *startBuf = SM->getCharacterData(DeclLoc);
4903 const char *endBuf = startBuf;
4904 // scan backward (from the decl location) for the end of the previous decl.
4905 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4906 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004907
Steve Naroff677ab3a2008-10-27 17:20:55 +00004908 // *startBuf != '^' if we are dealing with a pointer to function that
4909 // may take block argument types (which will be handled below).
4910 if (*startBuf == '^') {
4911 // Replace the '^' with '*', computing a negative offset.
4912 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004913 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004914 }
4915 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4916 // Replace the '^' with '*' for arguments.
4917 DeclLoc = ND->getLocation();
4918 startBuf = SM->getCharacterData(DeclLoc);
4919 const char *argListBegin, *argListEnd;
4920 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4921 while (argListBegin < argListEnd) {
4922 if (*argListBegin == '^') {
4923 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004924 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004925 }
4926 argListBegin++;
4927 }
4928 }
4929 return;
4930}
4931
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004932
4933/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4934/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4935/// struct Block_byref_id_object *src) {
4936/// _Block_object_assign (&_dest->object, _src->object,
4937/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4938/// [|BLOCK_FIELD_IS_WEAK]) // object
4939/// _Block_object_assign(&_dest->object, _src->object,
4940/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4941/// [|BLOCK_FIELD_IS_WEAK]) // block
4942/// }
4943/// And:
4944/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4945/// _Block_object_dispose(_src->object,
4946/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4947/// [|BLOCK_FIELD_IS_WEAK]) // object
4948/// _Block_object_dispose(_src->object,
4949/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4950/// [|BLOCK_FIELD_IS_WEAK]) // block
4951/// }
4952
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004953std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4954 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004955 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004956 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004957 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004958 CopyDestroyCache.insert(flag);
4959 S = "static void __Block_byref_id_object_copy_";
4960 S += utostr(flag);
4961 S += "(void *dst, void *src) {\n";
4962
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004963 // offset into the object pointer is computed as:
4964 // void * + void* + int + int + void* + void *
4965 unsigned IntSize =
4966 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4967 unsigned VoidPtrSize =
4968 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4969
4970 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4971 S += " _Block_object_assign((char*)dst + ";
4972 S += utostr(offset);
4973 S += ", *(void * *) ((char*)src + ";
4974 S += utostr(offset);
4975 S += "), ";
4976 S += utostr(flag);
4977 S += ");\n}\n";
4978
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004979 S += "static void __Block_byref_id_object_dispose_";
4980 S += utostr(flag);
4981 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004982 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4983 S += utostr(offset);
4984 S += "), ";
4985 S += utostr(flag);
4986 S += ");\n}\n";
4987 return S;
4988}
4989
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004990/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4991/// the declaration into:
4992/// struct __Block_byref_ND {
4993/// void *__isa; // NULL for everything except __weak pointers
4994/// struct __Block_byref_ND *__forwarding;
4995/// int32_t __flags;
4996/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004997/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4998/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004999/// typex ND;
5000/// };
5001///
5002/// It then replaces declaration of ND variable with:
5003/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5004/// __size=sizeof(struct __Block_byref_ND),
5005/// ND=initializer-if-any};
5006///
5007///
5008void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005009 // Insert declaration for the function in which block literal is
5010 // used.
5011 if (CurFunctionDeclToDeclareForBlock)
5012 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005013 int flag = 0;
5014 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005015 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005016 if (DeclLoc.isInvalid())
5017 // If type location is missing, it is because of missing type (a warning).
5018 // Use variable's location which is good for this case.
5019 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005020 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005021 SourceLocation X = ND->getLocEnd();
5022 X = SM->getInstantiationLoc(X);
5023 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005024 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005025 std::string ByrefType;
5026 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005027 ByrefType += " {\n";
5028 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005029 RewriteByRefString(ByrefType, Name, ND);
5030 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005031 ByrefType += " int __flags;\n";
5032 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005033 // Add void *__Block_byref_id_object_copy;
5034 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005035 QualType Ty = ND->getType();
5036 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5037 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005038 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5039 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005040 }
5041
5042 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005043 ByrefType += " " + Name + ";\n";
5044 ByrefType += "};\n";
5045 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005046 SourceLocation FunLocStart;
5047 if (CurFunctionDef)
5048 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5049 else {
5050 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5051 FunLocStart = CurMethodDef->getLocStart();
5052 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005053 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005054 if (Ty.isObjCGCWeak()) {
5055 flag |= BLOCK_FIELD_IS_WEAK;
5056 isa = 1;
5057 }
5058
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005059 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005060 flag = BLOCK_BYREF_CALLER;
5061 QualType Ty = ND->getType();
5062 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5063 if (Ty->isBlockPointerType())
5064 flag |= BLOCK_FIELD_IS_BLOCK;
5065 else
5066 flag |= BLOCK_FIELD_IS_OBJECT;
5067 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005068 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005069 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005070 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005071
5072 // struct __Block_byref_ND ND =
5073 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5074 // initializer-if-any};
5075 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005076 unsigned flags = 0;
5077 if (HasCopyAndDispose)
5078 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005079 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005080 ByrefType.clear();
5081 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005082 std::string ForwardingCastType("(");
5083 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005084 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005085 ByrefType += " " + Name + " = {(void*)";
5086 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005087 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005088 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005089 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005090 ByrefType += "sizeof(";
5091 RewriteByRefString(ByrefType, Name, ND);
5092 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005093 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005094 ByrefType += ", __Block_byref_id_object_copy_";
5095 ByrefType += utostr(flag);
5096 ByrefType += ", __Block_byref_id_object_dispose_";
5097 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005098 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005099 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005100 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005101 }
5102 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005103 SourceLocation startLoc;
5104 Expr *E = ND->getInit();
5105 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5106 startLoc = ECE->getLParenLoc();
5107 else
5108 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005109 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005110 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005111 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005112 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005113 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005114 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005115 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005116 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005117 ByrefType += "sizeof(";
5118 RewriteByRefString(ByrefType, Name, ND);
5119 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005120 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005121 ByrefType += "__Block_byref_id_object_copy_";
5122 ByrefType += utostr(flag);
5123 ByrefType += ", __Block_byref_id_object_dispose_";
5124 ByrefType += utostr(flag);
5125 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005126 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005127 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005128
5129 // Complete the newly synthesized compound expression by inserting a right
5130 // curly brace before the end of the declaration.
5131 // FIXME: This approach avoids rewriting the initializer expression. It
5132 // also assumes there is only one declarator. For example, the following
5133 // isn't currently supported by this routine (in general):
5134 //
5135 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5136 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005137 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5138 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005139 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5140 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005141 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005142
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005143 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005144 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005145 return;
5146}
5147
Mike Stump11289f42009-09-09 15:08:12 +00005148void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005149 // Add initializers for any closure decl refs.
5150 GetBlockDeclRefExprs(Exp->getBody());
5151 if (BlockDeclRefs.size()) {
5152 // Unique all "by copy" declarations.
5153 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005154 if (!BlockDeclRefs[i]->isByRef()) {
5155 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5156 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5157 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5158 }
5159 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005160 // Unique all "by ref" declarations.
5161 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5162 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005163 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5164 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5165 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5166 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005167 }
5168 // Find any imported blocks...they will need special attention.
5169 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005170 if (BlockDeclRefs[i]->isByRef() ||
5171 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005172 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005173 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005174 }
5175}
5176
Steve Narofff4b992a2008-10-28 20:29:00 +00005177FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5178 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005179 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005180 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00005181 ID, FType, 0, FunctionDecl::Extern,
5182 FunctionDecl::None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005183}
5184
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005185Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5186 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005187 Blocks.push_back(Exp);
5188
5189 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005190
5191 // Add inner imported variables now used in current block.
5192 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005193 if (!InnerBlockDeclRefs.empty()) {
5194 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5195 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5196 ValueDecl *VD = Exp->getDecl();
5197 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005198 // We need to save the copied-in variables in nested
5199 // blocks because it is needed at the end for some of the API generations.
5200 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005201 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5202 BlockDeclRefs.push_back(Exp);
5203 BlockByCopyDeclsPtrSet.insert(VD);
5204 BlockByCopyDecls.push_back(VD);
5205 }
5206 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5207 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5208 BlockDeclRefs.push_back(Exp);
5209 BlockByRefDeclsPtrSet.insert(VD);
5210 BlockByRefDecls.push_back(VD);
5211 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005212 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005213 // Find any imported blocks...they will need special attention.
5214 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5215 if (InnerBlockDeclRefs[i]->isByRef() ||
5216 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5217 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5218 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005219 }
5220 InnerDeclRefsCount.push_back(countOfInnerDecls);
5221
Steve Narofff4b992a2008-10-28 20:29:00 +00005222 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005223
Steve Narofff4b992a2008-10-28 20:29:00 +00005224 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005225 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005226 else if (CurMethodDef)
5227 BuildUniqueMethodName(FuncName, CurMethodDef);
5228 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005229 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005230
Steve Narofff4b992a2008-10-28 20:29:00 +00005231 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005232
Steve Narofff4b992a2008-10-28 20:29:00 +00005233 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5234 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005235
Steve Narofff4b992a2008-10-28 20:29:00 +00005236 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005237 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5238 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005239
5240 FunctionDecl *FD;
5241 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005242
Steve Narofff4b992a2008-10-28 20:29:00 +00005243 // Simulate a contructor call...
5244 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005245 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005246
Steve Narofff4b992a2008-10-28 20:29:00 +00005247 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005248
Steve Naroffe2514232008-10-29 21:23:59 +00005249 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00005250 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005251 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5252 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005253 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5254 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005255 InitExprs.push_back(castExpr);
5256
Steve Naroff30484702009-12-06 21:14:13 +00005257 // Initialize the block descriptor.
5258 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005259
Steve Naroff30484702009-12-06 21:14:13 +00005260 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5261 &Context->Idents.get(DescData.c_str()),
5262 Context->VoidPtrTy, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005263 VarDecl::Static, VarDecl::None);
Steve Naroff30484702009-12-06 21:14:13 +00005264 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5265 new (Context) DeclRefExpr(NewVD,
5266 Context->VoidPtrTy, SourceLocation()),
5267 UnaryOperator::AddrOf,
5268 Context->getPointerType(Context->VoidPtrTy),
5269 SourceLocation());
5270 InitExprs.push_back(DescRefExpr);
5271
Steve Narofff4b992a2008-10-28 20:29:00 +00005272 // Add initializers for any closure decl refs.
5273 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005274 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005275 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005276 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005277 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005278 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005279 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00005280 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005281 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005282 if (HasLocalVariableExternalStorage(*I)) {
5283 QualType QT = (*I)->getType();
5284 QT = Context->getPointerType(QT);
5285 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5286 SourceLocation());
5287 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005288 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00005289 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005290 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005291 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5292 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005293 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00005294 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005295 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005296 if (HasLocalVariableExternalStorage(*I)) {
5297 QualType QT = (*I)->getType();
5298 QT = Context->getPointerType(QT);
5299 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5300 SourceLocation());
5301 }
5302
Steve Narofff4b992a2008-10-28 20:29:00 +00005303 }
Mike Stump11289f42009-09-09 15:08:12 +00005304 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005305 }
5306 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005307 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005308 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005309 ValueDecl *ND = (*I);
5310 std::string Name(ND->getNameAsString());
5311 std::string RecName;
5312 RewriteByRefString(RecName, Name, ND);
5313 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5314 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005315 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005316 SourceLocation(), II);
5317 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5318 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5319
Chris Lattner86d7d912008-11-24 03:54:41 +00005320 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005321 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5322 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005323 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005324 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005325 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005326 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005327 }
5328 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005329 if (ImportedBlockDecls.size()) {
5330 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5331 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005332 unsigned IntSize =
5333 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005334 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5335 Context->IntTy, SourceLocation());
5336 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005337 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005338 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5339 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00005340 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005341 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005342 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005343 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5344 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005345 BlockDeclRefs.clear();
5346 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005347 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005348 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005349 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005350 ImportedBlockDecls.clear();
5351 return NewRep;
5352}
5353
5354//===----------------------------------------------------------------------===//
5355// Function Body / Expression rewriting
5356//===----------------------------------------------------------------------===//
5357
Steve Naroff4588d0f2008-12-04 16:24:46 +00005358// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5359// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5360// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5361// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5362// Since the rewriter isn't capable of rewriting rewritten code, it's important
5363// we get this right.
5364void RewriteObjC::CollectPropertySetters(Stmt *S) {
5365 // Perform a bottom up traversal of all children.
5366 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5367 CI != E; ++CI)
5368 if (*CI)
5369 CollectPropertySetters(*CI);
5370
5371 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5372 if (BinOp->isAssignmentOp()) {
5373 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5374 PropSetters[PRE] = BinOp;
5375 }
5376 }
5377}
5378
Steve Narofff4b992a2008-10-28 20:29:00 +00005379Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005380 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005381 isa<DoStmt>(S) || isa<ForStmt>(S))
5382 Stmts.push_back(S);
5383 else if (isa<ObjCForCollectionStmt>(S)) {
5384 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005385 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005386 }
Mike Stump11289f42009-09-09 15:08:12 +00005387
Steve Narofff4b992a2008-10-28 20:29:00 +00005388 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005389
Steve Narofff4b992a2008-10-28 20:29:00 +00005390 // Perform a bottom up rewrite of all children.
5391 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5392 CI != E; ++CI)
5393 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005394 Stmt *newStmt;
5395 Stmt *S = (*CI);
5396 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5397 Expr *OldBase = IvarRefExpr->getBase();
5398 bool replaced = false;
5399 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5400 if (replaced) {
5401 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5402 ReplaceStmt(OldBase, IRE->getBase());
5403 else
5404 ReplaceStmt(S, newStmt);
5405 }
5406 }
5407 else
5408 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005409 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005410 *CI = newStmt;
5411 }
Mike Stump11289f42009-09-09 15:08:12 +00005412
Steve Narofff4b992a2008-10-28 20:29:00 +00005413 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005414 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005415 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5416 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005417 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005418 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005419 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005420 // Rewrite the block body in place.
5421 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005422 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005423 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005424 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005425 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005426
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005427 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5428
Steve Narofff4b992a2008-10-28 20:29:00 +00005429 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005430 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005431 return blockTranscribed;
5432 }
5433 // Handle specific things.
5434 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5435 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005436
Steve Naroff4588d0f2008-12-04 16:24:46 +00005437 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5438 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5439 if (BinOp) {
5440 // Because the rewriter doesn't allow us to rewrite rewritten code,
5441 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005442 DisableReplaceStmt = true;
5443 // Save the source range. Even if we disable the replacement, the
5444 // rewritten node will have been inserted into the tree. If the synthesized
5445 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005446 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005447 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5448 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005449 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005450 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005451 //
5452 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5453 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5454 // to see the original expression). Consider this example:
5455 //
5456 // Foo *obj1, *obj2;
5457 //
5458 // obj1.i = [obj2 rrrr];
5459 //
5460 // 'BinOp' for the previous expression looks like:
5461 //
5462 // (BinaryOperator 0x231ccf0 'int' '='
5463 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5464 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5465 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5466 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5467 //
5468 // 'newStmt' represents the rewritten message expression. For example:
5469 //
5470 // (CallExpr 0x231d300 'id':'struct objc_object *'
5471 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5472 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5473 // (CStyleCastExpr 0x231d220 'void *'
5474 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5475 //
5476 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5477 // can be used as the setter argument. ReplaceStmt() will still 'see'
5478 // the original RHS (since we haven't altered BinOp).
5479 //
Mike Stump11289f42009-09-09 15:08:12 +00005480 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005481 // node. As a result, we now leak the original AST nodes.
5482 //
Steve Naroff08628db2008-12-09 12:56:34 +00005483 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005484 } else {
5485 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005486 }
5487 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005488 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5489 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005490
Steve Narofff4b992a2008-10-28 20:29:00 +00005491 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5492 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005493
Steve Narofff4b992a2008-10-28 20:29:00 +00005494 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005495#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005496 // Before we rewrite it, put the original message expression in a comment.
5497 SourceLocation startLoc = MessExpr->getLocStart();
5498 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005499
Steve Narofff4b992a2008-10-28 20:29:00 +00005500 const char *startBuf = SM->getCharacterData(startLoc);
5501 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005502
Steve Narofff4b992a2008-10-28 20:29:00 +00005503 std::string messString;
5504 messString += "// ";
5505 messString.append(startBuf, endBuf-startBuf+1);
5506 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005507
5508 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005509 // InsertText(clang::SourceLocation, char const*, unsigned int).
5510 // InsertText(startLoc, messString.c_str(), messString.size());
5511 // Tried this, but it didn't work either...
5512 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005513#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005514 return RewriteMessageExpr(MessExpr);
5515 }
Mike Stump11289f42009-09-09 15:08:12 +00005516
Steve Narofff4b992a2008-10-28 20:29:00 +00005517 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5518 return RewriteObjCTryStmt(StmtTry);
5519
5520 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5521 return RewriteObjCSynchronizedStmt(StmtTry);
5522
5523 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5524 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005525
Steve Narofff4b992a2008-10-28 20:29:00 +00005526 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5527 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005528
5529 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005530 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005531 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005532 OrigStmtRange.getEnd());
5533 if (BreakStmt *StmtBreakStmt =
5534 dyn_cast<BreakStmt>(S))
5535 return RewriteBreakStmt(StmtBreakStmt);
5536 if (ContinueStmt *StmtContinueStmt =
5537 dyn_cast<ContinueStmt>(S))
5538 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005539
5540 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005541 // and cast exprs.
5542 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5543 // FIXME: What we're doing here is modifying the type-specifier that
5544 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005545 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005546 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5547 // the context of an ObjCForCollectionStmt. For example:
5548 // NSArray *someArray;
5549 // for (id <FooProtocol> index in someArray) ;
5550 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5551 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005552 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005553 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005554
Steve Narofff4b992a2008-10-28 20:29:00 +00005555 // Blocks rewrite rules.
5556 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5557 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005558 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005559 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005560 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005561 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005562 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005563 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005564 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005565 if (VD->hasAttr<BlocksAttr>()) {
5566 static unsigned uniqueByrefDeclCount = 0;
5567 assert(!BlockByRefDeclNo.count(ND) &&
5568 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5569 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005570 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005571 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005572 else
5573 RewriteTypeOfDecl(VD);
5574 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005575 }
5576 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005577 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005578 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005579 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005580 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5581 }
5582 }
5583 }
Mike Stump11289f42009-09-09 15:08:12 +00005584
Steve Narofff4b992a2008-10-28 20:29:00 +00005585 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5586 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005587
5588 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005589 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5590 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005591 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5592 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005593 && "Statement stack mismatch");
5594 Stmts.pop_back();
5595 }
5596 // Handle blocks rewriting.
5597 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5598 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005599 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005600 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005601 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5602 ValueDecl *VD = DRE->getDecl();
5603 if (VD->hasAttr<BlocksAttr>())
5604 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005605 if (HasLocalVariableExternalStorage(VD))
5606 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005607 }
5608
Steve Narofff4b992a2008-10-28 20:29:00 +00005609 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005610 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005611 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005612 ReplaceStmt(S, BlockCall);
5613 return BlockCall;
5614 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005615 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005616 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005617 RewriteCastExpr(CE);
5618 }
5619#if 0
5620 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005621 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5622 ICE->getSubExpr(),
5623 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005624 // Get the new text.
5625 std::string SStr;
5626 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005627 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005628 const std::string &Str = Buf.str();
5629
5630 printf("CAST = %s\n", &Str[0]);
5631 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5632 delete S;
5633 return Replacement;
5634 }
5635#endif
5636 // Return this stmt unmodified.
5637 return S;
5638}
5639
Steve Naroffe70a52a2009-12-05 15:55:59 +00005640void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5641 for (RecordDecl::field_iterator i = RD->field_begin(),
5642 e = RD->field_end(); i != e; ++i) {
5643 FieldDecl *FD = *i;
5644 if (isTopLevelBlockPointerType(FD->getType()))
5645 RewriteBlockPointerDecl(FD);
5646 if (FD->getType()->isObjCQualifiedIdType() ||
5647 FD->getType()->isObjCQualifiedInterfaceType())
5648 RewriteObjCQualifiedInterfaceTypes(FD);
5649 }
5650}
5651
Steve Narofff4b992a2008-10-28 20:29:00 +00005652/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5653/// main file of the input.
5654void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005656 if (FD->isOverloadedOperator())
5657 return;
Mike Stump11289f42009-09-09 15:08:12 +00005658
Steve Narofff4b992a2008-10-28 20:29:00 +00005659 // Since function prototypes don't have ParmDecl's, we check the function
5660 // prototype. This enables us to rewrite function declarations and
5661 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005662 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005663
Sebastian Redla7b98a72009-04-26 20:35:05 +00005664 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005665 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005666 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005667 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005668 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005669 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005670 Body =
5671 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5672 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005673 CurrentBody = 0;
5674 if (PropParentMap) {
5675 delete PropParentMap;
5676 PropParentMap = 0;
5677 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005678 // This synthesizes and inserts the block "impl" struct, invoke function,
5679 // and any copy/dispose helper functions.
5680 InsertBlockLiteralsWithinFunction(FD);
5681 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005682 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005683 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005684 return;
5685 }
5686 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005687 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005688 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005689 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005690 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005691 Body =
5692 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5693 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005694 CurrentBody = 0;
5695 if (PropParentMap) {
5696 delete PropParentMap;
5697 PropParentMap = 0;
5698 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005699 InsertBlockLiteralsWithinMethod(MD);
5700 CurMethodDef = 0;
5701 }
5702 }
5703 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5704 ClassImplementation.push_back(CI);
5705 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5706 CategoryImplementation.push_back(CI);
5707 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5708 RewriteForwardClassDecl(CD);
5709 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5710 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005711 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005712 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005713 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005714 CheckFunctionPointerDecl(VD->getType(), VD);
5715 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005716 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005717 RewriteCastExpr(CE);
5718 }
5719 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005720 } else if (VD->getType()->isRecordType()) {
5721 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5722 if (RD->isDefinition())
5723 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005724 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005725 if (VD->getInit()) {
5726 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005727 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005728 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005729 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005730 CurrentBody = 0;
5731 if (PropParentMap) {
5732 delete PropParentMap;
5733 PropParentMap = 0;
5734 }
Mike Stump11289f42009-09-09 15:08:12 +00005735 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005736 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005737 GlobalVarDecl = 0;
5738
5739 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005740 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005741 RewriteCastExpr(CE);
5742 }
5743 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005744 return;
5745 }
5746 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005747 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005748 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005749 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005750 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5751 return;
5752 }
5753 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005754 if (RD->isDefinition())
5755 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005756 return;
5757 }
5758 // Nothing yet.
5759}
5760
Chris Lattnercf169832009-03-28 04:11:33 +00005761void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005762 if (Diags.hasErrorOccurred())
5763 return;
Mike Stump11289f42009-09-09 15:08:12 +00005764
Steve Narofff4b992a2008-10-28 20:29:00 +00005765 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005766
Steve Naroffd9803712009-04-29 16:37:50 +00005767 // Here's a great place to add any extra declarations that may be needed.
5768 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005769 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005770 E = ProtocolExprDecls.end(); I != E; ++I)
5771 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5772
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005773 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005774 if (ClassImplementation.size() || CategoryImplementation.size())
5775 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005776
Steve Narofff4b992a2008-10-28 20:29:00 +00005777 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5778 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005779 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005780 Rewrite.getRewriteBufferFor(MainFileID)) {
5781 //printf("Changed:\n");
5782 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5783 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005784 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005785 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005786
Steve Naroffd9803712009-04-29 16:37:50 +00005787 if (ClassImplementation.size() || CategoryImplementation.size() ||
5788 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005789 // Rewrite Objective-c meta data*
5790 std::string ResultStr;
5791 SynthesizeMetaDataIntoBuffer(ResultStr);
5792 // Emit metadata.
5793 *OutFile << ResultStr;
5794 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005795 OutFile->flush();
5796}