blob: 8cdb55a0c1c60ff954e98b49ac9b9b83b36e96dc [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarc1b17292010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000042 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000096
Steve Naroffa397efd2007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Steve Naroffd9803712009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Steve Narofff9e7c902008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000120
Steve Naroff00a31762008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff677ab3a2008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4588d0f2008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff22216db2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000151
Steve Naroff677ab3a2008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Steve Naroff08628db2008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000157
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattnere99c8322007-10-11 00:43:27 +0000159 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattner3c799d72007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattnercf169832009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000176
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000179
Steve Naroff22216db2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182
Steve Naroff08628db2008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff22216db2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000195 }
Steve Naroff08628db2008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000198 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner1780a852008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000255 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner3c799d72007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Steve Naroff1042ff32008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Fariborz Jahanian74405b02011-02-24 21:29:21 +0000301 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump11289f42009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000303 Expr **args, unsigned nargs,
304 SourceLocation StartLoc=SourceLocation(),
305 SourceLocation EndLoc=SourceLocation());
306 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
307 SourceLocation StartLoc=SourceLocation(),
308 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000311 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000313 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000314 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000315 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000316 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000317 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000318 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000319 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000320 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner3c799d72007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000327
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000335 llvm::StringRef prefix,
336 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +0000337 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Steve Naroffd9803712009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000340 llvm::StringRef prefix,
341 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000344 llvm::StringRef prefix,
345 llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +0000346 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000348 std::string &Result);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000349 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000350 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000351 void RewriteImplementations();
352 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Steve Naroff677ab3a2008-10-27 17:20:55 +0000354 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000355 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
359 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000360
361 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000362 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000363 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000365 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000366 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000367 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000368
369 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000370 llvm::StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000371 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000372 llvm::StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000373 std::string SynthesizeBlockImpl(BlockExpr *CE,
374 std::string Tag, std::string Desc);
375 std::string SynthesizeBlockDescriptor(std::string DescTag,
376 std::string ImplTag,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000377 int i, llvm::StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000378 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000379 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000380 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +0000381 llvm::StringRef FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000382 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000386 void GetInnerBlockDeclRefExprs(Stmt *S,
387 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000388 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 // We avoid calling Type::isBlockPointerType(), since it operates on the
391 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000392 bool isTopLevelBlockPointerType(QualType T) {
393 return isa<BlockPointerType>(T);
394 }
Mike Stump11289f42009-09-09 15:08:12 +0000395
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000396 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
397 /// to a function pointer type and upon success, returns true; false
398 /// otherwise.
399 bool convertBlockPointerToFunctionPointer(QualType &T) {
400 if (isTopLevelBlockPointerType(T)) {
401 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
402 T = Context->getPointerType(BPT->getPointeeType());
403 return true;
404 }
405 return false;
406 }
407
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000408 void convertToUnqualifiedObjCType(QualType &T) {
409 if (T->isObjCQualifiedIdType())
410 T = Context->getObjCIdType();
411 else if (T->isObjCQualifiedClassType())
412 T = Context->getObjCClassType();
413 else if (T->isObjCObjectPointerType() &&
414 T->getPointeeType()->isObjCQualifiedInterfaceType())
415 T = Context->getObjCIdType();
416 }
417
Steve Naroff677ab3a2008-10-27 17:20:55 +0000418 // FIXME: This predicate seems like it would be useful to add to ASTContext.
419 bool isObjCType(QualType T) {
420 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
421 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Steve Naroff677ab3a2008-10-27 17:20:55 +0000423 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000424
Steve Naroff677ab3a2008-10-27 17:20:55 +0000425 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
426 OCT == Context->getCanonicalType(Context->getObjCClassType()))
427 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000429 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000431 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000432 return true;
433 }
434 return false;
435 }
436 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000437 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000438 void GetExtentOfArgList(const char *Name, const char *&LParen,
439 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000440 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Daniel Dunbar56df9772010-08-17 22:39:59 +0000442 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
444 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Steve Naroffd9803712009-04-29 16:37:50 +0000446 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000447 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000448 if (From[i] == '"')
449 To += "\\\"";
450 else
451 To += From[i];
452 }
453 }
John McCalldb40c7f2010-12-14 08:05:40 +0000454
455 QualType getSimpleFunctionType(QualType result,
456 const QualType *args,
457 unsigned numArgs,
458 bool variadic = false) {
459 FunctionProtoType::ExtProtoInfo fpi;
460 fpi.Variadic = variadic;
461 return Context->getFunctionType(result, args, numArgs, fpi);
462 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000463 };
John McCall97513962010-01-15 18:39:57 +0000464
465 // Helper function: create a CStyleCastExpr with trivial type source info.
466 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +0000467 CastKind Kind, Expr *E) {
John McCall97513962010-01-15 18:39:57 +0000468 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +0000469 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallcf142162010-08-07 06:22:56 +0000470 SourceLocation(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +0000471 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000472}
473
Mike Stump11289f42009-09-09 15:08:12 +0000474void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
475 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000476 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000477 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000479 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000480 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000481 // All the args are checked/rewritten. Don't call twice!
482 RewriteBlockPointerDecl(D);
483 break;
484 }
485 }
486}
487
488void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000490 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000491 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000492}
493
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000494static bool IsHeaderFile(const std::string &Filename) {
495 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000496
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000497 if (DotPos == std::string::npos) {
498 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000499 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000502 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
503 // C header: .h
504 // C++ header: .hh or .H;
505 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000506}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000507
Eli Friedman94cf21e2009-05-18 22:20:00 +0000508RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000509 Diagnostic &D, const LangOptions &LOpts,
510 bool silenceMacroWarn)
511 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
512 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000513 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000514 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000515 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000516 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000517 "rewriter doesn't support user-specified control flow semantics "
518 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000519}
520
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000521ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
522 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000523 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000524 const LangOptions &LOpts,
525 bool SilenceRewriteMacroWarning) {
526 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000527}
Chris Lattnere99c8322007-10-11 00:43:27 +0000528
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000529void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000530 Context = &context;
531 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000532 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000533 MsgSendFunctionDecl = 0;
534 MsgSendSuperFunctionDecl = 0;
535 MsgSendStretFunctionDecl = 0;
536 MsgSendSuperStretFunctionDecl = 0;
537 MsgSendFpretFunctionDecl = 0;
538 GetClassFunctionDecl = 0;
539 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000540 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000541 SelGetUidFunctionDecl = 0;
542 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000543 ConstantStringClassReference = 0;
544 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000545 CurMethodDef = 0;
546 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000547 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000548 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000549 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000550 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000551 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000552 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000553 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000554 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000555 PropParentMap = 0;
556 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000557 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000558 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000559
Chris Lattner187f6262008-01-31 19:38:44 +0000560 // Get the ID and start/end of the main file.
561 MainFileID = SM->getMainFileID();
562 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
563 MainFileStart = MainBuf->getBufferStart();
564 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000565
Chris Lattner184e65d2009-04-14 23:22:57 +0000566 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattner187f6262008-01-31 19:38:44 +0000568 // declaring objc_selector outside the parameter list removes a silly
569 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000570 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000571 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000573 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000575 if (LangOpts.Microsoft) {
576 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000577 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
578 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000580 }
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
583 Preamble += "typedef struct objc_object Protocol;\n";
584 Preamble += "#define _REWRITER_typedef_Protocol\n";
585 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000586 if (LangOpts.Microsoft) {
587 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
588 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
589 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000590 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000592 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000594 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000596 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000598 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000600 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000602 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000603 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
604 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000606 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
611 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000612 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000613 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
616 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000617 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
618 Preamble += "struct __objcFastEnumerationState {\n\t";
619 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000620 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000621 Preamble += "unsigned long *mutationsPtr;\n\t";
622 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000624 Preamble += "#define __FASTENUMERATIONSTATE\n";
625 Preamble += "#endif\n";
626 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
627 Preamble += "struct __NSConstantStringImpl {\n";
628 Preamble += " int *isa;\n";
629 Preamble += " int flags;\n";
630 Preamble += " char *str;\n";
631 Preamble += " long length;\n";
632 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000633 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
634 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
635 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000636 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000637 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000638 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
639 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000640 // Blocks preamble.
641 Preamble += "#ifndef BLOCK_IMPL\n";
642 Preamble += "#define BLOCK_IMPL\n";
643 Preamble += "struct __block_impl {\n";
644 Preamble += " void *isa;\n";
645 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000646 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000647 Preamble += " void *FuncPtr;\n";
648 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000649 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000650 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000651 Preamble += "extern \"C\" __declspec(dllexport) "
652 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000653 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
655 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
656 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
658 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
660 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
661 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000662 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000663 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000664 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
665 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000666 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000667 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000668 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000669 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000670 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000671 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000672 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000673 Preamble += "#define __weak\n";
674 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000675 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
676 // as this avoids warning in any 64bit/32bit compilation model.
677 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000678}
679
680
Chris Lattner3c799d72007-10-24 17:06:59 +0000681//===----------------------------------------------------------------------===//
682// Top Level Driver Code
683//===----------------------------------------------------------------------===//
684
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000685void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000686 if (Diags.hasErrorOccurred())
687 return;
688
Chris Lattner0bd1c972007-10-16 21:07:07 +0000689 // Two cases: either the decl could be in the main file, or it could be in a
690 // #included file. If the former, rewrite it now. If the later, check to see
691 // if we rewrote the #include/#import.
692 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000693 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner0bd1c972007-10-16 21:07:07 +0000695 // If this is for a builtin, ignore it.
696 if (Loc.isInvalid()) return;
697
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000698 // Look for built-in declarations that we need to refer during the rewrite.
699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000700 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000701 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000702 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000703 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000704 ConstantStringClassReference = FVD;
705 return;
706 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000707 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000708 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000709 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000710 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000711 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000712 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000713 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000714 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000715 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000716 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
717 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000718 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
719 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000720 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000721 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000722 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000726}
727
Chris Lattner3c799d72007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000734 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000738
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000750 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffc038b3a2008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
780 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000784
Steve Naroff9af94912008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000788
Steve Naroff003d00e2008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000802 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
824 Context->PrintingPolicy);
825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
838 SynthesizeIvarOffsetComputation(OID, Getr);
839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000845 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000848 return;
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Naroff9af94912008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000868 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000871 Setr += ", ";
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
873 Setr += "0, ";
874 else
875 Setr += "1, ";
876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000884 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000887}
Chris Lattner16a0de42007-10-11 18:38:32 +0000888
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000889void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = ClassDecl->getLocation();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattner3c799d72007-10-24 17:06:59 +0000895 // Translate to typedef's that forward reference structs with the same name
896 // as the class. As a convenience, we include the original declaration
897 // as a comment.
898 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000899 typedefString += "// @class ";
900 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
901 I != E; ++I) {
902 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
903 typedefString += ForwardDecl->getNameAsString();
904 if (I+1 != E)
905 typedefString += ", ";
906 else
907 typedefString += ";\n";
908 }
909
Chris Lattner9ee23b72009-02-20 18:04:31 +0000910 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
911 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000912 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000913 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000914 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000915 typedefString += "\n";
916 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000917 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000918 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000919 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000920 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000921 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Steve Naroff574440f2007-10-24 22:48:43 +0000924 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000925 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000926}
927
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000928void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000929 // When method is a synthesized one, such as a getter/setter there is
930 // nothing to rewrite.
931 if (Method->isSynthesized())
932 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000933 SourceLocation LocStart = Method->getLocStart();
934 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner88ea93e2009-02-04 01:06:56 +0000936 if (SM->getInstantiationLineNumber(LocEnd) >
937 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000938 InsertText(LocStart, "#if 0\n");
939 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000940 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000941 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000942 }
943}
944
Mike Stump11289f42009-09-09 15:08:12 +0000945void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000946 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000947
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000948 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000949 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000950}
951
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000952void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000953 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000954
Steve Naroff5448cf62007-10-30 13:30:57 +0000955 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000956 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000957
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000958 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
959 E = CatDecl->prop_end(); I != E; ++I)
960 RewriteProperty(*I);
961
Mike Stump11289f42009-09-09 15:08:12 +0000962 for (ObjCCategoryDecl::instmeth_iterator
963 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000964 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000965 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000966 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000967 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000968 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000969 RewriteMethodDeclaration(*I);
970
Steve Naroff5448cf62007-10-30 13:30:57 +0000971 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000972 ReplaceText(CatDecl->getAtEndRange().getBegin(),
973 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000974}
975
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000976void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000977 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000978
Steve Narofff921385f2007-10-30 16:42:30 +0000979 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000980 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000981
982 for (ObjCProtocolDecl::instmeth_iterator
983 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000984 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000985 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000986 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000987 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000988 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000989 RewriteMethodDeclaration(*I);
990
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +0000991 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
992 E = PDecl->prop_end(); I != E; ++I)
993 RewriteProperty(*I);
994
Steve Narofff921385f2007-10-30 16:42:30 +0000995 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000996 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000997 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +0000998
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000999 // Must comment out @optional/@required
1000 const char *startBuf = SM->getCharacterData(LocStart);
1001 const char *endBuf = SM->getCharacterData(LocEnd);
1002 for (const char *p = startBuf; p < endBuf; p++) {
1003 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001004 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001005 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001006
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001007 }
1008 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001009 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001010 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001011
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001012 }
1013 }
Steve Narofff921385f2007-10-30 16:42:30 +00001014}
1015
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001016void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001017 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001018 if (LocStart.isInvalid())
1019 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001020 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001021 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001022}
1023
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001024void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1025 const FunctionType *&FPRetType) {
1026 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001027 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001028 else if (T->isFunctionPointerType() ||
1029 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001030 // needs special handling, since pointer-to-functions have special
1031 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001032 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001033 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001035 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001036 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001037 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001038 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001039 ResultStr += FPRetType->getResultType().getAsString(
1040 Context->PrintingPolicy);
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001041 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001042 }
1043 } else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001044 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001045}
1046
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001047void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1048 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001049 std::string &ResultStr) {
1050 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1051 const FunctionType *FPRetType = 0;
1052 ResultStr += "\nstatic ";
1053 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001054 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001055
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001056 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001057 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Douglas Gregorffca3a22009-01-09 17:18:27 +00001059 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001060 NameStr += "_I_";
1061 else
1062 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001063
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001064 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001065 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001066
1067 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001068 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001069 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001070 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001073 {
1074 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001075 int len = selString.size();
1076 for (int i = 0; i < len; i++)
1077 if (selString[i] == ':')
1078 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001079 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001081 // Remember this name for metadata emission
1082 MethodInternalNames[OMD] = NameStr;
1083 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085 // Rewrite arguments
1086 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001087
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001089 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001090 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001092 if (!LangOpts.Microsoft) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001093 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001094 ResultStr += "struct ";
1095 }
1096 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001097 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001098 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001099 }
1100 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001101 ResultStr += Context->getObjCClassType().getAsString(
1102 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00001103
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001104 ResultStr += " self, ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001105 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001106 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001107
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001108 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001109 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1110 E = OMD->param_end(); PI != E; ++PI) {
1111 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001113 if (PDecl->getType()->isObjCQualifiedIdType()) {
1114 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001115 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001116 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001117 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001118 QualType QT = PDecl->getType();
1119 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1120 if (convertBlockPointerToFunctionPointer(QT))
1121 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1122 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001123 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001124 ResultStr += Name;
1125 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001126 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001127 if (OMD->isVariadic())
1128 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001129 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001130
Steve Naroffb067bbd2008-07-16 14:40:40 +00001131 if (FPRetType) {
1132 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001133
Steve Naroffb067bbd2008-07-16 14:40:40 +00001134 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001135 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001136 ResultStr += "(";
1137 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1138 if (i) ResultStr += ", ";
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001139 std::string ParamStr = FT->getArgType(i).getAsString(
1140 Context->PrintingPolicy);
Steve Naroffb067bbd2008-07-16 14:40:40 +00001141 ResultStr += ParamStr;
1142 }
1143 if (FT->isVariadic()) {
1144 if (FT->getNumArgs()) ResultStr += ", ";
1145 ResultStr += "...";
1146 }
1147 ResultStr += ")";
1148 } else {
1149 ResultStr += "()";
1150 }
1151 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001152}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001153void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001154 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1155 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001156
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001157 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001158
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001159 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001160 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1161 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001162 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001163 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001164 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001165 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001166 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001167 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001168
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001169 const char *startBuf = SM->getCharacterData(LocStart);
1170 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001171 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001174 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001175 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1176 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001177 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001178 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001179 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001180 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001181 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001182 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001184 const char *startBuf = SM->getCharacterData(LocStart);
1185 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001186 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001187 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001188 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001189 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001190 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001191 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001192 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001193 }
1194
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001195 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001196}
1197
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001198void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001199 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001200 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001201 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001202 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001204 ResultStr += "\n";
1205 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001207 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001208 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001210 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001211 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001212 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001213 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001214 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001215
1216 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001217 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001218 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001219 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001220 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001221 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001222 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001223 for (ObjCInterfaceDecl::classmeth_iterator
1224 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001225 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001226 RewriteMethodDeclaration(*I);
1227
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001228 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001229 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001231}
1232
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001233Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +00001234 SourceRange SrcRange) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001235 ObjCMethodDecl *OMD = 0;
1236 QualType Ty;
1237 Selector Sel;
Duncan Sands3a02f3e2010-10-20 08:21:16 +00001238 Stmt *Receiver = 0;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001239 bool Super = false;
1240 QualType SuperTy;
1241 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001242 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001243 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroff4588d0f2008-12-04 16:24:46 +00001244 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCallb7bd14f2010-12-02 01:19:52 +00001245 if (ObjCPropertyRefExpr *PropRefExpr =
1246 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001247 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001248 if (PropRefExpr->isExplicitProperty()) {
1249 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1250 OMD = PDecl->getSetterMethodDecl();
1251 Ty = PDecl->getType();
1252 Sel = PDecl->getSetterName();
1253 } else {
1254 OMD = PropRefExpr->getImplicitPropertySetter();
1255 Sel = OMD->getSelector();
1256 Ty = PropRefExpr->getType();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001257 }
John McCallb7bd14f2010-12-02 01:19:52 +00001258 Super = PropRefExpr->isSuperReceiver();
1259 if (!Super) {
1260 Receiver = PropRefExpr->getBase();
1261 } else {
1262 SuperTy = PropRefExpr->getSuperReceiverType();
1263 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001264 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001265 }
1266
1267 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroff4588d0f2008-12-04 16:24:46 +00001268 llvm::SmallVector<Expr *, 1> ExprVec;
1269 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001271 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001272 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001273 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001274 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001275 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001276 /*FIXME?*/SourceLocation(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001277 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001278 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001279 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001280 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001281 &ExprVec[0], 1,
1282 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001283 else {
1284 // FIXME. Refactor this into common code with that in
1285 // RewritePropertyOrImplicitGetter
1286 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1287 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1288 if (PropGetters[Exp])
1289 // This allows us to handle chain/nested property/implicit getters.
1290 Receiver = PropGetters[Exp];
1291
Douglas Gregor9a129192010-04-21 00:45:42 +00001292 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001293 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001294 Expr::getValueKindForType(Ty),
Douglas Gregor9a129192010-04-21 00:45:42 +00001295 /*FIXME: */SourceLocation(),
1296 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001297 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001298 &ExprVec[0], 1,
1299 /*FIXME:*/SourceLocation());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001300 }
Steve Naroff4588d0f2008-12-04 16:24:46 +00001301 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Steve Naroff4588d0f2008-12-04 16:24:46 +00001303 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001304 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001305 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001306 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1307 // to things that stay around.
1308 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001309 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001310}
1311
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001312Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1313 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Narofff326f402008-12-03 00:56:33 +00001314 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenekc81155e2010-10-19 23:10:22 +00001315 Stmt *Receiver = 0;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001316 ObjCMethodDecl *OMD = 0;
1317 QualType Ty;
1318 Selector Sel;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001319 bool Super = false;
1320 QualType SuperTy;
1321 SourceLocation SuperLocation;
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001322 SourceLocation SelectorLoc;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001323 if (ObjCPropertyRefExpr *PropRefExpr =
1324 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001325 SelectorLoc = PropRefExpr->getLocation();
John McCallb7bd14f2010-12-02 01:19:52 +00001326 if (PropRefExpr->isExplicitProperty()) {
1327 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1328 OMD = PDecl->getGetterMethodDecl();
1329 Ty = PDecl->getType();
1330 Sel = PDecl->getGetterName();
1331 } else {
1332 OMD = PropRefExpr->getImplicitPropertyGetter();
1333 Sel = OMD->getSelector();
1334 Ty = PropRefExpr->getType();
1335 }
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001336 Super = PropRefExpr->isSuperReceiver();
1337 if (!Super)
1338 Receiver = PropRefExpr->getBase();
1339 else {
John McCallb7bd14f2010-12-02 01:19:52 +00001340 SuperTy = PropRefExpr->getSuperReceiverType();
1341 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001342 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001343 }
1344
1345 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1346
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001347 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001348 if (Super)
Douglas Gregor9a129192010-04-21 00:45:42 +00001349 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001350 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001351 Expr::getValueKindForType(Ty),
Fariborz Jahanianf2890fc2011-02-26 00:33:41 +00001352 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001353 SuperLocation,
Douglas Gregor9a129192010-04-21 00:45:42 +00001354 /*IsInstanceSuper=*/true,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001355 SuperTy,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001356 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001357 0, 0,
Fariborz Jahanianf2890fc2011-02-26 00:33:41 +00001358 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001359 else {
1360 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1361 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1362 if (PropGetters[Exp])
1363 // This allows us to handle chain/nested property/implicit getters.
1364 Receiver = PropGetters[Exp];
Douglas Gregor9a129192010-04-21 00:45:42 +00001365 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001366 Ty.getNonReferenceType(),
John McCall7decc9e2010-11-18 06:31:45 +00001367 Expr::getValueKindForType(Ty),
Fariborz Jahanianf2890fc2011-02-26 00:33:41 +00001368 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor9a129192010-04-21 00:45:42 +00001369 cast<Expr>(Receiver),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001370 Sel, SelectorLoc, OMD,
Douglas Gregor9a129192010-04-21 00:45:42 +00001371 0, 0,
Fariborz Jahanianf2890fc2011-02-26 00:33:41 +00001372 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001373 }
Steve Narofff326f402008-12-03 00:56:33 +00001374
Fariborz Jahanianf2890fc2011-02-26 00:33:41 +00001375 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1376 MsgExpr->getLocEnd());
Steve Naroff1042ff32008-12-08 16:43:47 +00001377
1378 if (!PropParentMap)
1379 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001380 bool NestedPropertyRef = false;
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001381 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001382 ImplicitCastExpr*ICE=0;
1383 if (Parent)
1384 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1385 assert((ICE->getCastKind() == CK_GetObjCProperty)
1386 && "RewritePropertyOrImplicitGetter");
1387 Parent = PropParentMap->getParent(Parent);
1388 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1389 }
1390 if (NestedPropertyRef) {
Steve Naroff1042ff32008-12-08 16:43:47 +00001391 // We stash away the ReplacingStmt since actually doing the
1392 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian83e7d5a2010-12-04 21:22:13 +00001393 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001394 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1395 // to things that stay around.
1396 Context->Deallocate(MsgExpr);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001397 return PropOrGetterRefExpr; // return the original...
Steve Naroff1042ff32008-12-08 16:43:47 +00001398 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001399 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001400 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001401 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1402 // to things that stay around.
1403 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001404 return ReplacingStmt;
1405 }
Steve Narofff326f402008-12-03 00:56:33 +00001406}
1407
Mike Stump11289f42009-09-09 15:08:12 +00001408Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001409 SourceLocation OrigStart,
1410 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001411 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001412 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001413 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001414 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001415 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001416 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001417 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001418 // lookup which class implements the instance variable.
1419 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001420 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001421 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001422 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001423
Steve Naroffb1c02372008-05-08 17:52:16 +00001424 // Synthesize an explicit cast to gain access to the ivar.
1425 std::string RecName = clsDeclared->getIdentifier()->getName();
1426 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001427 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001428 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001429 SourceLocation(), SourceLocation(),
1430 II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001431 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1432 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001433 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001434 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001435 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001436 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001437 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCall7decc9e2010-11-18 06:31:45 +00001438 IV->getBase()->getLocEnd(),
1439 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001440 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001441 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001442 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001443 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCall7decc9e2010-11-18 06:31:45 +00001444 IV->getLocation(),
1445 D->getType(),
1446 VK_LValue, OK_Ordinary);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00001447 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001448 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001449 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001450 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001451 // Cannot delete IV->getBase(), since PE points to it.
1452 // Replace the old base with the cast. This is important when doing
1453 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001454 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001455 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001456 }
Steve Naroff24840f62008-04-18 21:55:08 +00001457 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001458 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001459
Steve Naroff29ce4e52008-05-06 23:20:07 +00001460 // Explicit ivar refs need to have a cast inserted.
1461 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001462 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCall424cec92011-01-19 06:33:43 +00001463 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001464 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001465 // lookup which class implements the instance variable.
1466 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001467 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001468 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001469 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001470
Steve Naroff29ce4e52008-05-06 23:20:07 +00001471 // Synthesize an explicit cast to gain access to the ivar.
1472 std::string RecName = clsDeclared->getIdentifier()->getName();
1473 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001474 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001475 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001476 SourceLocation(), SourceLocation(),
1477 II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001478 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1479 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001480 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCallf608deb2010-11-15 09:46:46 +00001481 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001482 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001483 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001484 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001485 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001486 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001487 // Cannot delete IV->getBase(), since PE points to it.
1488 // Replace the old base with the cast. This is important when doing
1489 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001490 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001491 return IV;
1492 }
Steve Naroff05caa482007-11-15 11:33:00 +00001493 }
Steve Naroff24840f62008-04-18 21:55:08 +00001494 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001495}
1496
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001497Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall8322c3a2011-02-13 04:07:26 +00001498 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001499 if (*CI) {
1500 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1501 if (newStmt)
1502 *CI = newStmt;
1503 }
1504 }
1505 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1506 SourceRange OrigStmtRange = S->getSourceRange();
1507 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1508 replaced);
1509 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001510 }
1511 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1512 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1513 return newStmt;
1514 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001515 return S;
1516}
1517
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001518/// SynthCountByEnumWithState - To print:
1519/// ((unsigned int (*)
1520/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001521/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001523/// "countByEnumeratingWithState:objects:count:"),
1524/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001525/// (id *)items, (unsigned int)16)
1526///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001527void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001528 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1529 "id *, unsigned int))(void *)objc_msgSend)";
1530 buf += "\n\t\t";
1531 buf += "((id)l_collection,\n\t\t";
1532 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1533 buf += "\n\t\t";
1534 buf += "&enumState, "
1535 "(id *)items, (unsigned int)16)";
1536}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001537
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001538/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1539/// statement to exit to its outer synthesized loop.
1540///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001541Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001542 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1543 return S;
1544 // replace break with goto __break_label
1545 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001546
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001547 SourceLocation startLoc = S->getLocStart();
1548 buf = "goto __break_label_";
1549 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001550 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001551
1552 return 0;
1553}
1554
1555/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1556/// statement to continue with its inner synthesized loop.
1557///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001558Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001559 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1560 return S;
1561 // replace continue with goto __continue_label
1562 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001563
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001564 SourceLocation startLoc = S->getLocStart();
1565 buf = "goto __continue_label_";
1566 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001567 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001568
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001569 return 0;
1570}
1571
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001572/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001573/// It rewrites:
1574/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001576/// Into:
1577/// {
Mike Stump11289f42009-09-09 15:08:12 +00001578/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001580/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001581/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001582/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001583/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001584/// if (limit) {
1585/// unsigned long startMutations = *enumState.mutationsPtr;
1586/// do {
1587/// unsigned long counter = 0;
1588/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001589/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001590/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001591/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001592/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001593/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001594/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001595/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001596/// objects:items count:16]);
1597/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001598/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001599/// }
1600/// else
1601/// elem = nil;
1602/// }
1603///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001604Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001605 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001606 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001607 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001608 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001609 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001610 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001611
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001612 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar56df9772010-08-17 22:39:59 +00001614 llvm::StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001615 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001616 std::string buf;
1617 buf = "\n{\n\t";
1618 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1619 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001620 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001621 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001622 if (ElementType->isObjCQualifiedIdType() ||
1623 ElementType->isObjCQualifiedInterfaceType())
1624 // Simply use 'id' for all qualified types.
1625 elementTypeAsString = "id";
1626 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001627 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001628 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001629 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001630 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001631 buf += elementName;
1632 buf += ";\n\t";
1633 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001634 else {
1635 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001636 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001637 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1638 if (VD->getType()->isObjCQualifiedIdType() ||
1639 VD->getType()->isObjCQualifiedInterfaceType())
1640 // Simply use 'id' for all qualified types.
1641 elementTypeAsString = "id";
1642 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001643 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001644 }
Mike Stump11289f42009-09-09 15:08:12 +00001645
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001646 // struct __objcFastEnumerationState enumState = { 0 };
1647 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1648 // id items[16];
1649 buf += "id items[16];\n\t";
1650 // id l_collection = (id)
1651 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001652 // Find start location of 'collection' the hard way!
1653 const char *startCollectionBuf = startBuf;
1654 startCollectionBuf += 3; // skip 'for'
1655 startCollectionBuf = strchr(startCollectionBuf, '(');
1656 startCollectionBuf++; // skip '('
1657 // find 'in' and skip it.
1658 while (*startCollectionBuf != ' ' ||
1659 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1660 (*(startCollectionBuf+3) != ' ' &&
1661 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1662 startCollectionBuf++;
1663 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001664
1665 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001666 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001667 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001668 SourceLocation rightParenLoc = S->getRParenLoc();
1669 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1670 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001671 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001672
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001673 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1674 // objects:items count:16];
1675 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001676 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001677 // ((unsigned int (*)
1678 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001679 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001681 // "countByEnumeratingWithState:objects:count:"),
1682 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001683 // (id *)items, (unsigned int)16);
1684 buf += "unsigned long limit =\n\t\t";
1685 SynthCountByEnumWithState(buf);
1686 buf += ";\n\t";
1687 /// if (limit) {
1688 /// unsigned long startMutations = *enumState.mutationsPtr;
1689 /// do {
1690 /// unsigned long counter = 0;
1691 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001692 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001693 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001694 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001695 buf += "if (limit) {\n\t";
1696 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1697 buf += "do {\n\t\t";
1698 buf += "unsigned long counter = 0;\n\t\t";
1699 buf += "do {\n\t\t\t";
1700 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1701 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1702 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001703 buf += " = (";
1704 buf += elementTypeAsString;
1705 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001706 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001707 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001708
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001709 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001710 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001711 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001712 /// objects:items count:16]);
1713 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001714 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001715 /// }
1716 /// else
1717 /// elem = nil;
1718 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001719 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001720 buf = ";\n\t";
1721 buf += "__continue_label_";
1722 buf += utostr(ObjCBcLabelNo.back());
1723 buf += ": ;";
1724 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001725 buf += "} while (counter < limit);\n\t";
1726 buf += "} while (limit = ";
1727 SynthCountByEnumWithState(buf);
1728 buf += ");\n\t";
1729 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001730 buf += " = ((";
1731 buf += elementTypeAsString;
1732 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001733 buf += "__break_label_";
1734 buf += utostr(ObjCBcLabelNo.back());
1735 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001736 buf += "}\n\t";
1737 buf += "else\n\t\t";
1738 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001739 buf += " = ((";
1740 buf += elementTypeAsString;
1741 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001742 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001743
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001744 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001745 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001746 if (isa<CompoundStmt>(S->getBody())) {
1747 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001748 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001749 } else {
1750 /* Need to treat single statements specially. For example:
1751 *
1752 * for (A *a in b) if (stuff()) break;
1753 * for (A *a in b) xxxyy;
1754 *
1755 * The following code simply scans ahead to the semi to find the actual end.
1756 */
1757 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1758 const char *semiBuf = strchr(stmtBuf, ';');
1759 assert(semiBuf && "Can't find ';'");
1760 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001761 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001762 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001763 Stmts.pop_back();
1764 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001765 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001766}
1767
Mike Stump11289f42009-09-09 15:08:12 +00001768/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001769/// This routine rewrites @synchronized(expr) stmt;
1770/// into:
1771/// objc_sync_enter(expr);
1772/// @try stmt @finally { objc_sync_exit(expr); }
1773///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001774Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001775 // Get the start location and compute the semi location.
1776 SourceLocation startLoc = S->getLocStart();
1777 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001779 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001780
1781 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001782 buf = "objc_sync_enter((id)";
1783 const char *lparenBuf = startBuf;
1784 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001785 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001786 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1787 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001788 // been rewritten! (which implies the SourceLocation's are invalid).
1789 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001790 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001791 while (*endBuf != ')') endBuf--;
1792 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001793 buf = ");\n";
1794 // declare a new scope with two variables, _stack and _rethrow.
1795 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1796 buf += "int buf[18/*32-bit i386*/];\n";
1797 buf += "char *pointers[4];} _stack;\n";
1798 buf += "id volatile _rethrow = 0;\n";
1799 buf += "objc_exception_try_enter(&_stack);\n";
1800 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001801 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001802 startLoc = S->getSynchBody()->getLocEnd();
1803 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001804
Steve Naroffad7013b2008-08-19 13:04:19 +00001805 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001806 SourceLocation lastCurlyLoc = startLoc;
1807 buf = "}\nelse {\n";
1808 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001809 buf += "}\n";
1810 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001811 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001812
1813 std::string syncBuf;
1814 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001815 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00001816 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00001817 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001818 std::string syncExprBufS;
1819 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001820 syncExpr->printPretty(syncExprBuf, *Context, 0,
1821 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001822 syncBuf += syncExprBuf.str();
1823 syncBuf += ");";
1824
1825 buf += syncBuf;
1826 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001827 buf += "}\n";
1828 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001829
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001830 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001831
1832 bool hasReturns = false;
1833 HasReturnStmts(S->getSynchBody(), hasReturns);
1834 if (hasReturns)
1835 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1836
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001837 return 0;
1838}
1839
Steve Naroffec60b432009-12-05 21:43:12 +00001840void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1841{
Steve Naroff6d6da252008-12-05 17:03:39 +00001842 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001843 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001844 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001845 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001846
Steve Naroffec60b432009-12-05 21:43:12 +00001847 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001848 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001849 TryFinallyContainsReturnDiag);
1850 }
1851 return;
1852}
1853
Steve Naroffec60b432009-12-05 21:43:12 +00001854void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1855{
1856 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001857 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001858 if (*CI)
1859 HasReturnStmts(*CI, hasReturns);
1860
1861 if (isa<ReturnStmt>(S))
1862 hasReturns = true;
1863 return;
1864}
1865
1866void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1867 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001868 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001869 if (*CI) {
1870 RewriteTryReturnStmts(*CI);
1871 }
1872 if (isa<ReturnStmt>(S)) {
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1878 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1879
1880 std::string buf;
1881 buf = "{ objc_exception_try_exit(&_stack); return";
1882
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001883 ReplaceText(startLoc, 6, buf);
1884 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001885 }
1886 return;
1887}
1888
1889void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1890 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001891 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001892 if (*CI) {
1893 RewriteSyncReturnStmts(*CI, syncExitBuf);
1894 }
1895 if (isa<ReturnStmt>(S)) {
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 const char *semiBuf = strchr(startBuf, ';');
1900 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1901 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1902
1903 std::string buf;
1904 buf = "{ objc_exception_try_exit(&_stack);";
1905 buf += syncExitBuf;
1906 buf += " return";
1907
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001908 ReplaceText(startLoc, 6, buf);
1909 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001910 }
1911 return;
1912}
1913
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001915 // Get the start location and compute the semi location.
1916 SourceLocation startLoc = S->getLocStart();
1917 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Steve Naroffbf478ec2007-11-07 04:08:17 +00001919 assert((*startBuf == '@') && "bogus @try location");
1920
1921 std::string buf;
1922 // declare a new scope with two variables, _stack and _rethrow.
1923 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1924 buf += "int buf[18/*32-bit i386*/];\n";
1925 buf += "char *pointers[4];} _stack;\n";
1926 buf += "id volatile _rethrow = 0;\n";
1927 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001928 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001929
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001930 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001931
Steve Naroffbf478ec2007-11-07 04:08:17 +00001932 startLoc = S->getTryBody()->getLocEnd();
1933 startBuf = SM->getCharacterData(startLoc);
1934
1935 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001936
Steve Naroffbf478ec2007-11-07 04:08:17 +00001937 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001938 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001939 startLoc = startLoc.getFileLocWithOffset(1);
1940 buf = " /* @catch begin */ else {\n";
1941 buf += " id _caught = objc_exception_extract(&_stack);\n";
1942 buf += " objc_exception_try_enter (&_stack);\n";
1943 buf += " if (_setjmp(_stack.buf))\n";
1944 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1945 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001946
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001947 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001948 } else { /* no catch list */
1949 buf = "}\nelse {\n";
1950 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1951 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001952 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001953 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001954 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001955 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1956 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001957 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958
Douglas Gregor96c79492010-04-23 22:50:49 +00001959 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001960 buf = "if ("; // we are generating code for the first catch clause
1961 else
1962 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001963 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001964 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001965
Steve Naroffbf478ec2007-11-07 04:08:17 +00001966 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001967
Steve Naroffbf478ec2007-11-07 04:08:17 +00001968 const char *lParenLoc = strchr(startBuf, '(');
1969
Douglas Gregor96c79492010-04-23 22:50:49 +00001970 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001971 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001972 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001973 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1974 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001975 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001976 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001977 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001978
Steve Naroffedb5bc62008-02-01 20:02:07 +00001979 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001980 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001981 } else if (catchDecl) {
1982 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001983 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001984 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001985 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001986 } else if (const ObjCObjectPointerType *Ptr =
1987 t->getAs<ObjCObjectPointerType>()) {
1988 // Should be a pointer to a class.
1989 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1990 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001991 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001992 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001993 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001994 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001995 }
1996 }
1997 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001998 lastCatchBody = Catch->getCatchBody();
1999 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00002000 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2001 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2002 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2003 assert((*rParenBuf == ')') && "bogus @catch paren location");
2004 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002005
Mike Stump11289f42009-09-09 15:08:12 +00002006 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00002007 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002008 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00002009 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002010 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002011 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00002012 }
2013 // Complete the catch list...
2014 if (lastCatchBody) {
2015 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002016 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2017 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00002018
Steve Naroff4adbe312008-09-11 15:29:03 +00002019 // Insert the last (implicit) else clause *before* the right curly brace.
2020 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2021 buf = "} /* last catch end */\n";
2022 buf += "else {\n";
2023 buf += " _rethrow = _caught;\n";
2024 buf += " objc_exception_try_exit(&_stack);\n";
2025 buf += "} } /* @catch end */\n";
2026 if (!S->getFinallyStmt())
2027 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002028 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Steve Naroffbf478ec2007-11-07 04:08:17 +00002030 // Set lastCurlyLoc
2031 lastCurlyLoc = lastCatchBody->getLocEnd();
2032 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002033 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00002034 startLoc = finalStmt->getLocStart();
2035 startBuf = SM->getCharacterData(startLoc);
2036 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00002037
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002038 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00002039
Steve Naroffbf478ec2007-11-07 04:08:17 +00002040 Stmt *body = finalStmt->getFinallyBody();
2041 SourceLocation startLoc = body->getLocStart();
2042 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002043 assert(*SM->getCharacterData(startLoc) == '{' &&
2044 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002045 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00002046 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00002047
Steve Naroffbf478ec2007-11-07 04:08:17 +00002048 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002049 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00002050 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002051 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00002052
Steve Naroffbf478ec2007-11-07 04:08:17 +00002053 // Set lastCurlyLoc
2054 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002055
Steve Naroff6d6da252008-12-05 17:03:39 +00002056 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00002057 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002058 } else { /* no finally clause - make sure we synthesize an implicit one */
2059 buf = "{ /* implicit finally clause */\n";
2060 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2061 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2062 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002063 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002064
2065 // Now check for any return/continue/go statements within the @try.
2066 // The implicit finally clause won't called if the @try contains any
2067 // jump statements.
2068 bool hasReturns = false;
2069 HasReturnStmts(S->getTryBody(), hasReturns);
2070 if (hasReturns)
2071 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002072 }
2073 // Now emit the final closing curly brace...
2074 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002075 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002076 return 0;
2077}
2078
Mike Stump11289f42009-09-09 15:08:12 +00002079// This can't be done with ReplaceStmt(S, ThrowExpr), since
2080// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002081// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002082Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002083 // Get the start location and compute the semi location.
2084 SourceLocation startLoc = S->getLocStart();
2085 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002086
Steve Naroffa733c7f2007-11-07 15:32:26 +00002087 assert((*startBuf == '@') && "bogus @throw location");
2088
2089 std::string buf;
2090 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002091 if (S->getThrowExpr())
2092 buf = "objc_exception_throw(";
2093 else // add an implicit argument
2094 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002095
Steve Naroff29788342008-07-25 15:41:30 +00002096 // handle "@ throw" correctly.
2097 const char *wBuf = strchr(startBuf, 'w');
2098 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002099 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002100
Steve Naroffa733c7f2007-11-07 15:32:26 +00002101 const char *semiBuf = strchr(startBuf, ';');
2102 assert((*semiBuf == ';') && "@throw: can't find ';'");
2103 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002104 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002105 return 0;
2106}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002107
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002108Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002109 // Create a new string expression.
2110 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002111 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002112 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002113 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
Anders Carlsson75245402011-04-14 00:40:03 +00002114 StrEncoding.length(),
2115 false, false, StrType,
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002116 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002117 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattner4431a1b2007-11-30 22:53:43 +00002119 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002120 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002121 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002122}
2123
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002124Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002125 if (!SelGetUidFunctionDecl)
2126 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002127 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2128 // Create a call to sel_registerName("selName").
2129 llvm::SmallVector<Expr*, 8> SelExprs;
2130 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002131 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002132 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002133 Exp->getSelector().getAsString().size(),
Anders Carlsson75245402011-04-14 00:40:03 +00002134 false, false, argType,
2135 SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002136 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2137 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002138 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002139 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002140 return SelExp;
2141}
2142
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002143CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002144 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2145 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002146 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002147 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002148
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002149 // Create a reference to the objc_msgSend() declaration.
John McCall7decc9e2010-11-18 06:31:45 +00002150 DeclRefExpr *DRE =
2151 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002152
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002153 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002154 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002155 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002156 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002157 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002158
John McCall9dd450b2009-09-21 23:43:11 +00002159 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002160
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002161 CallExpr *Exp =
Douglas Gregor603d81b2010-07-13 08:18:22 +00002162 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCall7decc9e2010-11-18 06:31:45 +00002163 FT->getCallResultType(*Context),
2164 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002165 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002166}
2167
Steve Naroff50d42052007-11-01 13:24:47 +00002168static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2169 const char *&startRef, const char *&endRef) {
2170 while (startBuf < endBuf) {
2171 if (*startBuf == '<')
2172 startRef = startBuf; // mark the start.
2173 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002174 if (startRef && *startRef == '<') {
2175 endRef = startBuf; // mark the end.
2176 return true;
2177 }
2178 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002179 }
2180 startBuf++;
2181 }
2182 return false;
2183}
2184
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002185static void scanToNextArgument(const char *&argRef) {
2186 int angle = 0;
2187 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2188 if (*argRef == '<')
2189 angle++;
2190 else if (*argRef == '>')
2191 angle--;
2192 argRef++;
2193 }
2194 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2195}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002196
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002197bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002198 if (T->isObjCQualifiedIdType())
2199 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002200 if (const PointerType *PT = T->getAs<PointerType>()) {
2201 if (PT->getPointeeType()->isObjCQualifiedIdType())
2202 return true;
2203 }
2204 if (T->isObjCObjectPointerType()) {
2205 T = T->getPointeeType();
2206 return T->isObjCQualifiedInterfaceType();
2207 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002208 if (T->isArrayType()) {
2209 QualType ElemTy = Context->getBaseElementType(T);
2210 return needToScanForQualifiers(ElemTy);
2211 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002212 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002213}
2214
Steve Naroff873bd842008-07-29 18:15:38 +00002215void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2216 QualType Type = E->getType();
2217 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002218 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002219
Steve Naroffdbfc6932008-11-19 21:15:47 +00002220 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2221 Loc = ECE->getLParenLoc();
2222 EndLoc = ECE->getRParenLoc();
2223 } else {
2224 Loc = E->getLocStart();
2225 EndLoc = E->getLocEnd();
2226 }
2227 // This will defend against trying to rewrite synthesized expressions.
2228 if (Loc.isInvalid() || EndLoc.isInvalid())
2229 return;
2230
Steve Naroff873bd842008-07-29 18:15:38 +00002231 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002232 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002233 const char *startRef = 0, *endRef = 0;
2234 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2235 // Get the locations of the startRef, endRef.
2236 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2237 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2238 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002239 InsertText(LessLoc, "/*");
2240 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002241 }
2242 }
2243}
2244
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002245void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002246 SourceLocation Loc;
2247 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002248 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002249 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2250 Loc = VD->getLocation();
2251 Type = VD->getType();
2252 }
2253 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2254 Loc = FD->getLocation();
2255 // Check for ObjC 'id' and class types that have been adorned with protocol
2256 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002257 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002258 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002259 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002260 if (!proto)
2261 return;
2262 Type = proto->getResultType();
2263 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002264 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2265 Loc = FD->getLocation();
2266 Type = FD->getType();
2267 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002268 else
2269 return;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002271 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002272 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002273
Steve Naroff50d42052007-11-01 13:24:47 +00002274 const char *endBuf = SM->getCharacterData(Loc);
2275 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002276 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002277 startBuf--; // scan backward (from the decl location) for return type.
2278 const char *startRef = 0, *endRef = 0;
2279 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2280 // Get the locations of the startRef, endRef.
2281 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2282 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2283 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002286 }
2287 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002288 if (!proto)
2289 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002290 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002291 const char *startBuf = SM->getCharacterData(Loc);
2292 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002293 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2294 if (needToScanForQualifiers(proto->getArgType(i))) {
2295 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002296
Steve Naroff50d42052007-11-01 13:24:47 +00002297 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002298 // scan forward (from the decl location) for argument types.
2299 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002300 const char *startRef = 0, *endRef = 0;
2301 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2302 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002303 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002304 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002305 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002306 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002307 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002308 InsertText(LessLoc, "/*");
2309 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002310 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002311 startBuf = ++endBuf;
2312 }
2313 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002314 // If the function name is derived from a macro expansion, then the
2315 // argument buffer will not follow the name. Need to speak with Chris.
2316 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002317 startBuf++; // scan forward (from the decl location) for argument types.
2318 startBuf++;
2319 }
Steve Naroff50d42052007-11-01 13:24:47 +00002320 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002321}
2322
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002323void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2324 QualType QT = ND->getType();
2325 const Type* TypePtr = QT->getAs<Type>();
2326 if (!isa<TypeOfExprType>(TypePtr))
2327 return;
2328 while (isa<TypeOfExprType>(TypePtr)) {
2329 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2330 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2331 TypePtr = QT->getAs<Type>();
2332 }
2333 // FIXME. This will not work for multiple declarators; as in:
2334 // __typeof__(a) b,c,d;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002335 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002336 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2337 const char *startBuf = SM->getCharacterData(DeclLoc);
2338 if (ND->getInit()) {
2339 std::string Name(ND->getNameAsString());
2340 TypeAsString += " " + Name + " = ";
2341 Expr *E = ND->getInit();
2342 SourceLocation startLoc;
2343 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2344 startLoc = ECE->getLParenLoc();
2345 else
2346 startLoc = E->getLocStart();
2347 startLoc = SM->getInstantiationLoc(startLoc);
2348 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002349 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002350 }
2351 else {
2352 SourceLocation X = ND->getLocEnd();
2353 X = SM->getInstantiationLoc(X);
2354 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002355 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002356 }
2357}
2358
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002359// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002360void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002361 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2362 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002363 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002364 QualType getFuncType =
2365 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002366 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002367 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002368 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002369 SelGetUidIdent, getFuncType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002370 SC_Extern,
2371 SC_None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002372}
2373
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002374void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002375 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002376 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002377 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002378 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002379 return;
2380 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002381 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002382}
2383
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002384void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2385 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002386 const char *argPtr = TypeString.c_str();
2387 if (!strchr(argPtr, '^')) {
2388 Str += TypeString;
2389 return;
2390 }
2391 while (*argPtr) {
2392 Str += (*argPtr == '^' ? '*' : *argPtr);
2393 argPtr++;
2394 }
2395}
2396
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002397// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002398void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2399 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002400 QualType Type = VD->getType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002401 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002402 const char *argPtr = TypeString.c_str();
2403 int paren = 0;
2404 while (*argPtr) {
2405 switch (*argPtr) {
2406 case '(':
2407 Str += *argPtr;
2408 paren++;
2409 break;
2410 case ')':
2411 Str += *argPtr;
2412 paren--;
2413 break;
2414 case '^':
2415 Str += '*';
2416 if (paren == 1)
2417 Str += VD->getNameAsString();
2418 break;
2419 default:
2420 Str += *argPtr;
2421 break;
2422 }
2423 argPtr++;
2424 }
2425}
2426
2427
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002428void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2429 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2430 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2431 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2432 if (!proto)
2433 return;
2434 QualType Type = proto->getResultType();
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002435 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002436 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002437 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002438 FdStr += "(";
2439 unsigned numArgs = proto->getNumArgs();
2440 for (unsigned i = 0; i < numArgs; i++) {
2441 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002442 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002443 if (i+1 < numArgs)
2444 FdStr += ", ";
2445 }
2446 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002447 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002448 CurFunctionDeclToDeclareForBlock = 0;
2449}
2450
Steve Naroff17978c42008-03-11 17:37:02 +00002451// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002452void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002453 if (SuperContructorFunctionDecl)
2454 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002455 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002456 llvm::SmallVector<QualType, 16> ArgTys;
2457 QualType argT = Context->getObjCIdType();
2458 assert(!argT.isNull() && "Can't find 'id' type");
2459 ArgTys.push_back(argT);
2460 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002461 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2462 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002463 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002464 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002465 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002466 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002467 SC_Extern,
2468 SC_None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002469}
2470
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002471// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002472void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002473 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2474 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002475 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002476 assert(!argT.isNull() && "Can't find 'id' type");
2477 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002478 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002479 assert(!argT.isNull() && "Can't find 'SEL' type");
2480 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002481 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2482 &ArgTys[0], ArgTys.size(),
2483 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002484 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002485 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002486 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002487 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002488 SC_Extern,
2489 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002490}
2491
Steve Naroff7fa2f042007-11-15 10:28:18 +00002492// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002493void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2495 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002496 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002497 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002498 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2500 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2501 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002502 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002503 assert(!argT.isNull() && "Can't find 'SEL' type");
2504 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002505 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2506 &ArgTys[0], ArgTys.size(),
2507 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002508 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002509 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002510 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002511 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002512 SC_Extern,
2513 SC_None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002514}
2515
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002516// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002517void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002518 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2519 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002520 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002521 assert(!argT.isNull() && "Can't find 'id' type");
2522 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002523 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002524 assert(!argT.isNull() && "Can't find 'SEL' type");
2525 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002526 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2527 &ArgTys[0], ArgTys.size(),
2528 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002529 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002530 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002531 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002532 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002533 SC_Extern,
2534 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002535}
2536
Mike Stump11289f42009-09-09 15:08:12 +00002537// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002538// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002539void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002540 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002541 &Context->Idents.get("objc_msgSendSuper_stret");
2542 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002543 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002544 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002545 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002546 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2547 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2548 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002549 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002550 assert(!argT.isNull() && "Can't find 'SEL' type");
2551 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002552 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2553 &ArgTys[0], ArgTys.size(),
2554 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002555 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002556 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002557 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002558 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002559 SC_Extern,
2560 SC_None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002561}
2562
Steve Naroff2e4e3852008-05-08 22:02:18 +00002563// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002564void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002565 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2566 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002567 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002568 assert(!argT.isNull() && "Can't find 'id' type");
2569 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002570 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002571 assert(!argT.isNull() && "Can't find 'SEL' type");
2572 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002573 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2574 &ArgTys[0], ArgTys.size(),
2575 true /*isVariadic*/);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002576 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002577 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002578 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002579 msgSendIdent, msgSendType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002580 SC_Extern,
2581 SC_None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002582}
2583
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002584// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002585void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002586 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2587 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002588 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002589 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2590 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002591 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002592 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002593 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002594 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002595 SC_Extern,
2596 SC_None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002597}
2598
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002599// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2600void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2601 IdentifierInfo *getSuperClassIdent =
2602 &Context->Idents.get("class_getSuperclass");
2603 llvm::SmallVector<QualType, 16> ArgTys;
2604 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002605 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2606 &ArgTys[0], ArgTys.size());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002607 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002608 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002609 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002610 getSuperClassIdent,
2611 getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002614 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002615}
2616
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002617// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002618void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002619 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2620 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002621 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002622 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2623 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002624 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002625 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002626 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002627 getClassIdent, getClassType, 0,
John McCall8e7d6562010-08-26 03:08:43 +00002628 SC_Extern,
2629 SC_None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002630}
2631
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002632Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002633 QualType strType = getConstantStringStructType();
2634
2635 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002636
2637 std::string tmpName = InFileName;
2638 unsigned i;
2639 for (i=0; i < tmpName.length(); i++) {
2640 char c = tmpName.at(i);
2641 // replace any non alphanumeric characters with '_'.
2642 if (!isalpha(c) && (c < '0' || c > '9'))
2643 tmpName[i] = '_';
2644 }
2645 S += tmpName;
2646 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002647 S += utostr(NumObjCStringLiterals++);
2648
Steve Naroff00a31762008-03-27 22:29:16 +00002649 Preamble += "static __NSConstantStringImpl " + S;
2650 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2651 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002652 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002653 std::string prettyBufS;
2654 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002655 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2656 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002657 Preamble += prettyBuf.str();
2658 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002659 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002660
2661 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002662 SourceLocation(), &Context->Idents.get(S),
2663 strType, 0, SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00002664 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2665 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002666 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002667 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002668 VK_RValue, OK_Ordinary,
2669 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002670 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002671 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCallf608deb2010-11-15 09:46:46 +00002672 CK_BitCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002673 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002674 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002675 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002676}
2677
Steve Naroff7fa2f042007-11-15 10:28:18 +00002678// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002679QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002680 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002681 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002682 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002683 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002684 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002685
Steve Naroff7fa2f042007-11-15 10:28:18 +00002686 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002687 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002688 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002689 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002690
Steve Naroff7fa2f042007-11-15 10:28:18 +00002691 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002692 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002693 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002694 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002695 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002696 FieldTypes[i], 0,
2697 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002698 /*Mutable=*/false,
2699 /*HasInit=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
Douglas Gregord5058122010-02-11 01:19:42 +00002702 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002703 }
2704 return Context->getTagDeclType(SuperStructDecl);
2705}
2706
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002707QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002708 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002709 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002710 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002711 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002712 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002713
Steve Naroffce8e8862008-03-15 00:55:56 +00002714 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002715 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002716 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002717 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002718 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002719 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002720 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002721 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002722
Steve Naroffce8e8862008-03-15 00:55:56 +00002723 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002724 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002725 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2726 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002727 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00002728 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002729 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002730 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002731 /*Mutable=*/true,
2732 /*HasInit=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002733 }
2734
Douglas Gregord5058122010-02-11 01:19:42 +00002735 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002736 }
2737 return Context->getTagDeclType(ConstantStringDecl);
2738}
2739
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002740Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2741 SourceLocation StartLoc,
2742 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002743 if (!SelGetUidFunctionDecl)
2744 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002745 if (!MsgSendFunctionDecl)
2746 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002747 if (!MsgSendSuperFunctionDecl)
2748 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002749 if (!MsgSendStretFunctionDecl)
2750 SynthMsgSendStretFunctionDecl();
2751 if (!MsgSendSuperStretFunctionDecl)
2752 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002753 if (!MsgSendFpretFunctionDecl)
2754 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002755 if (!GetClassFunctionDecl)
2756 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002757 if (!GetSuperClassFunctionDecl)
2758 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002759 if (!GetMetaClassFunctionDecl)
2760 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002761
Steve Naroff7fa2f042007-11-15 10:28:18 +00002762 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002763 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2764 // May need to use objc_msgSend_stret() as well.
2765 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002766 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2767 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002768 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002769 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002770 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002771 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002772 }
Mike Stump11289f42009-09-09 15:08:12 +00002773
Steve Naroff574440f2007-10-24 22:48:43 +00002774 // Synthesize a call to objc_msgSend().
2775 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 switch (Exp->getReceiverKind()) {
2777 case ObjCMessageExpr::SuperClass: {
2778 MsgSendFlavor = MsgSendSuperFunctionDecl;
2779 if (MsgSendStretFlavor)
2780 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2781 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002782
Douglas Gregor9a129192010-04-21 00:45:42 +00002783 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002784
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002786
Douglas Gregor9a129192010-04-21 00:45:42 +00002787 // set the receiver to self, the first argument to all methods.
2788 InitExprs.push_back(
2789 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002790 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002791 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002792 Context->getObjCIdType(),
2793 VK_RValue,
2794 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002795 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002796
Douglas Gregor9a129192010-04-21 00:45:42 +00002797 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2798 llvm::SmallVector<Expr*, 8> ClsExprs;
2799 QualType argType = Context->getPointerType(Context->CharTy);
2800 ClsExprs.push_back(StringLiteral::Create(*Context,
2801 ClassDecl->getIdentifier()->getNameStart(),
2802 ClassDecl->getIdentifier()->getLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00002803 false, false, argType, SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002804 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2805 &ClsExprs[0],
2806 ClsExprs.size(),
2807 StartLoc,
2808 EndLoc);
2809 // (Class)objc_getClass("CurrentClass")
2810 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2811 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002812 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002813 ClsExprs.clear();
2814 ClsExprs.push_back(ArgExpr);
2815 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2816 &ClsExprs[0], ClsExprs.size(),
2817 StartLoc, EndLoc);
2818
2819 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2820 // To turn off a warning, type-cast to 'id'
2821 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2822 NoTypeInfoCStyleCastExpr(Context,
2823 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002824 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002825 // struct objc_super
2826 QualType superType = getSuperStructType();
2827 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002828
Douglas Gregor9a129192010-04-21 00:45:42 +00002829 if (LangOpts.Microsoft) {
2830 SynthSuperContructorFunctionDecl();
2831 // Simulate a contructor call...
2832 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002833 superType, VK_LValue,
2834 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002835 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2836 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002837 superType, VK_LValue,
2838 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002839 // The code for super is a little tricky to prevent collision with
2840 // the structure definition in the header. The rewriter has it's own
2841 // internal definition (__rw_objc_super) that is uses. This is why
2842 // we need the cast below. For example:
2843 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2844 //
John McCalle3027922010-08-25 11:45:40 +00002845 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002846 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002847 VK_RValue, OK_Ordinary,
2848 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002849 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2850 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002851 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002852 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002853 // (struct objc_super) { <exprs from above> }
2854 InitListExpr *ILE =
2855 new (Context) InitListExpr(*Context, SourceLocation(),
2856 &InitExprs[0], InitExprs.size(),
2857 SourceLocation());
2858 TypeSourceInfo *superTInfo
2859 = Context->getTrivialTypeSourceInfo(superType);
2860 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002861 superType, VK_LValue,
2862 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002863 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002864 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002865 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002866 VK_RValue, OK_Ordinary,
2867 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002868 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002869 MsgExprs.push_back(SuperRep);
2870 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002871 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002872
2873 case ObjCMessageExpr::Class: {
2874 llvm::SmallVector<Expr*, 8> ClsExprs;
2875 QualType argType = Context->getPointerType(Context->CharTy);
2876 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002877 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002878 IdentifierInfo *clsName = Class->getIdentifier();
2879 ClsExprs.push_back(StringLiteral::Create(*Context,
2880 clsName->getNameStart(),
2881 clsName->getLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00002882 false, false,
2883 argType, SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002884 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2885 &ClsExprs[0],
2886 ClsExprs.size(),
2887 StartLoc, EndLoc);
2888 MsgExprs.push_back(Cls);
2889 break;
2890 }
2891
2892 case ObjCMessageExpr::SuperInstance:{
2893 MsgSendFlavor = MsgSendSuperFunctionDecl;
2894 if (MsgSendStretFlavor)
2895 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2896 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2897 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2898 llvm::SmallVector<Expr*, 4> InitExprs;
2899
2900 InitExprs.push_back(
2901 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002902 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002903 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall7decc9e2010-11-18 06:31:45 +00002904 Context->getObjCIdType(),
2905 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002906 ); // set the 'receiver'.
2907
2908 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2909 llvm::SmallVector<Expr*, 8> ClsExprs;
2910 QualType argType = Context->getPointerType(Context->CharTy);
2911 ClsExprs.push_back(StringLiteral::Create(*Context,
2912 ClassDecl->getIdentifier()->getNameStart(),
2913 ClassDecl->getIdentifier()->getLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00002914 false, false, argType, SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002915 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2916 &ClsExprs[0],
2917 ClsExprs.size(),
2918 StartLoc, EndLoc);
2919 // (Class)objc_getClass("CurrentClass")
2920 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2921 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002922 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002923 ClsExprs.clear();
2924 ClsExprs.push_back(ArgExpr);
2925 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2926 &ClsExprs[0], ClsExprs.size(),
2927 StartLoc, EndLoc);
2928
2929 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2930 // To turn off a warning, type-cast to 'id'
2931 InitExprs.push_back(
2932 // set 'super class', using class_getSuperclass().
2933 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002934 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002935 // struct objc_super
2936 QualType superType = getSuperStructType();
2937 Expr *SuperRep;
2938
2939 if (LangOpts.Microsoft) {
2940 SynthSuperContructorFunctionDecl();
2941 // Simulate a contructor call...
2942 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCall7decc9e2010-11-18 06:31:45 +00002943 superType, VK_LValue,
2944 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002945 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2946 InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00002947 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002948 // The code for super is a little tricky to prevent collision with
2949 // the structure definition in the header. The rewriter has it's own
2950 // internal definition (__rw_objc_super) that is uses. This is why
2951 // we need the cast below. For example:
2952 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2953 //
John McCalle3027922010-08-25 11:45:40 +00002954 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002955 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002956 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002957 SourceLocation());
2958 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2959 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002960 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002961 } else {
2962 // (struct objc_super) { <exprs from above> }
2963 InitListExpr *ILE =
2964 new (Context) InitListExpr(*Context, SourceLocation(),
2965 &InitExprs[0], InitExprs.size(),
2966 SourceLocation());
2967 TypeSourceInfo *superTInfo
2968 = Context->getTrivialTypeSourceInfo(superType);
2969 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002970 superType, VK_RValue, ILE,
2971 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002972 }
2973 MsgExprs.push_back(SuperRep);
2974 break;
2975 }
2976
2977 case ObjCMessageExpr::Instance: {
2978 // Remove all type-casts because it may contain objc-style types; e.g.
2979 // Foo<Proto> *.
2980 Expr *recExpr = Exp->getInstanceReceiver();
2981 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2982 recExpr = CE->getSubExpr();
2983 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002984 CK_BitCast, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002985 MsgExprs.push_back(recExpr);
2986 break;
2987 }
2988 }
2989
Steve Naroffa397efd2007-11-03 11:27:19 +00002990 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002991 llvm::SmallVector<Expr*, 8> SelExprs;
2992 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002993 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002994 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002995 Exp->getSelector().getAsString().size(),
Anders Carlsson75245402011-04-14 00:40:03 +00002996 false, false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002997 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002998 &SelExprs[0], SelExprs.size(),
2999 StartLoc,
3000 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00003001 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00003002
Steve Naroff574440f2007-10-24 22:48:43 +00003003 // Now push any user supplied arguments.
3004 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00003005 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00003006 // Make all implicit casts explicit...ICE comes in handy:-)
3007 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3008 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00003009 QualType type = ICE->getType();
3010 if (needToScanForQualifiers(type))
3011 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003012 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003013 (void)convertBlockPointerToFunctionPointer(type);
John McCallf608deb2010-11-15 09:46:46 +00003014 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003015 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003016 }
3017 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00003018 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003019 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00003020 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003021 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00003022 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00003023 CK_BitCast, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00003024 }
Mike Stump11289f42009-09-09 15:08:12 +00003025 }
Steve Naroffe7f18192007-11-14 23:54:14 +00003026 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003027 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3028 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003029 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003030 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00003031 }
Steve Narofff36987c2007-11-04 22:37:50 +00003032 // Generate the funky cast.
3033 CastExpr *cast;
3034 llvm::SmallVector<QualType, 8> ArgTypes;
3035 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00003036
Steve Narofff36987c2007-11-04 22:37:50 +00003037 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00003038 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3039 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3040 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003041 ArgTypes.push_back(Context->getObjCIdType());
3042 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00003043 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00003044 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00003045 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3046 E = OMD->param_end(); PI != E; ++PI) {
3047 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00003048 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00003049 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00003050 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003051 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003052 ArgTypes.push_back(t);
3053 }
Chris Lattnera4997152009-02-20 18:43:26 +00003054 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3055 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003056 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003057 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003058 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003059 }
3060 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003061 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003062
Steve Narofff36987c2007-11-04 22:37:50 +00003063 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003064 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003065 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003066
Mike Stump11289f42009-09-09 15:08:12 +00003067 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003068 // If we don't do this cast, we get the following bizarre warning/note:
3069 // xx.m:13: warning: function called through a non-compatible type
3070 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003071 cast = NoTypeInfoCStyleCastExpr(Context,
3072 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003073 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003074
Steve Narofff36987c2007-11-04 22:37:50 +00003075 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003076 QualType castType =
3077 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3078 // If we don't have a method decl, force a variadic cast.
3079 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00003080 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003081 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003082 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003083
3084 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003085 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003086
John McCall9dd450b2009-09-21 23:43:11 +00003087 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003088 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003089 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003090 FT->getResultType(), VK_RValue,
3091 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003092 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003093 if (MsgSendStretFlavor) {
3094 // We have the method which returns a struct/union. Must also generate
3095 // call to objc_msgSend_stret and hang both varieties on a conditional
3096 // expression which dictate which one to envoke depending on size of
3097 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003098
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003099 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003100 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003101 VK_LValue, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003102 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003103 cast = NoTypeInfoCStyleCastExpr(Context,
3104 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003105 CK_BitCast, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003106 // Now do the "normal" pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00003107 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3108 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003109 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003110 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003111 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003112
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003113 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003114 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003115
John McCall9dd450b2009-09-21 23:43:11 +00003116 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003117 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003118 MsgExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00003119 FT->getResultType(), VK_RValue,
3120 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003121
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003122 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003123 UnaryExprOrTypeTraitExpr *sizeofExpr =
3124 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3125 Context->getTrivialTypeSourceInfo(returnType),
3126 Context->getSizeType(), SourceLocation(),
3127 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003128 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3129 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3130 // For X86 it is more complicated and some kind of target specific routine
3131 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003132 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003133 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003134 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3135 llvm::APInt(IntSize, 8),
3136 Context->IntTy,
3137 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003138 BinaryOperator *lessThanExpr =
3139 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3140 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003141 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003142 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003143 new (Context) ConditionalOperator(lessThanExpr,
3144 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003145 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003146 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003147 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3148 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003149 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003150 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003151 return ReplacingStmt;
3152}
3153
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003154Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003155 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3156 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003157
Steve Naroff574440f2007-10-24 22:48:43 +00003158 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003159 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003160
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003161 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003162 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003163}
3164
Steve Naroffd9803712009-04-29 16:37:50 +00003165// typedef struct objc_object Protocol;
3166QualType RewriteObjC::getProtocolType() {
3167 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003168 TypeSourceInfo *TInfo
3169 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003170 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003171 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003172 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003173 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003174 }
3175 return Context->getTypeDeclType(ProtocolTypeDecl);
3176}
3177
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003178/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003179/// a synthesized/forward data reference (to the protocol's metadata).
3180/// The forward references (and metadata) are generated in
3181/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003182Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003183 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3184 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003185 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003186 SourceLocation(), ID, getProtocolType(), 0,
John McCall8e7d6562010-08-26 03:08:43 +00003187 SC_Extern, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00003188 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3189 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003190 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003191 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003192 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003193 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003194 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003195 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003196 ReplaceStmt(Exp, castExpr);
3197 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003198 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003199 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003200
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003201}
3202
Mike Stump11289f42009-09-09 15:08:12 +00003203bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003204 const char *endBuf) {
3205 while (startBuf < endBuf) {
3206 if (*startBuf == '#') {
3207 // Skip whitespace.
3208 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3209 ;
3210 if (!strncmp(startBuf, "if", strlen("if")) ||
3211 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3212 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3213 !strncmp(startBuf, "define", strlen("define")) ||
3214 !strncmp(startBuf, "undef", strlen("undef")) ||
3215 !strncmp(startBuf, "else", strlen("else")) ||
3216 !strncmp(startBuf, "elif", strlen("elif")) ||
3217 !strncmp(startBuf, "endif", strlen("endif")) ||
3218 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3219 !strncmp(startBuf, "include", strlen("include")) ||
3220 !strncmp(startBuf, "import", strlen("import")) ||
3221 !strncmp(startBuf, "include_next", strlen("include_next")))
3222 return true;
3223 }
3224 startBuf++;
3225 }
3226 return false;
3227}
3228
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003229/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003230/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003231void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003232 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003233 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003234 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003235 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003236 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003237 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003238 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003239 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003240 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003241 SourceLocation LocStart = CDecl->getLocStart();
3242 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003243
Steve Naroffdde78982007-11-14 19:25:57 +00003244 const char *startBuf = SM->getCharacterData(LocStart);
3245 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003246
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003247 // If no ivars and no root or if its root, directly or indirectly,
3248 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003249 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3250 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003251 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003252 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003253 return;
3254 }
Mike Stump11289f42009-09-09 15:08:12 +00003255
3256 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003257 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003258 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003259 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003260 if (LangOpts.Microsoft)
3261 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003262
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003263 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003264 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003265 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003266 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003267 // If the buffer contains preprocessor directives, we do more fine-grained
3268 // rewrites. This is intended to fix code that looks like (which occurs in
3269 // NSURL.h, for example):
3270 //
3271 // #ifdef XYZ
3272 // @interface Foo : NSObject
3273 // #else
3274 // @interface FooBar : NSObject
3275 // #endif
3276 // {
3277 // int i;
3278 // }
3279 // @end
3280 //
3281 // This clause is segregated to avoid breaking the common case.
3282 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003283 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003284 CDecl->getClassLoc();
3285 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003286 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003287
Chris Lattnerf5b77512009-02-20 18:18:36 +00003288 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003289 // advance to the end of the referenced protocols.
3290 while (endHeader < cursor && *endHeader != '>') endHeader++;
3291 endHeader++;
3292 }
3293 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003294 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003295 } else {
3296 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003297 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003298 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003299 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003300 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003301 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003302 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003303 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003304 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003305
Steve Naroffdde78982007-11-14 19:25:57 +00003306 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003307 SourceLocation OnePastCurly =
3308 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003309 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003310 }
3311 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003312
Steve Naroffdde78982007-11-14 19:25:57 +00003313 // Now comment out any visibility specifiers.
3314 while (cursor < endBuf) {
3315 if (*cursor == '@') {
3316 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003317 // Skip whitespace.
3318 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3319 /*scan*/;
3320
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003321 // FIXME: presence of @public, etc. inside comment results in
3322 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003323 if (!strncmp(cursor, "public", strlen("public")) ||
3324 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003325 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003326 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003327 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003328 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003329 // FIXME: If there are cases where '<' is used in ivar declaration part
3330 // of user code, then scan the ivar list and use needToScanForQualifiers
3331 // for type checking.
3332 else if (*cursor == '<') {
3333 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003334 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003335 cursor = strchr(cursor, '>');
3336 cursor++;
3337 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003338 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003339 } else if (*cursor == '^') { // rewrite block specifier.
3340 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003341 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003342 }
Steve Naroffdde78982007-11-14 19:25:57 +00003343 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003344 }
Steve Naroffdde78982007-11-14 19:25:57 +00003345 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003346 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003347 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003348 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003349 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003350 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003351 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003352 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003353 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003354 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003355 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003356 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003357 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003358 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003359}
3360
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003361// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003362/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003363template<typename MethodIterator>
3364void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3365 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003366 bool IsInstanceMethod,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003367 llvm::StringRef prefix,
3368 llvm::StringRef ClassName,
Chris Lattner211f8b82007-10-25 17:07:24 +00003369 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003370 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003371
Chris Lattner31bc07e2007-12-12 07:46:12 +00003372 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003373 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003374 SEL _cmd;
3375 char *method_types;
3376 void *_imp;
3377 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003378 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003379 Result += "\nstruct _objc_method {\n";
3380 Result += "\tSEL _cmd;\n";
3381 Result += "\tchar *method_types;\n";
3382 Result += "\tvoid *_imp;\n";
3383 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003384
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003385 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003388 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003389
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003390 /* struct {
3391 struct _objc_method_list *next_method;
3392 int method_count;
3393 struct _objc_method method_list[];
3394 }
3395 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003396 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003397 Result += "\nstatic struct {\n";
3398 Result += "\tstruct _objc_method_list *next_method;\n";
3399 Result += "\tint method_count;\n";
3400 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003401 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003402 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003403 Result += prefix;
3404 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3405 Result += "_METHODS_";
3406 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003407 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003408 Result += IsInstanceMethod ? "inst" : "cls";
3409 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003410 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003411
Chris Lattner31bc07e2007-12-12 07:46:12 +00003412 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003413 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003414 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003415 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003416 Result += "\", \"";
3417 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003418 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003419 Result += MethodInternalNames[*MethodBegin];
3420 Result += "}\n";
3421 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3422 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003423 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003424 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003425 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003426 Result += "\", \"";
3427 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003428 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003429 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003430 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003431 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003432 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003433}
3434
Steve Naroffd9803712009-04-29 16:37:50 +00003435/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003436void RewriteObjC::
Daniel Dunbar56df9772010-08-17 22:39:59 +00003437RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3438 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003439 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003440
3441 // Output struct protocol_methods holder of method selector and type.
3442 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3443 /* struct protocol_methods {
3444 SEL _cmd;
3445 char *method_types;
3446 }
3447 */
3448 Result += "\nstruct _protocol_methods {\n";
3449 Result += "\tstruct objc_selector *_cmd;\n";
3450 Result += "\tchar *method_types;\n";
3451 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003452
Steve Naroffd9803712009-04-29 16:37:50 +00003453 objc_protocol_methods = true;
3454 }
3455 // Do not synthesize the protocol more than once.
3456 if (ObjCSynthesizedProtocols.count(PDecl))
3457 return;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003459 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3460 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3461 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003462 /* struct _objc_protocol_method_list {
3463 int protocol_method_count;
3464 struct protocol_methods protocols[];
3465 }
Steve Naroff251084d2008-03-12 01:06:30 +00003466 */
Steve Naroffd9803712009-04-29 16:37:50 +00003467 Result += "\nstatic struct {\n";
3468 Result += "\tint protocol_method_count;\n";
3469 Result += "\tstruct _protocol_methods protocol_methods[";
3470 Result += utostr(NumMethods);
3471 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3472 Result += PDecl->getNameAsString();
3473 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3474 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003475
Steve Naroffd9803712009-04-29 16:37:50 +00003476 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003477 for (ObjCProtocolDecl::instmeth_iterator
3478 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003479 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003480 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003481 Result += "\t ,{{(struct objc_selector *)\"";
3482 else
3483 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003484 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003485 std::string MethodTypeString;
3486 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3487 Result += "\", \"";
3488 Result += MethodTypeString;
3489 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003490 }
Steve Naroffd9803712009-04-29 16:37:50 +00003491 Result += "\t }\n};\n";
3492 }
Mike Stump11289f42009-09-09 15:08:12 +00003493
Steve Naroffd9803712009-04-29 16:37:50 +00003494 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003495 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3496 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003497 if (NumMethods > 0) {
3498 /* struct _objc_protocol_method_list {
3499 int protocol_method_count;
3500 struct protocol_methods protocols[];
3501 }
3502 */
3503 Result += "\nstatic struct {\n";
3504 Result += "\tint protocol_method_count;\n";
3505 Result += "\tstruct _protocol_methods protocol_methods[";
3506 Result += utostr(NumMethods);
3507 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3508 Result += PDecl->getNameAsString();
3509 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3510 "{\n\t";
3511 Result += utostr(NumMethods);
3512 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003513
Steve Naroffd9803712009-04-29 16:37:50 +00003514 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003515 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003516 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003517 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003518 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003519 Result += "\t ,{{(struct objc_selector *)\"";
3520 else
3521 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar56df9772010-08-17 22:39:59 +00003522 Result += (*I)->getSelector().getAsString();
Steve Naroffd9803712009-04-29 16:37:50 +00003523 std::string MethodTypeString;
3524 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3525 Result += "\", \"";
3526 Result += MethodTypeString;
3527 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003528 }
Steve Naroffd9803712009-04-29 16:37:50 +00003529 Result += "\t }\n};\n";
3530 }
3531
3532 // Output:
3533 /* struct _objc_protocol {
3534 // Objective-C 1.0 extensions
3535 struct _objc_protocol_extension *isa;
3536 char *protocol_name;
3537 struct _objc_protocol **protocol_list;
3538 struct _objc_protocol_method_list *instance_methods;
3539 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003540 };
Steve Naroffd9803712009-04-29 16:37:50 +00003541 */
3542 static bool objc_protocol = false;
3543 if (!objc_protocol) {
3544 Result += "\nstruct _objc_protocol {\n";
3545 Result += "\tstruct _objc_protocol_extension *isa;\n";
3546 Result += "\tchar *protocol_name;\n";
3547 Result += "\tstruct _objc_protocol **protocol_list;\n";
3548 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3549 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003550 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003551
Steve Naroffd9803712009-04-29 16:37:50 +00003552 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003553 }
Mike Stump11289f42009-09-09 15:08:12 +00003554
Steve Naroffd9803712009-04-29 16:37:50 +00003555 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3556 Result += PDecl->getNameAsString();
3557 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3558 "{\n\t0, \"";
3559 Result += PDecl->getNameAsString();
3560 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003561 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003562 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3563 Result += PDecl->getNameAsString();
3564 Result += ", ";
3565 }
3566 else
3567 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003568 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003569 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3570 Result += PDecl->getNameAsString();
3571 Result += "\n";
3572 }
3573 else
3574 Result += "0\n";
3575 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003576
Steve Naroffd9803712009-04-29 16:37:50 +00003577 // Mark this protocol as having been generated.
3578 if (!ObjCSynthesizedProtocols.insert(PDecl))
3579 assert(false && "protocol already synthesized");
3580
3581}
3582
3583void RewriteObjC::
3584RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar56df9772010-08-17 22:39:59 +00003585 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroffd9803712009-04-29 16:37:50 +00003586 std::string &Result) {
3587 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003588
Steve Naroffd9803712009-04-29 16:37:50 +00003589 for (unsigned i = 0; i != Protocols.size(); i++)
3590 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3591
Chris Lattner388f6e92008-07-21 21:33:21 +00003592 // Output the top lovel protocol meta-data for the class.
3593 /* struct _objc_protocol_list {
3594 struct _objc_protocol_list *next;
3595 int protocol_count;
3596 struct _objc_protocol *class_protocols[];
3597 }
3598 */
3599 Result += "\nstatic struct {\n";
3600 Result += "\tstruct _objc_protocol_list *next;\n";
3601 Result += "\tint protocol_count;\n";
3602 Result += "\tstruct _objc_protocol *class_protocols[";
3603 Result += utostr(Protocols.size());
3604 Result += "];\n} _OBJC_";
3605 Result += prefix;
3606 Result += "_PROTOCOLS_";
3607 Result += ClassName;
3608 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3609 "{\n\t0, ";
3610 Result += utostr(Protocols.size());
3611 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003612
Chris Lattner388f6e92008-07-21 21:33:21 +00003613 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003614 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003615 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003616
Chris Lattner388f6e92008-07-21 21:33:21 +00003617 for (unsigned i = 1; i != Protocols.size(); i++) {
3618 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003619 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003620 Result += "\n";
3621 }
3622 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003623}
3624
Steve Naroffd9803712009-04-29 16:37:50 +00003625
Mike Stump11289f42009-09-09 15:08:12 +00003626/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003627/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003628void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003629 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003630 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003631 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003632 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003633 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003634 CDecl = CDecl->getNextClassCategory())
3635 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3636 break;
Mike Stump11289f42009-09-09 15:08:12 +00003637
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003638 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003639 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003640 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003641
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003642 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003643 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003644 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003645
3646 // If any of our property implementations have associated getters or
3647 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003648 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3649 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003650 Prop != PropEnd; ++Prop) {
3651 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3652 continue;
3653 if (!(*Prop)->getPropertyIvarDecl())
3654 continue;
3655 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3656 if (!PD)
3657 continue;
3658 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3659 InstanceMethods.push_back(Getter);
3660 if (PD->isReadOnly())
3661 continue;
3662 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3663 InstanceMethods.push_back(Setter);
3664 }
3665 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003666 true, "CATEGORY_", FullCategoryName.c_str(),
3667 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003668
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003669 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003670 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003671 false, "CATEGORY_", FullCategoryName.c_str(),
3672 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003673
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003674 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003675 // Null CDecl is case of a category implementation with no category interface
3676 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003677 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar56df9772010-08-17 22:39:59 +00003678 FullCategoryName, Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003679 /* struct _objc_category {
3680 char *category_name;
3681 char *class_name;
3682 struct _objc_method_list *instance_methods;
3683 struct _objc_method_list *class_methods;
3684 struct _objc_protocol_list *protocols;
3685 // Objective-C 1.0 extensions
3686 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003687 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003688 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003689 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003690 */
Mike Stump11289f42009-09-09 15:08:12 +00003691
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003692 static bool objc_category = false;
3693 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 Result += "\nstruct _objc_category {\n";
3695 Result += "\tchar *category_name;\n";
3696 Result += "\tchar *class_name;\n";
3697 Result += "\tstruct _objc_method_list *instance_methods;\n";
3698 Result += "\tstruct _objc_method_list *class_methods;\n";
3699 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003700 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 Result += "\tstruct _objc_property_list *instance_properties;\n";
3702 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003703 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003704 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3706 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003707 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003708 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003709 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003710 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003712
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003713 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003714 Result += "\t, (struct _objc_method_list *)"
3715 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3716 Result += FullCategoryName;
3717 Result += "\n";
3718 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003719 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003720 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003721 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003722 Result += "\t, (struct _objc_method_list *)"
3723 "&_OBJC_CATEGORY_CLASS_METHODS_";
3724 Result += FullCategoryName;
3725 Result += "\n";
3726 }
3727 else
3728 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003729
Chris Lattnerf5b77512009-02-20 18:18:36 +00003730 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003731 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003732 Result += FullCategoryName;
3733 Result += "\n";
3734 }
3735 else
3736 Result += "\t, 0\n";
3737 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003738}
3739
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003740/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3741/// ivar offset.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003742void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003743 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003744 if (ivar->isBitField()) {
3745 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3746 // place all bitfields at offset 0.
3747 Result += "0";
3748 } else {
3749 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003750 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003751 if (LangOpts.Microsoft)
3752 Result += "_IMPL";
3753 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003754 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003755 Result += ")";
3756 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003757}
3758
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003759//===----------------------------------------------------------------------===//
3760// Meta Data Emission
3761//===----------------------------------------------------------------------===//
3762
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003763void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003764 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003765 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003766
Chris Lattner57540c52011-04-15 05:22:18 +00003767 // Explicitly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003768 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003769 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003770 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003771 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003772 }
Mike Stump11289f42009-09-09 15:08:12 +00003773
Chris Lattner30d23e82007-12-12 07:56:42 +00003774 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003775 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003776 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003777 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003778 if (NumIvars > 0) {
3779 static bool objc_ivar = false;
3780 if (!objc_ivar) {
3781 /* struct _objc_ivar {
3782 char *ivar_name;
3783 char *ivar_type;
3784 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003785 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003786 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003787 Result += "\nstruct _objc_ivar {\n";
3788 Result += "\tchar *ivar_name;\n";
3789 Result += "\tchar *ivar_type;\n";
3790 Result += "\tint ivar_offset;\n";
3791 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003792
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003793 objc_ivar = true;
3794 }
3795
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003796 /* struct {
3797 int ivar_count;
3798 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003799 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003800 */
Mike Stump11289f42009-09-09 15:08:12 +00003801 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003802 Result += "\tint ivar_count;\n";
3803 Result += "\tstruct _objc_ivar ivar_list[";
3804 Result += utostr(NumIvars);
3805 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003806 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003807 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003808 "{\n\t";
3809 Result += utostr(NumIvars);
3810 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003811
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003812 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003813 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003814 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003815 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003816 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003817 IV != IVEnd; ++IV)
3818 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003819 IVI = IDecl->ivar_begin();
3820 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003821 } else {
3822 IVI = CDecl->ivar_begin();
3823 IVE = CDecl->ivar_end();
3824 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003825 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003826 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003827 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003828 std::string TmpString, StrEncoding;
3829 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3830 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003831 Result += StrEncoding;
3832 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003833 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003834 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003835 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003836 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003837 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003838 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003839 std::string TmpString, StrEncoding;
3840 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3841 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003842 Result += StrEncoding;
3843 Result += "\", ";
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00003844 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003845 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003846 }
Mike Stump11289f42009-09-09 15:08:12 +00003847
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003848 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003849 }
Mike Stump11289f42009-09-09 15:08:12 +00003850
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003851 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003852 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003853 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003854
3855 // If any of our property implementations have associated getters or
3856 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003857 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3858 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003859 Prop != PropEnd; ++Prop) {
3860 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3861 continue;
3862 if (!(*Prop)->getPropertyIvarDecl())
3863 continue;
3864 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3865 if (!PD)
3866 continue;
3867 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003868 if (!Getter->isDefined())
3869 InstanceMethods.push_back(Getter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003870 if (PD->isReadOnly())
3871 continue;
3872 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +00003873 if (!Setter->isDefined())
3874 InstanceMethods.push_back(Setter);
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003875 }
3876 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003877 true, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003878
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003879 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003880 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003881 false, "", IDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003882
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003883 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003884 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00003885 "CLASS", CDecl->getName(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003886
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003887 // Declaration of class/meta-class metadata
3888 /* struct _objc_class {
3889 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003890 const char *super_class_name;
3891 char *name;
3892 long version;
3893 long info;
3894 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003895 struct _objc_ivar_list *ivars;
3896 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003897 struct objc_cache *cache;
3898 struct objc_protocol_list *protocols;
3899 const char *ivar_layout;
3900 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003901 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003902 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003903 static bool objc_class = false;
3904 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003905 Result += "\nstruct _objc_class {\n";
3906 Result += "\tstruct _objc_class *isa;\n";
3907 Result += "\tconst char *super_class_name;\n";
3908 Result += "\tchar *name;\n";
3909 Result += "\tlong version;\n";
3910 Result += "\tlong info;\n";
3911 Result += "\tlong instance_size;\n";
3912 Result += "\tstruct _objc_ivar_list *ivars;\n";
3913 Result += "\tstruct _objc_method_list *methods;\n";
3914 Result += "\tstruct objc_cache *cache;\n";
3915 Result += "\tstruct _objc_protocol_list *protocols;\n";
3916 Result += "\tconst char *ivar_layout;\n";
3917 Result += "\tstruct _objc_class_ext *ext;\n";
3918 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003919 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003920 }
Mike Stump11289f42009-09-09 15:08:12 +00003921
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003922 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003923 ObjCInterfaceDecl *RootClass = 0;
3924 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003925 while (SuperClass) {
3926 RootClass = SuperClass;
3927 SuperClass = SuperClass->getSuperClass();
3928 }
3929 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003930
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003931 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003932 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003933 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003934 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003935 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003936 Result += "\"";
3937
3938 if (SuperClass) {
3939 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003940 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003941 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003942 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003943 Result += "\"";
3944 }
3945 else {
3946 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003947 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003948 Result += "\"";
3949 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003950 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003951 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003952 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003953 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003954 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003955 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003956 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003957 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003958 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003959 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003960 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003961 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003962 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003963 Result += ",0,0\n";
3964 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003965 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003966 Result += "\t,0,0,0,0\n";
3967 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003968
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003969 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003970 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003971 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003972 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003973 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003974 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003975 if (SuperClass) {
3976 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003977 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003978 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003979 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003980 Result += "\"";
3981 }
3982 else {
3983 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003984 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003985 Result += "\"";
3986 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003987 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003988 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003989 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003990 Result += ",0";
3991 else {
3992 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003993 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003994 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003995 if (LangOpts.Microsoft)
3996 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003997 Result += ")";
3998 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003999 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00004000 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004001 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004002 Result += "\n\t";
4003 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004004 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004005 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004006 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00004007 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004008 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00004009 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004010 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004011 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004012 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00004013 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00004014 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004015 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004016 Result += ", 0,0\n";
4017 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00004018 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004019 Result += ",0,0,0\n";
4020 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00004021}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004022
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004023/// RewriteImplementations - This routine rewrites all method implementations
4024/// and emits meta-data.
4025
Steve Narofff8cfd162008-11-13 20:07:04 +00004026void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004027 int ClsDefCount = ClassImplementation.size();
4028 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00004029
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00004030 // Rewrite implemented methods
4031 for (int i = 0; i < ClsDefCount; i++)
4032 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00004033
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00004034 for (int i = 0; i < CatDefCount; i++)
4035 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00004036}
Mike Stump11289f42009-09-09 15:08:12 +00004037
Steve Narofff8cfd162008-11-13 20:07:04 +00004038void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4039 int ClsDefCount = ClassImplementation.size();
4040 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00004041
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004042 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00004043 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004044 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00004045
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00004046 // For each implemented category, write out all its meta data.
4047 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004048 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00004049
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004050 // Write objc_symtab metadata
4051 /*
4052 struct _objc_symtab
4053 {
4054 long sel_ref_cnt;
4055 SEL *refs;
4056 short cls_def_cnt;
4057 short cat_def_cnt;
4058 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004059 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004060 */
Mike Stump11289f42009-09-09 15:08:12 +00004061
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004062 Result += "\nstruct _objc_symtab {\n";
4063 Result += "\tlong sel_ref_cnt;\n";
4064 Result += "\tSEL *refs;\n";
4065 Result += "\tshort cls_def_cnt;\n";
4066 Result += "\tshort cat_def_cnt;\n";
4067 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4068 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004069
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004070 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004071 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004072 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004073 + ", " + utostr(CatDefCount) + "\n";
4074 for (int i = 0; i < ClsDefCount; i++) {
4075 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004076 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004077 Result += "\n";
4078 }
Mike Stump11289f42009-09-09 15:08:12 +00004079
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004080 for (int i = 0; i < CatDefCount; i++) {
4081 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004082 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004083 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004084 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004085 Result += "\n";
4086 }
Mike Stump11289f42009-09-09 15:08:12 +00004087
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004088 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004089
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004090 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004091
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004092 /*
4093 struct _objc_module {
4094 long version;
4095 long size;
4096 const char *name;
4097 struct _objc_symtab *symtab;
4098 }
4099 */
Mike Stump11289f42009-09-09 15:08:12 +00004100
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004101 Result += "\nstruct _objc_module {\n";
4102 Result += "\tlong version;\n";
4103 Result += "\tlong size;\n";
4104 Result += "\tconst char *name;\n";
4105 Result += "\tstruct _objc_symtab *symtab;\n";
4106 Result += "};\n\n";
4107 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004108 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004109 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004110 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004111 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004112
4113 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004114 if (ProtocolExprDecls.size()) {
4115 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4116 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004117 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004118 E = ProtocolExprDecls.end(); I != E; ++I) {
4119 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4120 Result += (*I)->getNameAsString();
4121 Result += " = &_OBJC_PROTOCOL_";
4122 Result += (*I)->getNameAsString();
4123 Result += ";\n";
4124 }
4125 Result += "#pragma data_seg(pop)\n\n";
4126 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004127 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004128 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004129 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4130 Result += "&_OBJC_MODULES;\n";
4131 Result += "#pragma data_seg(pop)\n\n";
4132 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004133}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004134
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004135void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4136 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004137 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004138 assert(BlockByRefDeclNo.count(VD) &&
4139 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004140 if (def)
4141 ResultStr += "struct ";
4142 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004143 "_" + utostr(BlockByRefDeclNo[VD]) ;
4144}
4145
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004146static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4147 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4148 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4149 return false;
4150}
4151
Steve Naroff677ab3a2008-10-27 17:20:55 +00004152std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004153 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004154 std::string Tag) {
4155 const FunctionType *AFT = CE->getFunctionType();
4156 QualType RT = AFT->getResultType();
4157 std::string StructRef = "struct " + Tag;
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00004158 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00004159 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004160
Steve Naroff677ab3a2008-10-27 17:20:55 +00004161 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004162
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004163 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004164 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004165 // block (to reference imported block decl refs).
4166 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004167 } else if (BD->param_empty()) {
4168 S += "(" + StructRef + " *__cself)";
4169 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004170 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 assert(FT && "SynthesizeBlockFunc: No function proto");
4172 S += '(';
4173 // first add the implicit argument.
4174 S += StructRef + " *__cself, ";
4175 std::string ParamStr;
4176 for (BlockDecl::param_iterator AI = BD->param_begin(),
4177 E = BD->param_end(); AI != E; ++AI) {
4178 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004179 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004180 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004181 if (convertBlockPointerToFunctionPointer(QT))
4182 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004183 else
4184 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004185 S += ParamStr;
4186 }
4187 if (FT->isVariadic()) {
4188 if (!BD->param_empty()) S += ", ";
4189 S += "...";
4190 }
4191 S += ')';
4192 }
4193 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004194
Steve Naroff677ab3a2008-10-27 17:20:55 +00004195 // Create local declarations to avoid rewriting all closure decl ref exprs.
4196 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004197 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004198 E = BlockByRefDecls.end(); I != E; ++I) {
4199 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004200 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004201 std::string TypeString;
4202 RewriteByRefString(TypeString, Name, (*I));
4203 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004204 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004205 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004206 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004208 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004209 E = BlockByCopyDecls.end(); I != E; ++I) {
4210 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 // Handle nested closure invocation. For example:
4212 //
4213 // void (^myImportedClosure)(void);
4214 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004215 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004216 // void (^anotherClosure)(void);
4217 // anotherClosure = ^(void) {
4218 // myImportedClosure(); // import and invoke the closure
4219 // };
4220 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004221 if (isTopLevelBlockPointerType((*I)->getType())) {
4222 RewriteBlockPointerTypeVariable(S, (*I));
4223 S += " = (";
4224 RewriteBlockPointerType(S, (*I)->getType());
4225 S += ")";
4226 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4227 }
4228 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004229 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004230 QualType QT = (*I)->getType();
4231 if (HasLocalVariableExternalStorage(*I))
4232 QT = Context->getPointerType(QT);
4233 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004234 S += Name + " = __cself->" +
4235 (*I)->getNameAsString() + "; // bound by copy\n";
4236 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004237 }
4238 std::string RewrittenStr = RewrittenBlockExprs[CE];
4239 const char *cstr = RewrittenStr.c_str();
4240 while (*cstr++ != '{') ;
4241 S += cstr;
4242 S += "\n";
4243 return S;
4244}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004245
Steve Naroff677ab3a2008-10-27 17:20:55 +00004246std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004247 llvm::StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 std::string Tag) {
4249 std::string StructRef = "struct " + Tag;
4250 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004251
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252 S += funcName;
4253 S += "_block_copy_" + utostr(i);
4254 S += "(" + StructRef;
4255 S += "*dst, " + StructRef;
4256 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004257 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004259 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004260 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004261 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004262 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004263 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004264 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004265 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004266 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004268 S += "}\n";
4269
Steve Naroff677ab3a2008-10-27 17:20:55 +00004270 S += "\nstatic void __";
4271 S += funcName;
4272 S += "_block_dispose_" + utostr(i);
4273 S += "(" + StructRef;
4274 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004275 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004276 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004277 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004278 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004279 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004280 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004281 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004282 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004285 return S;
4286}
4287
Steve Naroff30484702009-12-06 21:14:13 +00004288std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4289 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004290 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004292
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004294 S += " struct " + Desc;
4295 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004296
Steve Naroff30484702009-12-06 21:14:13 +00004297 Constructor += "(void *fp, "; // Invoke function pointer.
4298 Constructor += "struct " + Desc; // Descriptor pointer.
4299 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004300
Steve Naroff677ab3a2008-10-27 17:20:55 +00004301 if (BlockDeclRefs.size()) {
4302 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004303 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004304 E = BlockByCopyDecls.end(); I != E; ++I) {
4305 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004306 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 std::string ArgName = "_" + FieldName;
4308 // Handle nested closure invocation. For example:
4309 //
4310 // void (^myImportedBlock)(void);
4311 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004312 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 // void (^anotherBlock)(void);
4314 // anotherBlock = ^(void) {
4315 // myImportedBlock(); // import and invoke the closure
4316 // };
4317 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004318 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004319 S += "struct __block_impl *";
4320 Constructor += ", void *" + ArgName;
4321 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004322 QualType QT = (*I)->getType();
4323 if (HasLocalVariableExternalStorage(*I))
4324 QT = Context->getPointerType(QT);
4325 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4326 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004327 Constructor += ", " + ArgName;
4328 }
4329 S += FieldName + ";\n";
4330 }
4331 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004332 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004333 E = BlockByRefDecls.end(); I != E; ++I) {
4334 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004335 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004336 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00004337 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004338 std::string TypeString;
4339 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004340 TypeString += " *";
4341 FieldName = TypeString + FieldName;
4342 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004343 Constructor += ", " + ArgName;
4344 }
4345 S += FieldName + "; // by ref\n";
4346 }
4347 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004348 Constructor += ", int flags=0)";
4349 // Initialize all "by copy" arguments.
4350 bool firsTime = true;
4351 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4352 E = BlockByCopyDecls.end(); I != E; ++I) {
4353 std::string Name = (*I)->getNameAsString();
4354 if (firsTime) {
4355 Constructor += " : ";
4356 firsTime = false;
4357 }
4358 else
4359 Constructor += ", ";
4360 if (isTopLevelBlockPointerType((*I)->getType()))
4361 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4362 else
4363 Constructor += Name + "(_" + Name + ")";
4364 }
4365 // Initialize all "by ref" arguments.
4366 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4367 E = BlockByRefDecls.end(); I != E; ++I) {
4368 std::string Name = (*I)->getNameAsString();
4369 if (firsTime) {
4370 Constructor += " : ";
4371 firsTime = false;
4372 }
4373 else
4374 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00004375 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00004376 }
4377
4378 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004379 if (GlobalVarDecl)
4380 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4381 else
4382 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004383 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004384
Steve Naroff30484702009-12-06 21:14:13 +00004385 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004386 } else {
4387 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004388 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004389 if (GlobalVarDecl)
4390 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4391 else
4392 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004393 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4394 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004395 }
4396 Constructor += " ";
4397 Constructor += "}\n";
4398 S += Constructor;
4399 S += "};\n";
4400 return S;
4401}
4402
Steve Naroff30484702009-12-06 21:14:13 +00004403std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4404 std::string ImplTag, int i,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004405 llvm::StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00004406 unsigned hasCopy) {
4407 std::string S = "\nstatic struct " + DescTag;
4408
4409 S += " {\n unsigned long reserved;\n";
4410 S += " unsigned long Block_size;\n";
4411 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004412 S += " void (*copy)(struct ";
4413 S += ImplTag; S += "*, struct ";
4414 S += ImplTag; S += "*);\n";
4415
4416 S += " void (*dispose)(struct ";
4417 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004418 }
4419 S += "} ";
4420
4421 S += DescTag + "_DATA = { 0, sizeof(struct ";
4422 S += ImplTag + ")";
4423 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004424 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4425 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00004426 }
4427 S += "};\n";
4428 return S;
4429}
4430
Steve Naroff677ab3a2008-10-27 17:20:55 +00004431void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar56df9772010-08-17 22:39:59 +00004432 llvm::StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004433 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004434 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004435 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004436 bool RewriteSC = (GlobalVarDecl &&
4437 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00004438 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004439 GlobalVarDecl->getType().getCVRQualifiers());
4440 if (RewriteSC) {
4441 std::string SC(" void __");
4442 SC += GlobalVarDecl->getNameAsString();
4443 SC += "() {}";
4444 InsertText(FunLocStart, SC);
4445 }
4446
Steve Naroff677ab3a2008-10-27 17:20:55 +00004447 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004448 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4449 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004450 // Need to copy-in the inner copied-in variables not actually used in this
4451 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004452 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4453 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4454 ValueDecl *VD = Exp->getDecl();
4455 BlockDeclRefs.push_back(Exp);
4456 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4457 BlockByCopyDeclsPtrSet.insert(VD);
4458 BlockByCopyDecls.push_back(VD);
4459 }
4460 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4461 BlockByRefDeclsPtrSet.insert(VD);
4462 BlockByRefDecls.push_back(VD);
4463 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00004464 // imported objects in the inner blocks not used in the outer
4465 // blocks must be copied/disposed in the outer block as well.
4466 if (Exp->isByRef() ||
4467 VD->getType()->isObjCObjectPointerType() ||
4468 VD->getType()->isBlockPointerType())
4469 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004470 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004471
Daniel Dunbar56df9772010-08-17 22:39:59 +00004472 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4473 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Naroff30484702009-12-06 21:14:13 +00004475 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004476
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004477 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004478
Steve Naroff30484702009-12-06 21:14:13 +00004479 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004480
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004481 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004482
4483 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004484 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004485 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004486 }
Steve Naroff30484702009-12-06 21:14:13 +00004487 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4488 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004489 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004490
Steve Naroff677ab3a2008-10-27 17:20:55 +00004491 BlockDeclRefs.clear();
4492 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004493 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004494 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004495 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004496 ImportedBlockDecls.clear();
4497 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004498 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004499 // Must insert any 'const/volatile/static here. Since it has been
4500 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004501 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00004502 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004503 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004504 if (GlobalVarDecl->getType().isConstQualified())
4505 SC += "const ";
4506 if (GlobalVarDecl->getType().isVolatileQualified())
4507 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004508 if (GlobalVarDecl->getType().isRestrictQualified())
4509 SC += "restrict ";
4510 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004511 }
4512
Steve Naroff677ab3a2008-10-27 17:20:55 +00004513 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004514 InnerDeclRefsCount.clear();
4515 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004516 RewrittenBlockExprs.clear();
4517}
4518
4519void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4520 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004521 llvm::StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00004522
Steve Naroff677ab3a2008-10-27 17:20:55 +00004523 SynthesizeBlockLiterals(FunLocStart, FuncName);
4524}
4525
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004526static void BuildUniqueMethodName(std::string &Name,
4527 ObjCMethodDecl *MD) {
4528 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00004529 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004530 Name += "__" + MD->getSelector().getAsString();
4531 // Convert colons to underscores.
4532 std::string::size_type loc = 0;
4533 while ((loc = Name.find(":", loc)) != std::string::npos)
4534 Name.replace(loc, 1, "_");
4535}
4536
Steve Naroff677ab3a2008-10-27 17:20:55 +00004537void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004538 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4539 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004540 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004541 std::string FuncName;
4542 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00004543 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004544}
4545
4546void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00004547 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00004548 if (*CI) {
4549 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4550 GetBlockDeclRefExprs(CBE->getBody());
4551 else
4552 GetBlockDeclRefExprs(*CI);
4553 }
4554 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004555 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004556 // FIXME: Handle enums.
4557 if (!isa<FunctionDecl>(CDRE->getDecl()))
4558 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004559 }
4560 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4561 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4562 BlockDeclRefExpr *BDRE =
John McCall351762c2011-02-07 10:33:21 +00004563 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4564 DRE->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004565 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004566 BlockDeclRefs.push_back(BDRE);
4567 }
4568
Steve Naroff677ab3a2008-10-27 17:20:55 +00004569 return;
4570}
4571
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004572void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4573 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004574 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00004575 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004576 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004577 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4578 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004579 GetInnerBlockDeclRefExprs(CBE->getBody(),
4580 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004581 InnerContexts);
4582 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004583 else
4584 GetInnerBlockDeclRefExprs(*CI,
4585 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004586 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004587
4588 }
4589 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004590 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004591 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004592 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004593 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004594 }
4595 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4596 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4597 if (Var->isFunctionOrMethodVarDecl())
4598 ImportedLocalExternalDecls.insert(Var);
4599 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004600
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004601 return;
4602}
4603
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004604/// convertFunctionTypeOfBlocks - This routine converts a function type
4605/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00004606/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004607/// all block pointers to function pointers.
4608QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4609 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4610 // FTP will be null for closures that don't take arguments.
4611 // Generate a funky cast.
4612 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004613 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004614 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004615
4616 if (FTP) {
4617 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4618 E = FTP->arg_type_end(); I && (I != E); ++I) {
4619 QualType t = *I;
4620 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004621 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004622 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004623 ArgTypes.push_back(t);
4624 }
4625 }
4626 QualType FuncType;
4627 // FIXME. Does this work if block takes no argument but has a return type
4628 // which is of block type?
4629 if (HasBlockType)
John McCalldb40c7f2010-12-14 08:05:40 +00004630 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004631 else FuncType = QualType(FT, 0);
4632 return FuncType;
4633}
4634
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004635Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004636 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004637 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004638
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004639 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004640 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004641 } else if (const BlockDeclRefExpr *CDRE =
4642 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004643 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004644 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004645 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004646 }
4647 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4648 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4649 }
4650 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4651 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4652 else if (const ConditionalOperator *CEXPR =
4653 dyn_cast<ConditionalOperator>(BlockExp)) {
4654 Expr *LHSExp = CEXPR->getLHS();
4655 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4656 Expr *RHSExp = CEXPR->getRHS();
4657 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4658 Expr *CONDExp = CEXPR->getCond();
4659 ConditionalOperator *CondExpr =
4660 new (Context) ConditionalOperator(CONDExp,
4661 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004662 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00004663 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004664 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004665 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4666 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004667 } else {
4668 assert(1 && "RewriteBlockClass: Bad type");
4669 }
4670 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004671 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004672 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004673 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004674 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004675
Abramo Bagnara6150c882010-05-11 21:36:43 +00004676 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004677 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00004678 &Context->Idents.get("__block_impl"));
4679 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680
Steve Naroff350b6652008-10-30 10:07:53 +00004681 // Generate a funky cast.
4682 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004683
Steve Naroff350b6652008-10-30 10:07:53 +00004684 // Push the block argument type.
4685 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004686 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004687 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004688 E = FTP->arg_type_end(); I && (I != E); ++I) {
4689 QualType t = *I;
4690 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004691 if (!convertBlockPointerToFunctionPointer(t))
4692 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004693 ArgTypes.push_back(t);
4694 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004695 }
Steve Naroff350b6652008-10-30 10:07:53 +00004696 // Now do the pointer to function cast.
John McCalldb40c7f2010-12-14 08:05:40 +00004697 QualType PtrToFuncCastType
4698 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump11289f42009-09-09 15:08:12 +00004699
Steve Naroff350b6652008-10-30 10:07:53 +00004700 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004701
John McCall97513962010-01-15 18:39:57 +00004702 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00004703 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004704 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004705 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004706 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4707 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004708 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004709
Douglas Gregor91f84212008-12-11 16:49:14 +00004710 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004711 SourceLocation(),
4712 &Context->Idents.get("FuncPtr"),
4713 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00004714 /*BitWidth=*/0, /*Mutable=*/true,
4715 /*HasInit=*/false);
Ted Kremenek5a201952009-02-07 01:47:29 +00004716 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004717 FD->getType(), VK_LValue,
4718 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00004719
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00004720
John McCall97513962010-01-15 18:39:57 +00004721 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00004722 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004723 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004724
Steve Naroff350b6652008-10-30 10:07:53 +00004725 llvm::SmallVector<Expr*, 8> BlkExprs;
4726 // Add the implicit argument.
4727 BlkExprs.push_back(BlkCast);
4728 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004729 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004730 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004731 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004732 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004733 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4734 BlkExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00004735 Exp->getType(), VK_RValue,
4736 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004737 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004738}
4739
Steve Naroffd9803712009-04-29 16:37:50 +00004740// We need to return the rewritten expression to handle cases where the
4741// BlockDeclRefExpr is embedded in another expression being rewritten.
4742// For example:
4743//
4744// int main() {
4745// __block Foo *f;
4746// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004747//
Steve Naroffd9803712009-04-29 16:37:50 +00004748// void (^myblock)() = ^() {
4749// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4750// i = 77;
4751// };
4752//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004753Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004754 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004755 // for each DeclRefExp where BYREFVAR is name of the variable.
4756 ValueDecl *VD;
4757 bool isArrow = true;
4758 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4759 VD = BDRE->getDecl();
4760 else {
4761 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4762 isArrow = false;
4763 }
4764
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004765 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004766 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004767 &Context->Idents.get("__forwarding"),
4768 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00004769 /*BitWidth=*/0, /*Mutable=*/true,
4770 /*HasInit=*/false);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004771 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4772 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004773 FD->getType(), VK_LValue,
4774 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004775
Daniel Dunbar56df9772010-08-17 22:39:59 +00004776 llvm::StringRef Name = VD->getName();
Abramo Bagnaradff19302011-03-08 08:55:46 +00004777 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004778 &Context->Idents.get(Name),
4779 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00004780 /*BitWidth=*/0, /*Mutable=*/true,
4781 /*HasInit=*/false);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004782 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00004783 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004784
4785
4786
Steve Narofff26a1d42009-02-02 17:19:26 +00004787 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00004788 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4789 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004790 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004791 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004792 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004793}
4794
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004795// Rewrites the imported local variable V with external storage
4796// (static, extern, etc.) as *V
4797//
4798Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4799 ValueDecl *VD = DRE->getDecl();
4800 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4801 if (!ImportedLocalExternalDecls.count(Var))
4802 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00004803 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4804 VK_LValue, OK_Ordinary,
4805 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004806 // Need parens to enforce precedence.
4807 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4808 Exp);
4809 ReplaceStmt(DRE, PE);
4810 return PE;
4811}
4812
Steve Naroffc989a7b2008-11-03 23:29:32 +00004813void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4814 SourceLocation LocStart = CE->getLParenLoc();
4815 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004816
4817 // Need to avoid trying to rewrite synthesized casts.
4818 if (LocStart.isInvalid())
4819 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004820 // Need to avoid trying to rewrite casts contained in macros.
4821 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4822 return;
Mike Stump11289f42009-09-09 15:08:12 +00004823
Steve Naroff677ab3a2008-10-27 17:20:55 +00004824 const char *startBuf = SM->getCharacterData(LocStart);
4825 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004826 QualType QT = CE->getType();
4827 const Type* TypePtr = QT->getAs<Type>();
4828 if (isa<TypeOfExprType>(TypePtr)) {
4829 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4830 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4831 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004832 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004833 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004834 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004835 return;
4836 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 // advance the location to startArgList.
4838 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004839
Steve Naroff677ab3a2008-10-27 17:20:55 +00004840 while (*argPtr++ && (argPtr < endBuf)) {
4841 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004842 case '^':
4843 // Replace the '^' with '*'.
4844 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004845 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004846 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004847 }
4848 }
4849 return;
4850}
4851
4852void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4853 SourceLocation DeclLoc = FD->getLocation();
4854 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Steve Naroff677ab3a2008-10-27 17:20:55 +00004856 // We have 1 or more arguments that have closure pointers.
4857 const char *startBuf = SM->getCharacterData(DeclLoc);
4858 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004859
Steve Naroff677ab3a2008-10-27 17:20:55 +00004860 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004861
Steve Naroff677ab3a2008-10-27 17:20:55 +00004862 parenCount++;
4863 // advance the location to startArgList.
4864 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4865 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004866
Steve Naroff677ab3a2008-10-27 17:20:55 +00004867 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004868
Steve Naroff677ab3a2008-10-27 17:20:55 +00004869 while (*argPtr++ && parenCount) {
4870 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004871 case '^':
4872 // Replace the '^' with '*'.
4873 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004874 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004875 break;
4876 case '(':
4877 parenCount++;
4878 break;
4879 case ')':
4880 parenCount--;
4881 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004882 }
4883 }
4884 return;
4885}
4886
4887bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004888 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004889 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004890 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004891 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004892 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004893 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004894 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004895 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004896 }
4897 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004898 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004899 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004900 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004901 return true;
4902 }
4903 return false;
4904}
4905
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004906bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4907 const FunctionProtoType *FTP;
4908 const PointerType *PT = QT->getAs<PointerType>();
4909 if (PT) {
4910 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4911 } else {
4912 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4913 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4914 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4915 }
4916 if (FTP) {
4917 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004918 E = FTP->arg_type_end(); I != E; ++I) {
4919 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004920 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004921 if ((*I)->isObjCObjectPointerType() &&
4922 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4923 return true;
4924 }
4925
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004926 }
4927 return false;
4928}
4929
Ted Kremenek5a201952009-02-07 01:47:29 +00004930void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4931 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004932 const char *argPtr = strchr(Name, '(');
4933 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004934
Steve Naroff677ab3a2008-10-27 17:20:55 +00004935 LParen = argPtr; // output the start.
4936 argPtr++; // skip past the left paren.
4937 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004938
Steve Naroff677ab3a2008-10-27 17:20:55 +00004939 while (*argPtr && parenCount) {
4940 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004941 case '(': parenCount++; break;
4942 case ')': parenCount--; break;
4943 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004944 }
4945 if (parenCount) argPtr++;
4946 }
4947 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4948 RParen = argPtr; // output the end
4949}
4950
4951void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4952 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4953 RewriteBlockPointerFunctionArgs(FD);
4954 return;
Mike Stump11289f42009-09-09 15:08:12 +00004955 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004956 // Handle Variables and Typedefs.
4957 SourceLocation DeclLoc = ND->getLocation();
4958 QualType DeclT;
4959 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4960 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004961 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004962 DeclT = TDD->getUnderlyingType();
4963 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4964 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004965 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004966 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004967
Steve Naroff677ab3a2008-10-27 17:20:55 +00004968 const char *startBuf = SM->getCharacterData(DeclLoc);
4969 const char *endBuf = startBuf;
4970 // scan backward (from the decl location) for the end of the previous decl.
4971 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4972 startBuf--;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004973 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4974 std::string buf;
4975 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004976 // *startBuf != '^' if we are dealing with a pointer to function that
4977 // may take block argument types (which will be handled below).
4978 if (*startBuf == '^') {
4979 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004980 buf = '*';
4981 startBuf++;
4982 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004983 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004984 while (*startBuf != ')') {
4985 buf += *startBuf;
4986 startBuf++;
4987 OrigLength++;
4988 }
4989 buf += ')';
4990 OrigLength++;
4991
4992 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4993 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004994 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004995 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004996 DeclLoc = ND->getLocation();
4997 startBuf = SM->getCharacterData(DeclLoc);
4998 const char *argListBegin, *argListEnd;
4999 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5000 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005001 if (*argListBegin == '^')
5002 buf += '*';
5003 else if (*argListBegin == '<') {
5004 buf += "/*";
5005 buf += *argListBegin++;
5006 OrigLength++;;
5007 while (*argListBegin != '>') {
5008 buf += *argListBegin++;
5009 OrigLength++;
5010 }
5011 buf += *argListBegin;
5012 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00005013 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005014 else
5015 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005016 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005017 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005018 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005019 buf += ')';
5020 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00005021 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00005022 ReplaceText(Start, OrigLength, buf);
5023
Steve Naroff677ab3a2008-10-27 17:20:55 +00005024 return;
5025}
5026
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005027
5028/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5029/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5030/// struct Block_byref_id_object *src) {
5031/// _Block_object_assign (&_dest->object, _src->object,
5032/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5033/// [|BLOCK_FIELD_IS_WEAK]) // object
5034/// _Block_object_assign(&_dest->object, _src->object,
5035/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5036/// [|BLOCK_FIELD_IS_WEAK]) // block
5037/// }
5038/// And:
5039/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5040/// _Block_object_dispose(_src->object,
5041/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5042/// [|BLOCK_FIELD_IS_WEAK]) // object
5043/// _Block_object_dispose(_src->object,
5044/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5045/// [|BLOCK_FIELD_IS_WEAK]) // block
5046/// }
5047
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005048std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5049 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005050 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00005051 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005052 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005053 CopyDestroyCache.insert(flag);
5054 S = "static void __Block_byref_id_object_copy_";
5055 S += utostr(flag);
5056 S += "(void *dst, void *src) {\n";
5057
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005058 // offset into the object pointer is computed as:
5059 // void * + void* + int + int + void* + void *
5060 unsigned IntSize =
5061 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5062 unsigned VoidPtrSize =
5063 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5064
Ken Dyckd9c83e62011-04-30 16:08:27 +00005065 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005066 S += " _Block_object_assign((char*)dst + ";
5067 S += utostr(offset);
5068 S += ", *(void * *) ((char*)src + ";
5069 S += utostr(offset);
5070 S += "), ";
5071 S += utostr(flag);
5072 S += ");\n}\n";
5073
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005074 S += "static void __Block_byref_id_object_dispose_";
5075 S += utostr(flag);
5076 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005077 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5078 S += utostr(offset);
5079 S += "), ";
5080 S += utostr(flag);
5081 S += ");\n}\n";
5082 return S;
5083}
5084
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005085/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5086/// the declaration into:
5087/// struct __Block_byref_ND {
5088/// void *__isa; // NULL for everything except __weak pointers
5089/// struct __Block_byref_ND *__forwarding;
5090/// int32_t __flags;
5091/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005092/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5093/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005094/// typex ND;
5095/// };
5096///
5097/// It then replaces declaration of ND variable with:
5098/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5099/// __size=sizeof(struct __Block_byref_ND),
5100/// ND=initializer-if-any};
5101///
5102///
5103void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005104 // Insert declaration for the function in which block literal is
5105 // used.
5106 if (CurFunctionDeclToDeclareForBlock)
5107 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005108 int flag = 0;
5109 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005110 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00005111 if (DeclLoc.isInvalid())
5112 // If type location is missing, it is because of missing type (a warning).
5113 // Use variable's location which is good for this case.
5114 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005115 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005116 SourceLocation X = ND->getLocEnd();
5117 X = SM->getInstantiationLoc(X);
5118 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005119 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005120 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005121 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005122 ByrefType += " {\n";
5123 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005124 RewriteByRefString(ByrefType, Name, ND);
5125 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005126 ByrefType += " int __flags;\n";
5127 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005128 // Add void *__Block_byref_id_object_copy;
5129 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005130 QualType Ty = ND->getType();
5131 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5132 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005133 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5134 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005135 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00005136
5137 QualType T = Ty;
5138 (void)convertBlockPointerToFunctionPointer(T);
5139 T.getAsStringInternal(Name, Context->PrintingPolicy);
5140
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005141 ByrefType += " " + Name + ";\n";
5142 ByrefType += "};\n";
5143 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005144 SourceLocation FunLocStart;
5145 if (CurFunctionDef)
5146 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5147 else {
5148 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5149 FunLocStart = CurMethodDef->getLocStart();
5150 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005151 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005152 if (Ty.isObjCGCWeak()) {
5153 flag |= BLOCK_FIELD_IS_WEAK;
5154 isa = 1;
5155 }
5156
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005157 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005158 flag = BLOCK_BYREF_CALLER;
5159 QualType Ty = ND->getType();
5160 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5161 if (Ty->isBlockPointerType())
5162 flag |= BLOCK_FIELD_IS_BLOCK;
5163 else
5164 flag |= BLOCK_FIELD_IS_OBJECT;
5165 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005166 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005167 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005168 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005169
5170 // struct __Block_byref_ND ND =
5171 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5172 // initializer-if-any};
5173 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005174 unsigned flags = 0;
5175 if (HasCopyAndDispose)
5176 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005177 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005178 ByrefType.clear();
5179 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005180 std::string ForwardingCastType("(");
5181 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005182 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005183 ByrefType += " " + Name + " = {(void*)";
5184 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005185 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005186 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005187 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005188 ByrefType += "sizeof(";
5189 RewriteByRefString(ByrefType, Name, ND);
5190 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005191 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005192 ByrefType += ", __Block_byref_id_object_copy_";
5193 ByrefType += utostr(flag);
5194 ByrefType += ", __Block_byref_id_object_dispose_";
5195 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005196 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005197 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00005198 unsigned nameSize = Name.size();
5199 // for block or function pointer declaration. Name is aleady
5200 // part of the declaration.
5201 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5202 nameSize = 1;
5203 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005204 }
5205 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005206 SourceLocation startLoc;
5207 Expr *E = ND->getInit();
5208 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5209 startLoc = ECE->getLParenLoc();
5210 else
5211 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005212 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005213 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005214 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005215 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005216 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005217 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005218 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005219 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005220 ByrefType += "sizeof(";
5221 RewriteByRefString(ByrefType, Name, ND);
5222 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005223 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005224 ByrefType += "__Block_byref_id_object_copy_";
5225 ByrefType += utostr(flag);
5226 ByrefType += ", __Block_byref_id_object_dispose_";
5227 ByrefType += utostr(flag);
5228 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005229 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005230 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005231
5232 // Complete the newly synthesized compound expression by inserting a right
5233 // curly brace before the end of the declaration.
5234 // FIXME: This approach avoids rewriting the initializer expression. It
5235 // also assumes there is only one declarator. For example, the following
5236 // isn't currently supported by this routine (in general):
5237 //
5238 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5239 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005240 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5241 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00005242 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5243 SourceLocation semiLoc =
Fariborz Jahanian34c85982010-07-21 17:36:39 +00005244 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00005245
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005246 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005247 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005248 return;
5249}
5250
Mike Stump11289f42009-09-09 15:08:12 +00005251void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005252 // Add initializers for any closure decl refs.
5253 GetBlockDeclRefExprs(Exp->getBody());
5254 if (BlockDeclRefs.size()) {
5255 // Unique all "by copy" declarations.
5256 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005257 if (!BlockDeclRefs[i]->isByRef()) {
5258 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5259 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5260 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5261 }
5262 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005263 // Unique all "by ref" declarations.
5264 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5265 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005266 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5267 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5268 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5269 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005270 }
5271 // Find any imported blocks...they will need special attention.
5272 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005273 if (BlockDeclRefs[i]->isByRef() ||
5274 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005275 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005276 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005277 }
5278}
5279
Daniel Dunbar56df9772010-08-17 22:39:59 +00005280FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005281 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005282 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005283 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5284 SourceLocation(), ID, FType, 0, SC_Extern,
John McCall8e7d6562010-08-26 03:08:43 +00005285 SC_None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005286}
5287
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005288Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5289 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00005290 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00005291 Blocks.push_back(Exp);
5292
5293 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005294
5295 // Add inner imported variables now used in current block.
5296 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005297 if (!InnerBlockDeclRefs.empty()) {
5298 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5299 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5300 ValueDecl *VD = Exp->getDecl();
5301 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005302 // We need to save the copied-in variables in nested
5303 // blocks because it is needed at the end for some of the API generations.
5304 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005305 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5306 BlockDeclRefs.push_back(Exp);
5307 BlockByCopyDeclsPtrSet.insert(VD);
5308 BlockByCopyDecls.push_back(VD);
5309 }
5310 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5311 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5312 BlockDeclRefs.push_back(Exp);
5313 BlockByRefDeclsPtrSet.insert(VD);
5314 BlockByRefDecls.push_back(VD);
5315 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005316 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005317 // Find any imported blocks...they will need special attention.
5318 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5319 if (InnerBlockDeclRefs[i]->isByRef() ||
5320 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5321 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5322 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005323 }
5324 InnerDeclRefsCount.push_back(countOfInnerDecls);
5325
Steve Narofff4b992a2008-10-28 20:29:00 +00005326 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005327
Steve Narofff4b992a2008-10-28 20:29:00 +00005328 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005329 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005330 else if (CurMethodDef)
5331 BuildUniqueMethodName(FuncName, CurMethodDef);
5332 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005333 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005334
Steve Narofff4b992a2008-10-28 20:29:00 +00005335 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005336
Steve Narofff4b992a2008-10-28 20:29:00 +00005337 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5338 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005339
Steve Narofff4b992a2008-10-28 20:29:00 +00005340 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005341 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5342 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005343
5344 FunctionDecl *FD;
5345 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005346
Steve Narofff4b992a2008-10-28 20:29:00 +00005347 // Simulate a contructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00005348 FD = SynthBlockInitFunctionDecl(Tag);
John McCall7decc9e2010-11-18 06:31:45 +00005349 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5350 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005351
Steve Narofff4b992a2008-10-28 20:29:00 +00005352 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005353
Steve Naroffe2514232008-10-29 21:23:59 +00005354 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00005355 FD = SynthBlockInitFunctionDecl(Func);
John McCall7decc9e2010-11-18 06:31:45 +00005356 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek5a201952009-02-07 01:47:29 +00005357 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005358 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005359 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005360 InitExprs.push_back(castExpr);
5361
Steve Naroff30484702009-12-06 21:14:13 +00005362 // Initialize the block descriptor.
5363 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005364
Abramo Bagnaradff19302011-03-08 08:55:46 +00005365 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5366 SourceLocation(), SourceLocation(),
5367 &Context->Idents.get(DescData.c_str()),
5368 Context->VoidPtrTy, 0,
5369 SC_Static, SC_None);
John McCall7decc9e2010-11-18 06:31:45 +00005370 UnaryOperator *DescRefExpr =
5371 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5372 Context->VoidPtrTy,
5373 VK_LValue,
5374 SourceLocation()),
5375 UO_AddrOf,
5376 Context->getPointerType(Context->VoidPtrTy),
5377 VK_RValue, OK_Ordinary,
5378 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00005379 InitExprs.push_back(DescRefExpr);
5380
Steve Narofff4b992a2008-10-28 20:29:00 +00005381 // Add initializers for any closure decl refs.
5382 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005383 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005384 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005385 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005386 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005387 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005388 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00005389 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005390 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5391 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005392 if (HasLocalVariableExternalStorage(*I)) {
5393 QualType QT = (*I)->getType();
5394 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005395 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5396 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005397 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005398 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005399 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005400 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5401 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005402 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00005403 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005404 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00005405 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005406 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5407 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005408 if (HasLocalVariableExternalStorage(*I)) {
5409 QualType QT = (*I)->getType();
5410 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00005411 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5412 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005413 }
5414
Steve Narofff4b992a2008-10-28 20:29:00 +00005415 }
Mike Stump11289f42009-09-09 15:08:12 +00005416 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005417 }
5418 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005419 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005420 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005421 ValueDecl *ND = (*I);
5422 std::string Name(ND->getNameAsString());
5423 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00005424 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005425 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5426 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005427 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00005428 SourceLocation(), SourceLocation(),
5429 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005430 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5431 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5432
Daniel Dunbar56df9772010-08-17 22:39:59 +00005433 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall7decc9e2010-11-18 06:31:45 +00005434 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5435 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00005436 bool isNestedCapturedVar = false;
5437 if (block)
5438 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5439 ce = block->capture_end(); ci != ce; ++ci) {
5440 const VarDecl *variable = ci->getVariable();
5441 if (variable == ND && ci->isNested()) {
5442 assert (ci->isByRef() &&
5443 "SynthBlockInitExpr - captured block variable is not byref");
5444 isNestedCapturedVar = true;
5445 break;
5446 }
5447 }
5448 // captured nested byref variable has its address passed. Do not take
5449 // its address again.
5450 if (!isNestedCapturedVar)
5451 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00005452 Context->getPointerType(Exp->getType()),
5453 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005454 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005455 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005456 }
5457 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005458 if (ImportedBlockDecls.size()) {
5459 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5460 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005461 unsigned IntSize =
5462 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005463 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5464 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005465 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005466 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005467 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCall7decc9e2010-11-18 06:31:45 +00005468 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00005469 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005470 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00005471 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00005472 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00005473 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005474 BlockDeclRefs.clear();
5475 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005476 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005477 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005478 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005479 ImportedBlockDecls.clear();
5480 return NewRep;
5481}
5482
Fariborz Jahanian74405b02011-02-24 21:29:21 +00005483bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5484 if (const ObjCForCollectionStmt * CS =
5485 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5486 return CS->getElement() == DS;
5487 return false;
5488}
5489
Steve Narofff4b992a2008-10-28 20:29:00 +00005490//===----------------------------------------------------------------------===//
5491// Function Body / Expression rewriting
5492//===----------------------------------------------------------------------===//
5493
Steve Naroff4588d0f2008-12-04 16:24:46 +00005494// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5495// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5496// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5497// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5498// Since the rewriter isn't capable of rewriting rewritten code, it's important
5499// we get this right.
5500void RewriteObjC::CollectPropertySetters(Stmt *S) {
5501 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00005502 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff4588d0f2008-12-04 16:24:46 +00005503 if (*CI)
5504 CollectPropertySetters(*CI);
5505
5506 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5507 if (BinOp->isAssignmentOp()) {
John McCallb7bd14f2010-12-02 01:19:52 +00005508 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5509 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005510 }
5511 }
5512}
5513
Steve Narofff4b992a2008-10-28 20:29:00 +00005514Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005515 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005516 isa<DoStmt>(S) || isa<ForStmt>(S))
5517 Stmts.push_back(S);
5518 else if (isa<ObjCForCollectionStmt>(S)) {
5519 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005520 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005521 }
Mike Stump11289f42009-09-09 15:08:12 +00005522
Steve Narofff4b992a2008-10-28 20:29:00 +00005523 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005524
Steve Narofff4b992a2008-10-28 20:29:00 +00005525 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00005526 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00005527 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005528 Stmt *newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005529 Stmt *ChildStmt = (*CI);
5530 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005531 Expr *OldBase = IvarRefExpr->getBase();
5532 bool replaced = false;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005533 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005534 if (replaced) {
5535 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5536 ReplaceStmt(OldBase, IRE->getBase());
5537 else
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005538 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005539 }
5540 }
5541 else
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005542 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5543 if (newStmt) {
5544 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5545 if (PropSetters[PropOrImplicitRefExpr] == S) {
5546 S = newStmt;
5547 newStmt = 0;
5548 }
5549 if (newStmt)
5550 *CI = newStmt;
5551 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005552 // If dealing with an assignment with LHS being a property reference
5553 // expression, the entire assignment tree is rewritten into a property
5554 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5555 // RHS again.
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005556 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCallb7bd14f2010-12-02 01:19:52 +00005557 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanianfef5d162010-10-11 22:21:03 +00005558 if (PropSetters[Exp]) {
5559 ++CI;
5560 continue;
5561 }
Fariborz Jahanian163488f2010-10-08 21:12:22 +00005562 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00005563 }
Mike Stump11289f42009-09-09 15:08:12 +00005564
Steve Narofff4b992a2008-10-28 20:29:00 +00005565 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005566 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005567 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5568 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005569 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005570 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005571 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005572 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005573 Stmt *SaveCurrentBody = CurrentBody;
5574 CurrentBody = BE->getBody();
Fariborz Jahanianeae9c0e2011-04-08 23:48:29 +00005575 CollectPropertySetters(CurrentBody);
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005576 PropParentMap = 0;
Steve Narofff4b992a2008-10-28 20:29:00 +00005577 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00005578 CurrentBody = SaveCurrentBody;
5579 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005580 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005581 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00005582 std::string Str = Rewrite.ConvertToString(BE->getBody());
Steve Naroffd8907b72008-10-29 18:15:37 +00005583 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005584
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005585 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5586
Steve Narofff4b992a2008-10-28 20:29:00 +00005587 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005588 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005589 return blockTranscribed;
5590 }
5591 // Handle specific things.
5592 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5593 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005594
John McCallb7bd14f2010-12-02 01:19:52 +00005595 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005596 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5597 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5598
5599 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroff4588d0f2008-12-04 16:24:46 +00005600 if (BinOp) {
5601 // Because the rewriter doesn't allow us to rewrite rewritten code,
5602 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005603 DisableReplaceStmt = true;
5604 // Save the source range. Even if we disable the replacement, the
5605 // rewritten node will have been inserted into the tree. If the synthesized
5606 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005607 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005608 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5609 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005610 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanian9c07e172010-10-14 23:31:39 +00005611 // Need to rewrite the ivar access expression if need be.
5612 if (isa<ObjCIvarRefExpr>(newStmt)) {
5613 bool replaced = false;
5614 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5615 }
5616
Steve Naroff08628db2008-12-09 12:56:34 +00005617 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005618 //
5619 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5620 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5621 // to see the original expression). Consider this example:
5622 //
5623 // Foo *obj1, *obj2;
5624 //
5625 // obj1.i = [obj2 rrrr];
5626 //
5627 // 'BinOp' for the previous expression looks like:
5628 //
5629 // (BinaryOperator 0x231ccf0 'int' '='
5630 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5631 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5632 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5633 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5634 //
5635 // 'newStmt' represents the rewritten message expression. For example:
5636 //
5637 // (CallExpr 0x231d300 'id':'struct objc_object *'
5638 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5639 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5640 // (CStyleCastExpr 0x231d220 'void *'
5641 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5642 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005643 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff22216db2008-12-04 23:50:32 +00005644 // can be used as the setter argument. ReplaceStmt() will still 'see'
5645 // the original RHS (since we haven't altered BinOp).
5646 //
Mike Stump11289f42009-09-09 15:08:12 +00005647 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005648 // node. As a result, we now leak the original AST nodes.
5649 //
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005650 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005651 } else {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005652 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005653 }
5654 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00005655
Steve Narofff4b992a2008-10-28 20:29:00 +00005656 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5657 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005658
Steve Narofff4b992a2008-10-28 20:29:00 +00005659 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5660 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005661
Steve Narofff4b992a2008-10-28 20:29:00 +00005662 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005663#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005664 // Before we rewrite it, put the original message expression in a comment.
5665 SourceLocation startLoc = MessExpr->getLocStart();
5666 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005667
Steve Narofff4b992a2008-10-28 20:29:00 +00005668 const char *startBuf = SM->getCharacterData(startLoc);
5669 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005670
Steve Narofff4b992a2008-10-28 20:29:00 +00005671 std::string messString;
5672 messString += "// ";
5673 messString.append(startBuf, endBuf-startBuf+1);
5674 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005675
5676 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005677 // InsertText(clang::SourceLocation, char const*, unsigned int).
5678 // InsertText(startLoc, messString.c_str(), messString.size());
5679 // Tried this, but it didn't work either...
5680 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005681#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005682 return RewriteMessageExpr(MessExpr);
5683 }
Mike Stump11289f42009-09-09 15:08:12 +00005684
Steve Narofff4b992a2008-10-28 20:29:00 +00005685 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5686 return RewriteObjCTryStmt(StmtTry);
5687
5688 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5689 return RewriteObjCSynchronizedStmt(StmtTry);
5690
5691 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5692 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005693
Steve Narofff4b992a2008-10-28 20:29:00 +00005694 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5695 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005696
5697 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005698 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005699 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005700 OrigStmtRange.getEnd());
5701 if (BreakStmt *StmtBreakStmt =
5702 dyn_cast<BreakStmt>(S))
5703 return RewriteBreakStmt(StmtBreakStmt);
5704 if (ContinueStmt *StmtContinueStmt =
5705 dyn_cast<ContinueStmt>(S))
5706 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005707
5708 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005709 // and cast exprs.
5710 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5711 // FIXME: What we're doing here is modifying the type-specifier that
5712 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005713 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005714 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5715 // the context of an ObjCForCollectionStmt. For example:
5716 // NSArray *someArray;
5717 // for (id <FooProtocol> index in someArray) ;
5718 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5719 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00005720 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005721 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005722
Steve Narofff4b992a2008-10-28 20:29:00 +00005723 // Blocks rewrite rules.
5724 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5725 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005726 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005727 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005728 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005729 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005730 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005731 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005732 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005733 if (VD->hasAttr<BlocksAttr>()) {
5734 static unsigned uniqueByrefDeclCount = 0;
5735 assert(!BlockByRefDeclNo.count(ND) &&
5736 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5737 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005738 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005739 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005740 else
5741 RewriteTypeOfDecl(VD);
5742 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005743 }
Richard Smithdda56e42011-04-15 14:24:37 +00005744 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005745 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005746 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005747 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005748 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5749 }
5750 }
5751 }
Mike Stump11289f42009-09-09 15:08:12 +00005752
Steve Narofff4b992a2008-10-28 20:29:00 +00005753 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5754 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005755
5756 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005757 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5758 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005759 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5760 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005761 && "Statement stack mismatch");
5762 Stmts.pop_back();
5763 }
5764 // Handle blocks rewriting.
5765 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5766 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005767 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005768 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005769 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5770 ValueDecl *VD = DRE->getDecl();
5771 if (VD->hasAttr<BlocksAttr>())
5772 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005773 if (HasLocalVariableExternalStorage(VD))
5774 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005775 }
5776
Steve Narofff4b992a2008-10-28 20:29:00 +00005777 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005778 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005779 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005780 ReplaceStmt(S, BlockCall);
5781 return BlockCall;
5782 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005783 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005784 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005785 RewriteCastExpr(CE);
5786 }
5787#if 0
5788 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005789 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5790 ICE->getSubExpr(),
5791 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005792 // Get the new text.
5793 std::string SStr;
5794 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005795 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005796 const std::string &Str = Buf.str();
5797
5798 printf("CAST = %s\n", &Str[0]);
5799 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5800 delete S;
5801 return Replacement;
5802 }
5803#endif
5804 // Return this stmt unmodified.
5805 return S;
5806}
5807
Steve Naroffe70a52a2009-12-05 15:55:59 +00005808void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5809 for (RecordDecl::field_iterator i = RD->field_begin(),
5810 e = RD->field_end(); i != e; ++i) {
5811 FieldDecl *FD = *i;
5812 if (isTopLevelBlockPointerType(FD->getType()))
5813 RewriteBlockPointerDecl(FD);
5814 if (FD->getType()->isObjCQualifiedIdType() ||
5815 FD->getType()->isObjCQualifiedInterfaceType())
5816 RewriteObjCQualifiedInterfaceTypes(FD);
5817 }
5818}
5819
Steve Narofff4b992a2008-10-28 20:29:00 +00005820/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5821/// main file of the input.
5822void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005824 if (FD->isOverloadedOperator())
5825 return;
Mike Stump11289f42009-09-09 15:08:12 +00005826
Steve Narofff4b992a2008-10-28 20:29:00 +00005827 // Since function prototypes don't have ParmDecl's, we check the function
5828 // prototype. This enables us to rewrite function declarations and
5829 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005830 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005831
Sebastian Redla7b98a72009-04-26 20:35:05 +00005832 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis568bc842010-07-07 11:31:34 +00005833 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005834 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005835 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005836 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005837 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005838 Body =
5839 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5840 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005841 CurrentBody = 0;
5842 if (PropParentMap) {
5843 delete PropParentMap;
5844 PropParentMap = 0;
5845 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005846 // This synthesizes and inserts the block "impl" struct, invoke function,
5847 // and any copy/dispose helper functions.
5848 InsertBlockLiteralsWithinFunction(FD);
5849 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005850 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005851 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005852 return;
5853 }
5854 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005855 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005856 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005857 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005858 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005859 Body =
5860 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5861 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005862 CurrentBody = 0;
5863 if (PropParentMap) {
5864 delete PropParentMap;
5865 PropParentMap = 0;
5866 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005867 InsertBlockLiteralsWithinMethod(MD);
5868 CurMethodDef = 0;
5869 }
5870 }
5871 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5872 ClassImplementation.push_back(CI);
5873 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5874 CategoryImplementation.push_back(CI);
5875 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5876 RewriteForwardClassDecl(CD);
5877 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5878 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005879 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005880 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005881 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005882 CheckFunctionPointerDecl(VD->getType(), VD);
5883 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005884 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005885 RewriteCastExpr(CE);
5886 }
5887 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005888 } else if (VD->getType()->isRecordType()) {
5889 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5890 if (RD->isDefinition())
5891 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005892 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005893 if (VD->getInit()) {
5894 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005895 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005896 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005897 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005898 CurrentBody = 0;
5899 if (PropParentMap) {
5900 delete PropParentMap;
5901 PropParentMap = 0;
5902 }
Mike Stump11289f42009-09-09 15:08:12 +00005903 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar56df9772010-08-17 22:39:59 +00005904 VD->getName());
Steve Naroffd8907b72008-10-29 18:15:37 +00005905 GlobalVarDecl = 0;
5906
5907 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005908 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005909 RewriteCastExpr(CE);
5910 }
5911 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005912 return;
5913 }
Richard Smithdda56e42011-04-15 14:24:37 +00005914 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005915 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005916 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005917 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005918 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5919 return;
5920 }
5921 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005922 if (RD->isDefinition())
5923 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005924 return;
5925 }
5926 // Nothing yet.
5927}
5928
Chris Lattnercf169832009-03-28 04:11:33 +00005929void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005930 if (Diags.hasErrorOccurred())
5931 return;
Mike Stump11289f42009-09-09 15:08:12 +00005932
Steve Narofff4b992a2008-10-28 20:29:00 +00005933 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005934
Steve Naroffd9803712009-04-29 16:37:50 +00005935 // Here's a great place to add any extra declarations that may be needed.
5936 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005937 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005938 E = ProtocolExprDecls.end(); I != E; ++I)
5939 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5940
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005941 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005942 if (ClassImplementation.size() || CategoryImplementation.size())
5943 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005944
Steve Narofff4b992a2008-10-28 20:29:00 +00005945 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5946 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005947 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005948 Rewrite.getRewriteBufferFor(MainFileID)) {
5949 //printf("Changed:\n");
5950 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5951 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005952 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005953 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005954
Steve Naroffd9803712009-04-29 16:37:50 +00005955 if (ClassImplementation.size() || CategoryImplementation.size() ||
5956 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005957 // Rewrite Objective-c meta data*
5958 std::string ResultStr;
5959 SynthesizeMetaDataIntoBuffer(ResultStr);
5960 // Emit metadata.
5961 *OutFile << ResultStr;
5962 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005963 OutFile->flush();
5964}