blob: 35d7cc8e1fa7c60ed753323c093b415946ce4434 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremenek79b50cb2008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000046 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner569faa62007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000051
Ted Kremenek42730c52008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000060
Steve Naroff47e7fa22008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffe9780582007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000074
Steve Naroff0add5d22007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000078
Fariborz Jahanian22277422008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff764c1ae2007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000086
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Narofffef037c2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +000099
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000111 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner12499682008-01-31 19:38:44 +0000118
Chris Lattner569faa62007-10-11 18:38:32 +0000119
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerb1548372008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000133 return;
134
Chris Lattnerb1548372008-01-31 19:37:57 +0000135 SourceRange Range = Old->getSourceRange();
136 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
137 0, 0, &Range, 1);
138 }
139
Steve Narofffef037c2008-03-27 22:29:16 +0000140 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
141 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000142 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000143 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000144 SilenceRewriteMacroWarning)
145 return;
146
147 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
148 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000149
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000150 void RemoveText(SourceLocation Loc, unsigned StrLen) {
151 // If removal succeeded or warning disabled return with no warning.
152 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
153 return;
154
155 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
156 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000157
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000158 void ReplaceText(SourceLocation Start, unsigned OrigLength,
159 const char *NewStr, unsigned NewLength) {
160 // If removal succeeded or warning disabled return with no warning.
161 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
162 SilenceRewriteMacroWarning)
163 return;
164
165 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
166 }
167
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000168 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000169 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000170 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000171 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000172 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000175 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
176 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
177 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
178 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
179 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000189
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff02a82aa2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000222
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000226
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000229
Ted Kremenek42730c52008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000237
Chris Lattner0be08822008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000247 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000248 void RewriteImplementations(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000249
250 // Block rewriting.
251 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
252 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
253
254 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
255 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
256
Steve Naroff80c54752008-10-29 18:15:37 +0000257 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000258 void RewriteBlockCall(CallExpr *Exp);
259 void RewriteBlockPointerDecl(NamedDecl *VD);
260 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
261 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
262
263 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
264 const char *funcName, std::string Tag);
265 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
266 const char *funcName, std::string Tag);
267 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
268 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000269 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000270 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
271 const char *FunName);
272
273 void CollectBlockDeclRefInfo(BlockExpr *Exp);
274 void GetBlockCallExprs(Stmt *S);
275 void GetBlockDeclRefExprs(Stmt *S);
276
277 // We avoid calling Type::isBlockPointerType(), since it operates on the
278 // canonical type. We only care if the top-level type is a closure pointer.
279 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
280
281 // FIXME: This predicate seems like it would be useful to add to ASTContext.
282 bool isObjCType(QualType T) {
283 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
284 return false;
285
286 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
287
288 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
289 OCT == Context->getCanonicalType(Context->getObjCClassType()))
290 return true;
291
292 if (const PointerType *PT = OCT->getAsPointerType()) {
293 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
294 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
295 return true;
296 }
297 return false;
298 }
299 bool PointerTypeTakesAnyBlockArguments(QualType QT);
300 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000301 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000302
303 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000304 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000305 };
306}
307
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000308void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
309 NamedDecl *D) {
310 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
311 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
312 E = fproto->arg_type_end(); I && (I != E); ++I)
313 if (isBlockPointerType(*I)) {
314 // All the args are checked/rewritten. Don't call twice!
315 RewriteBlockPointerDecl(D);
316 break;
317 }
318 }
319}
320
321void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
322 const PointerType *PT = funcType->getAsPointerType();
323 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
324 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
325}
326
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000327static bool IsHeaderFile(const std::string &Filename) {
328 std::string::size_type DotPos = Filename.rfind('.');
329
330 if (DotPos == std::string::npos) {
331 // no file extension
332 return false;
333 }
334
335 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
336 // C header: .h
337 // C++ header: .hh or .H;
338 return Ext == "h" || Ext == "hh" || Ext == "H";
339}
340
Steve Naroff44e81222008-04-14 22:03:09 +0000341RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000342 Diagnostic &D, const LangOptions &LOpts)
343 : Diags(D), LangOpts(LOpts) {
344 IsHeader = IsHeaderFile(inFile);
345 InFileName = inFile;
346 OutFileName = outFile;
347 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
348 "rewriting sub-expression within a macro (may not be correct)");
349}
350
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000351ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000352 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000353 Diagnostic &Diags,
354 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000355 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000356}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000357
Steve Naroff44e81222008-04-14 22:03:09 +0000358void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000359 Context = &context;
360 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000361 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000362 MsgSendFunctionDecl = 0;
363 MsgSendSuperFunctionDecl = 0;
364 MsgSendStretFunctionDecl = 0;
365 MsgSendSuperStretFunctionDecl = 0;
366 MsgSendFpretFunctionDecl = 0;
367 GetClassFunctionDecl = 0;
368 GetMetaClassFunctionDecl = 0;
369 SelGetUidFunctionDecl = 0;
370 CFStringFunctionDecl = 0;
371 GetProtocolFunctionDecl = 0;
372 ConstantStringClassReference = 0;
373 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000374 CurMethodDef = 0;
375 CurFunctionDef = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000376 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000377 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000378 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000379 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000380 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000381
382 // Get the ID and start/end of the main file.
383 MainFileID = SM->getMainFileID();
384 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
385 MainFileStart = MainBuf->getBufferStart();
386 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000387
Chris Lattner12499682008-01-31 19:38:44 +0000388 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000389
Chris Lattner12499682008-01-31 19:38:44 +0000390 // declaring objc_selector outside the parameter list removes a silly
391 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000392 if (IsHeader)
393 Preamble = "#pragma once\n";
394 Preamble += "struct objc_selector; struct objc_class;\n";
395 Preamble += "#ifndef OBJC_SUPER\n";
396 Preamble += "struct objc_super { struct objc_object *object; ";
397 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000398 if (LangOpts.Microsoft) {
399 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000400 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
401 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000402 }
Steve Narofffef037c2008-03-27 22:29:16 +0000403 Preamble += "};\n";
404 Preamble += "#define OBJC_SUPER\n";
405 Preamble += "#endif\n";
406 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
407 Preamble += "typedef struct objc_object Protocol;\n";
408 Preamble += "#define _REWRITER_typedef_Protocol\n";
409 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000410 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000411 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
412 else
413 Preamble += "#define __OBJC_RW_EXTERN extern\n";
414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000420 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000422 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000423 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000427 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000428 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
429 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000433 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000434 // @synchronized hooks.
435 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000437 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000438 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
439 Preamble += "struct __objcFastEnumerationState {\n\t";
440 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000441 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000442 Preamble += "unsigned long *mutationsPtr;\n\t";
443 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000444 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000445 Preamble += "#define __FASTENUMERATIONSTATE\n";
446 Preamble += "#endif\n";
447 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
448 Preamble += "struct __NSConstantStringImpl {\n";
449 Preamble += " int *isa;\n";
450 Preamble += " int flags;\n";
451 Preamble += " char *str;\n";
452 Preamble += " long length;\n";
453 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000454 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
455 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
456 Preamble += "#else\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000457 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000458 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000459 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
460 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000461 // Blocks preamble.
462 Preamble += "#ifndef BLOCK_IMPL\n";
463 Preamble += "#define BLOCK_IMPL\n";
464 Preamble += "struct __block_impl {\n";
465 Preamble += " void *isa;\n";
466 Preamble += " int Flags;\n";
467 Preamble += " int Size;\n";
468 Preamble += " void *FuncPtr;\n";
469 Preamble += "};\n";
470 Preamble += "enum {\n";
471 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
472 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
473 Preamble += "};\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000474 Preamble += "// Runtime copy/destroy helper functions\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
481 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000482 if (LangOpts.Microsoft) {
483 Preamble += "#undef __OBJC_RW_EXTERN\n";
484 Preamble += "#define __attribute__(X)\n";
485 }
Chris Lattner12499682008-01-31 19:38:44 +0000486}
487
488
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000489//===----------------------------------------------------------------------===//
490// Top Level Driver Code
491//===----------------------------------------------------------------------===//
492
Steve Naroff44e81222008-04-14 22:03:09 +0000493void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000494 // Two cases: either the decl could be in the main file, or it could be in a
495 // #included file. If the former, rewrite it now. If the later, check to see
496 // if we rewrote the #include/#import.
497 SourceLocation Loc = D->getLocation();
498 Loc = SM->getLogicalLoc(Loc);
499
500 // If this is for a builtin, ignore it.
501 if (Loc.isInvalid()) return;
502
Steve Naroffe9780582007-10-23 23:50:29 +0000503 // Look for built-in declarations that we need to refer during the rewrite.
504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000505 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000506 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000507 // declared in <Foundation/NSString.h>
508 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
509 ConstantStringClassReference = FVD;
510 return;
511 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000512 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000513 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000514 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000515 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000516 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000517 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000518 } else if (ObjCForwardProtocolDecl *FP =
519 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000520 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000521 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000522 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000523 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000524 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000525}
526
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000527//===----------------------------------------------------------------------===//
528// Syntactic (non-AST) Rewriting Code
529//===----------------------------------------------------------------------===//
530
Steve Naroff44e81222008-04-14 22:03:09 +0000531void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000532 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
533 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
534 const char *MainBufStart = MainBuf.first;
535 const char *MainBufEnd = MainBuf.second;
536 size_t ImportLen = strlen("import");
537 size_t IncludeLen = strlen("include");
538
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000539 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000540 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
541 if (*BufPtr == '#') {
542 if (++BufPtr == MainBufEnd)
543 return;
544 while (*BufPtr == ' ' || *BufPtr == '\t')
545 if (++BufPtr == MainBufEnd)
546 return;
547 if (!strncmp(BufPtr, "import", ImportLen)) {
548 // replace import with include
549 SourceLocation ImportLoc =
550 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000551 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000552 BufPtr += ImportLen;
553 }
554 }
555 }
Chris Lattner74db1682007-10-16 21:07:07 +0000556}
557
Steve Naroff44e81222008-04-14 22:03:09 +0000558void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000559 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
560 const char *MainBufStart = MainBuf.first;
561 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000562
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000563 // Loop over the whole file, looking for tabs.
564 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
565 if (*BufPtr != '\t')
566 continue;
567
568 // Okay, we found a tab. This tab will turn into at least one character,
569 // but it depends on which 'virtual column' it is in. Compute that now.
570 unsigned VCol = 0;
571 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
572 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
573 ++VCol;
574
575 // Okay, now that we know the virtual column, we know how many spaces to
576 // insert. We assume 8-character tab-stops.
577 unsigned Spaces = 8-(VCol & 7);
578
579 // Get the location of the tab.
580 SourceLocation TabLoc =
581 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
582
583 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000584 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000585 }
Chris Lattner569faa62007-10-11 18:38:32 +0000586}
587
588
Steve Naroff44e81222008-04-14 22:03:09 +0000589void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000590 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000591 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000592
593 // Get the start location and compute the semi location.
594 SourceLocation startLoc = ClassDecl->getLocation();
595 const char *startBuf = SM->getCharacterData(startLoc);
596 const char *semiPtr = strchr(startBuf, ';');
597
598 // Translate to typedef's that forward reference structs with the same name
599 // as the class. As a convenience, we include the original declaration
600 // as a comment.
601 std::string typedefString;
602 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000603 typedefString.append(startBuf, semiPtr-startBuf+1);
604 typedefString += "\n";
605 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000606 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000607 typedefString += "#ifndef _REWRITER_typedef_";
608 typedefString += ForwardDecl->getName();
609 typedefString += "\n";
610 typedefString += "#define _REWRITER_typedef_";
611 typedefString += ForwardDecl->getName();
612 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000613 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000614 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000615 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000616 }
617
618 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000619 ReplaceText(startLoc, semiPtr-startBuf+1,
620 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000621}
622
Steve Naroff44e81222008-04-14 22:03:09 +0000623void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000624 SourceLocation LocStart = Method->getLocStart();
625 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000626
Steve Naroff2ce399a2007-12-14 23:37:57 +0000627 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000628 InsertText(LocStart, "#if 0\n", 6);
629 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000630 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000631 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000632 }
633}
634
Steve Naroff44e81222008-04-14 22:03:09 +0000635void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000636{
Chris Lattnercffe3662008-03-16 21:23:50 +0000637 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000638 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000639 SourceLocation Loc = Property->getLocation();
640
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000641 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000642
643 // FIXME: handle properties that are declared across multiple lines.
644 }
645}
646
Steve Naroff44e81222008-04-14 22:03:09 +0000647void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000648 SourceLocation LocStart = CatDecl->getLocStart();
649
650 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000651 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000652
Ted Kremenek42730c52008-01-07 19:49:32 +0000653 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000654 E = CatDecl->instmeth_end(); I != E; ++I)
655 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000656 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000657 E = CatDecl->classmeth_end(); I != E; ++I)
658 RewriteMethodDeclaration(*I);
659
Steve Naroff667f1682007-10-30 13:30:57 +0000660 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000661 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000662}
663
Steve Naroff44e81222008-04-14 22:03:09 +0000664void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000666
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000667 SourceLocation LocStart = PDecl->getLocStart();
668
669 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000670 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000671
Ted Kremenek42730c52008-01-07 19:49:32 +0000672 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000673 E = PDecl->instmeth_end(); I != E; ++I)
674 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000675 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000676 E = PDecl->classmeth_end(); I != E; ++I)
677 RewriteMethodDeclaration(*I);
678
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000679 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000680 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000681 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000682
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000683 // Must comment out @optional/@required
684 const char *startBuf = SM->getCharacterData(LocStart);
685 const char *endBuf = SM->getCharacterData(LocEnd);
686 for (const char *p = startBuf; p < endBuf; p++) {
687 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
688 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000689 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000690 ReplaceText(OptionalLoc, strlen("@optional"),
691 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000692
693 }
694 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
695 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000696 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000697 ReplaceText(OptionalLoc, strlen("@required"),
698 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000699
700 }
701 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000702}
703
Steve Naroff44e81222008-04-14 22:03:09 +0000704void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000705 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000706 if (LocStart.isInvalid())
707 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000708 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000709 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000710}
711
Steve Naroff44e81222008-04-14 22:03:09 +0000712void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000713 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000714 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000715 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000716 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000717 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000718 ResultStr += "id";
Steve Naroff91044cf2008-07-16 14:40:40 +0000719 else if (OMD->getResultType()->isFunctionPointerType()) {
720 // needs special handling, since pointer-to-functions have special
721 // syntax (where a decaration models use).
722 QualType retType = OMD->getResultType();
723 if (const PointerType* PT = retType->getAsPointerType()) {
724 QualType PointeeTy = PT->getPointeeType();
725 if ((FPRetType = PointeeTy->getAsFunctionType())) {
726 ResultStr += FPRetType->getResultType().getAsString();
727 ResultStr += "(*";
728 }
729 }
730 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000731 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000732 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000733
734 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000735 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000736
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000737 if (OMD->isInstance())
738 NameStr += "_I_";
739 else
740 NameStr += "_C_";
741
742 NameStr += OMD->getClassInterface()->getName();
743 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000744
745 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000746 if (ObjCCategoryImplDecl *CID =
747 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000748 NameStr += CID->getName();
749 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000750 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000751 // Append selector names, replacing ':' with '_'
752 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000753 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000754 else {
755 std::string selString = OMD->getSelector().getName();
756 int len = selString.size();
757 for (int i = 0; i < len; i++)
758 if (selString[i] == ':')
759 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000760 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000761 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000762 // Remember this name for metadata emission
763 MethodInternalNames[OMD] = NameStr;
764 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000765
766 // Rewrite arguments
767 ResultStr += "(";
768
769 // invisible arguments
770 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000771 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000772 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000773 if (!LangOpts.Microsoft) {
774 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
775 ResultStr += "struct ";
776 }
777 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000778 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000779 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000780 }
781 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000782 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000783
784 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000785 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000786 ResultStr += " _cmd";
787
788 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000789 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000790 ParmVarDecl *PDecl = OMD->getParamDecl(i);
791 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000792 if (PDecl->getType()->isObjCQualifiedIdType()) {
793 ResultStr += "id ";
794 ResultStr += PDecl->getName();
795 } else {
796 std::string Name = PDecl->getName();
Steve Naroff4e2ae512008-10-30 14:45:29 +0000797 if (isBlockPointerType(PDecl->getType())) {
798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
799 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
800 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
801 } else
802 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000803 ResultStr += Name;
804 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000805 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000806 if (OMD->isVariadic())
807 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000808 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000809
Steve Naroff91044cf2008-07-16 14:40:40 +0000810 if (FPRetType) {
811 ResultStr += ")"; // close the precedence "scope" for "*".
812
813 // Now, emit the argument types (if any).
814 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
815 ResultStr += "(";
816 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
817 if (i) ResultStr += ", ";
818 std::string ParamStr = FT->getArgType(i).getAsString();
819 ResultStr += ParamStr;
820 }
821 if (FT->isVariadic()) {
822 if (FT->getNumArgs()) ResultStr += ", ";
823 ResultStr += "...";
824 }
825 ResultStr += ")";
826 } else {
827 ResultStr += "()";
828 }
829 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000830}
Steve Naroff44e81222008-04-14 22:03:09 +0000831void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000832 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
833 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000834
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000835 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000836 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000837 else
Chris Lattner6216f292008-01-31 19:42:41 +0000838 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000839
Ted Kremenek42730c52008-01-07 19:49:32 +0000840 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000841 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
842 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000843 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000844 ObjCMethodDecl *OMD = *I;
845 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000846 SourceLocation LocStart = OMD->getLocStart();
847 SourceLocation LocEnd = OMD->getBody()->getLocStart();
848
849 const char *startBuf = SM->getCharacterData(LocStart);
850 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000851 ReplaceText(LocStart, endBuf-startBuf,
852 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000853 }
854
Ted Kremenek42730c52008-01-07 19:49:32 +0000855 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000856 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
857 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000858 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000859 ObjCMethodDecl *OMD = *I;
860 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000861 SourceLocation LocStart = OMD->getLocStart();
862 SourceLocation LocEnd = OMD->getBody()->getLocStart();
863
864 const char *startBuf = SM->getCharacterData(LocStart);
865 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000866 ReplaceText(LocStart, endBuf-startBuf,
867 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000868 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000869 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000870 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000871 else
Chris Lattner6216f292008-01-31 19:42:41 +0000872 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000873}
874
Steve Naroff44e81222008-04-14 22:03:09 +0000875void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000876 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000877 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000878 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000879 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000880 ResultStr += ClassDecl->getName();
881 ResultStr += "\n";
882 ResultStr += "#define _REWRITER_typedef_";
883 ResultStr += ClassDecl->getName();
884 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000885 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000886 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000887 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000888 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000889 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000890 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000891 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000892
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000893 RewriteProperties(ClassDecl->getNumPropertyDecl(),
894 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000895 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000896 E = ClassDecl->instmeth_end(); I != E; ++I)
897 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000898 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000899 E = ClassDecl->classmeth_end(); I != E; ++I)
900 RewriteMethodDeclaration(*I);
901
Steve Naroff1ccf4632007-10-30 03:43:13 +0000902 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000903 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000904}
905
Chris Lattner343c82b2008-05-23 20:40:52 +0000906Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
907 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000908 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000909 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000910 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000911 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
912 // lookup which class implements the instance variable.
913 ObjCInterfaceDecl *clsDeclared = 0;
914 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
915 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
916
917 // Synthesize an explicit cast to gain access to the ivar.
918 std::string RecName = clsDeclared->getIdentifier()->getName();
919 RecName += "_IMPL";
920 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000921 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000922 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +0000923 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
924 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +0000925 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroff7f1412d2008-11-03 23:29:32 +0000926 SourceLocation(), SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +0000927 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000928 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
929 IV->getBase()->getLocEnd(),
930 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000931 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000932 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000933 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
934 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000935 ReplaceStmt(IV, ME);
936 delete IV;
937 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000938 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000939
940 ReplaceStmt(IV->getBase(), PE);
941 // Cannot delete IV->getBase(), since PE points to it.
942 // Replace the old base with the cast. This is important when doing
943 // embedded rewrites. For example, [newInv->_container addObject:0].
944 IV->setBase(PE);
945 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000946 }
Steve Naroffe6155362008-04-18 21:55:08 +0000947 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000948 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
949
950 // Explicit ivar refs need to have a cast inserted.
951 // FIXME: consider sharing some of this code with the code above.
952 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000953 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000954 // lookup which class implements the instance variable.
955 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000956 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000957 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
958
959 // Synthesize an explicit cast to gain access to the ivar.
960 std::string RecName = clsDeclared->getIdentifier()->getName();
961 RecName += "_IMPL";
962 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000963 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000964 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000965 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
966 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +0000967 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroff7f1412d2008-11-03 23:29:32 +0000968 SourceLocation(), SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000969 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000970 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
971 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000972 ReplaceStmt(IV->getBase(), PE);
973 // Cannot delete IV->getBase(), since PE points to it.
974 // Replace the old base with the cast. This is important when doing
975 // embedded rewrites. For example, [newInv->_container addObject:0].
976 IV->setBase(PE);
977 return IV;
978 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000979 }
Steve Naroffe6155362008-04-18 21:55:08 +0000980 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000981}
982
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000983/// SynthCountByEnumWithState - To print:
984/// ((unsigned int (*)
985/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
986/// (void *)objc_msgSend)((id)l_collection,
987/// sel_registerName(
988/// "countByEnumeratingWithState:objects:count:"),
989/// &enumState,
990/// (id *)items, (unsigned int)16)
991///
Steve Naroff44e81222008-04-14 22:03:09 +0000992void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000993 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
994 "id *, unsigned int))(void *)objc_msgSend)";
995 buf += "\n\t\t";
996 buf += "((id)l_collection,\n\t\t";
997 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
998 buf += "\n\t\t";
999 buf += "&enumState, "
1000 "(id *)items, (unsigned int)16)";
1001}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001002
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001003/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1004/// statement to exit to its outer synthesized loop.
1005///
Steve Naroff44e81222008-04-14 22:03:09 +00001006Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001007 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1008 return S;
1009 // replace break with goto __break_label
1010 std::string buf;
1011
1012 SourceLocation startLoc = S->getLocStart();
1013 buf = "goto __break_label_";
1014 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001015 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001016
1017 return 0;
1018}
1019
1020/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1021/// statement to continue with its inner synthesized loop.
1022///
Steve Naroff44e81222008-04-14 22:03:09 +00001023Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001024 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1025 return S;
1026 // replace continue with goto __continue_label
1027 std::string buf;
1028
1029 SourceLocation startLoc = S->getLocStart();
1030 buf = "goto __continue_label_";
1031 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001032 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001033
1034 return 0;
1035}
1036
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001037/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001038/// It rewrites:
1039/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001040
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001041/// Into:
1042/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001043/// type elem;
1044/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001045/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001046/// id l_collection = (id)collection;
1047/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1048/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001049/// if (limit) {
1050/// unsigned long startMutations = *enumState.mutationsPtr;
1051/// do {
1052/// unsigned long counter = 0;
1053/// do {
1054/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001055/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001056/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001057/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001058/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001059/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001060/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1061/// objects:items count:16]);
1062/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001063/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001064/// }
1065/// else
1066/// elem = nil;
1067/// }
1068///
Steve Naroff44e81222008-04-14 22:03:09 +00001069Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001070 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001071 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1072 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1073 "ObjCForCollectionStmt Statement stack mismatch");
1074 assert(!ObjCBcLabelNo.empty() &&
1075 "ObjCForCollectionStmt - Label No stack empty");
1076
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001077 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001078 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001079 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001080 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001081 std::string buf;
1082 buf = "\n{\n\t";
1083 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1084 // type elem;
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001085 ScopedDecl* D = DS->getSolitaryDecl();
1086 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001087 elementTypeAsString = ElementType.getAsString();
1088 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001089 buf += " ";
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001090 elementName = D->getName();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001091 buf += elementName;
1092 buf += ";\n\t";
1093 }
Chris Lattner690c2872008-04-08 05:52:18 +00001094 else {
1095 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001096 elementName = DR->getDecl()->getName();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001097 elementTypeAsString
1098 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001099 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001100
1101 // struct __objcFastEnumerationState enumState = { 0 };
1102 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1103 // id items[16];
1104 buf += "id items[16];\n\t";
1105 // id l_collection = (id)
1106 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001107 // Find start location of 'collection' the hard way!
1108 const char *startCollectionBuf = startBuf;
1109 startCollectionBuf += 3; // skip 'for'
1110 startCollectionBuf = strchr(startCollectionBuf, '(');
1111 startCollectionBuf++; // skip '('
1112 // find 'in' and skip it.
1113 while (*startCollectionBuf != ' ' ||
1114 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1115 (*(startCollectionBuf+3) != ' ' &&
1116 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1117 startCollectionBuf++;
1118 startCollectionBuf += 3;
1119
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001121 ReplaceText(startLoc, startCollectionBuf - startBuf,
1122 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001123 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001124 SourceLocation rightParenLoc = S->getRParenLoc();
1125 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1126 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001127 buf = ";\n\t";
1128
1129 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1130 // objects:items count:16];
1131 // which is synthesized into:
1132 // unsigned int limit =
1133 // ((unsigned int (*)
1134 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1135 // (void *)objc_msgSend)((id)l_collection,
1136 // sel_registerName(
1137 // "countByEnumeratingWithState:objects:count:"),
1138 // (struct __objcFastEnumerationState *)&state,
1139 // (id *)items, (unsigned int)16);
1140 buf += "unsigned long limit =\n\t\t";
1141 SynthCountByEnumWithState(buf);
1142 buf += ";\n\t";
1143 /// if (limit) {
1144 /// unsigned long startMutations = *enumState.mutationsPtr;
1145 /// do {
1146 /// unsigned long counter = 0;
1147 /// do {
1148 /// if (startMutations != *enumState.mutationsPtr)
1149 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001150 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001151 buf += "if (limit) {\n\t";
1152 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1153 buf += "do {\n\t\t";
1154 buf += "unsigned long counter = 0;\n\t\t";
1155 buf += "do {\n\t\t\t";
1156 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1157 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1158 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001159 buf += " = (";
1160 buf += elementTypeAsString;
1161 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001162 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001163 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001164
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001165 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001166 /// } while (counter < limit);
1167 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1168 /// objects:items count:16]);
1169 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001170 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001171 /// }
1172 /// else
1173 /// elem = nil;
1174 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001175 ///
1176 buf = ";\n\t";
1177 buf += "__continue_label_";
1178 buf += utostr(ObjCBcLabelNo.back());
1179 buf += ": ;";
1180 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001181 buf += "} while (counter < limit);\n\t";
1182 buf += "} while (limit = ";
1183 SynthCountByEnumWithState(buf);
1184 buf += ");\n\t";
1185 buf += elementName;
1186 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001187 buf += "__break_label_";
1188 buf += utostr(ObjCBcLabelNo.back());
1189 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001190 buf += "}\n\t";
1191 buf += "else\n\t\t";
1192 buf += elementName;
1193 buf += " = nil;\n";
1194 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001195
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001196 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001197 if (isa<CompoundStmt>(S->getBody())) {
1198 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1199 InsertText(endBodyLoc, buf.c_str(), buf.size());
1200 } else {
1201 /* Need to treat single statements specially. For example:
1202 *
1203 * for (A *a in b) if (stuff()) break;
1204 * for (A *a in b) xxxyy;
1205 *
1206 * The following code simply scans ahead to the semi to find the actual end.
1207 */
1208 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1209 const char *semiBuf = strchr(stmtBuf, ';');
1210 assert(semiBuf && "Can't find ';'");
1211 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1212 InsertText(endBodyLoc, buf.c_str(), buf.size());
1213 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001214 Stmts.pop_back();
1215 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001216 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001217}
1218
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001219/// RewriteObjCSynchronizedStmt -
1220/// This routine rewrites @synchronized(expr) stmt;
1221/// into:
1222/// objc_sync_enter(expr);
1223/// @try stmt @finally { objc_sync_exit(expr); }
1224///
Steve Naroff44e81222008-04-14 22:03:09 +00001225Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001226 // Get the start location and compute the semi location.
1227 SourceLocation startLoc = S->getLocStart();
1228 const char *startBuf = SM->getCharacterData(startLoc);
1229
1230 assert((*startBuf == '@') && "bogus @synchronized location");
1231
1232 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001233 buf = "objc_sync_enter((id)";
1234 const char *lparenBuf = startBuf;
1235 while (*lparenBuf != '(') lparenBuf++;
1236 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001237 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1238 // the sync expression is typically a message expression that's already
1239 // been rewritten! (which implies the SourceLocation's are invalid).
1240 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001241 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001242 while (*endBuf != ')') endBuf--;
1243 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001244 buf = ");\n";
1245 // declare a new scope with two variables, _stack and _rethrow.
1246 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1247 buf += "int buf[18/*32-bit i386*/];\n";
1248 buf += "char *pointers[4];} _stack;\n";
1249 buf += "id volatile _rethrow = 0;\n";
1250 buf += "objc_exception_try_enter(&_stack);\n";
1251 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001252 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001253 startLoc = S->getSynchBody()->getLocEnd();
1254 startBuf = SM->getCharacterData(startLoc);
1255
Steve Naroff027cd0b2008-08-19 13:04:19 +00001256 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001257 SourceLocation lastCurlyLoc = startLoc;
1258 buf = "}\nelse {\n";
1259 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1260 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001261 buf += " objc_sync_exit(";
Douglas Gregor035d0882008-10-28 15:36:24 +00001262 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00001263 S->getSynchExpr(),
1264 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00001265 SourceLocation(), SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001266 std::string syncExprBufS;
1267 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001268 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001269 buf += syncExprBuf.str();
1270 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001271 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1272 buf += "}\n";
1273 buf += "}";
1274
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001275 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001276 return 0;
1277}
1278
Steve Naroff44e81222008-04-14 22:03:09 +00001279Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001280 // Get the start location and compute the semi location.
1281 SourceLocation startLoc = S->getLocStart();
1282 const char *startBuf = SM->getCharacterData(startLoc);
1283
1284 assert((*startBuf == '@') && "bogus @try location");
1285
1286 std::string buf;
1287 // declare a new scope with two variables, _stack and _rethrow.
1288 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1289 buf += "int buf[18/*32-bit i386*/];\n";
1290 buf += "char *pointers[4];} _stack;\n";
1291 buf += "id volatile _rethrow = 0;\n";
1292 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001293 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001294
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001295 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001296
1297 startLoc = S->getTryBody()->getLocEnd();
1298 startBuf = SM->getCharacterData(startLoc);
1299
1300 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001301
Steve Naroffe9f69842007-11-07 04:08:17 +00001302 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001303 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1304 if (catchList) {
1305 startLoc = startLoc.getFileLocWithOffset(1);
1306 buf = " /* @catch begin */ else {\n";
1307 buf += " id _caught = objc_exception_extract(&_stack);\n";
1308 buf += " objc_exception_try_enter (&_stack);\n";
1309 buf += " if (_setjmp(_stack.buf))\n";
1310 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1311 buf += " else { /* @catch continue */";
1312
1313 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001314 } else { /* no catch list */
1315 buf = "}\nelse {\n";
1316 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1317 buf += "}";
1318 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001319 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001320 bool sawIdTypedCatch = false;
1321 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001322 while (catchList) {
1323 Stmt *catchStmt = catchList->getCatchParamStmt();
1324
1325 if (catchList == S->getCatchStmts())
1326 buf = "if ("; // we are generating code for the first catch clause
1327 else
1328 buf = "else if (";
1329 startLoc = catchList->getLocStart();
1330 startBuf = SM->getCharacterData(startLoc);
1331
1332 assert((*startBuf == '@') && "bogus @catch location");
1333
1334 const char *lParenLoc = strchr(startBuf, '(');
1335
Steve Naroff397c4ce2008-02-01 22:08:12 +00001336 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001337 // Now rewrite the body...
1338 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001339 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1340 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001341 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1342 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001343 assert((*bodyBuf == '{') && "bogus @catch body location");
1344
1345 buf += "1) { id _tmp = _caught;";
1346 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1347 buf.c_str(), buf.size());
1348 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek91034202008-10-06 22:39:38 +00001349 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001350 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001351 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001352 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001353 sawIdTypedCatch = true;
1354 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001355 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001356
Ted Kremenek42730c52008-01-07 19:49:32 +00001357 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001358 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001359 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001360 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001361 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001362 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001363 }
1364 }
1365 // Now rewrite the body...
1366 lastCatchBody = catchList->getCatchBody();
1367 SourceLocation rParenLoc = catchList->getRParenLoc();
1368 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1369 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1370 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1371 assert((*rParenBuf == ')') && "bogus @catch paren location");
1372 assert((*bodyBuf == '{') && "bogus @catch body location");
1373
1374 buf = " = _caught;";
1375 // Here we replace ") {" with "= _caught;" (which initializes and
1376 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001377 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001378 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001379 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001380 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001381 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001382 catchList = catchList->getNextCatchStmt();
1383 }
1384 // Complete the catch list...
1385 if (lastCatchBody) {
1386 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001387 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1388 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001389
Steve Naroff31325c12008-09-11 15:29:03 +00001390 // Insert the last (implicit) else clause *before* the right curly brace.
1391 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1392 buf = "} /* last catch end */\n";
1393 buf += "else {\n";
1394 buf += " _rethrow = _caught;\n";
1395 buf += " objc_exception_try_exit(&_stack);\n";
1396 buf += "} } /* @catch end */\n";
1397 if (!S->getFinallyStmt())
1398 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001399 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001400
1401 // Set lastCurlyLoc
1402 lastCurlyLoc = lastCatchBody->getLocEnd();
1403 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001404 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001405 startLoc = finalStmt->getLocStart();
1406 startBuf = SM->getCharacterData(startLoc);
1407 assert((*startBuf == '@') && "bogus @finally start");
1408
1409 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001410 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001411
1412 Stmt *body = finalStmt->getFinallyBody();
1413 SourceLocation startLoc = body->getLocStart();
1414 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001415 assert(*SM->getCharacterData(startLoc) == '{' &&
1416 "bogus @finally body location");
1417 assert(*SM->getCharacterData(endLoc) == '}' &&
1418 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001419
1420 startLoc = startLoc.getFileLocWithOffset(1);
1421 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001422 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001423 endLoc = endLoc.getFileLocWithOffset(-1);
1424 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001425 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001426
1427 // Set lastCurlyLoc
1428 lastCurlyLoc = body->getLocEnd();
Steve Naroff31325c12008-09-11 15:29:03 +00001429 } else { /* no finally clause - make sure we synthesize an implicit one */
1430 buf = "{ /* implicit finally clause */\n";
1431 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1432 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1433 buf += "}";
1434 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001435 }
1436 // Now emit the final closing curly brace...
1437 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1438 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001439 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001440 return 0;
1441}
1442
Steve Naroff44e81222008-04-14 22:03:09 +00001443Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001444 return 0;
1445}
1446
Steve Naroff44e81222008-04-14 22:03:09 +00001447Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001448 return 0;
1449}
1450
Chris Lattnerb1548372008-01-31 19:37:57 +00001451// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001452// the throw expression is typically a message expression that's already
1453// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001454Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001455 // Get the start location and compute the semi location.
1456 SourceLocation startLoc = S->getLocStart();
1457 const char *startBuf = SM->getCharacterData(startLoc);
1458
1459 assert((*startBuf == '@') && "bogus @throw location");
1460
1461 std::string buf;
1462 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001463 if (S->getThrowExpr())
1464 buf = "objc_exception_throw(";
1465 else // add an implicit argument
1466 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001467
1468 // handle "@ throw" correctly.
1469 const char *wBuf = strchr(startBuf, 'w');
1470 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1471 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1472
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001473 const char *semiBuf = strchr(startBuf, ';');
1474 assert((*semiBuf == ';') && "@throw: can't find ';'");
1475 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1476 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001477 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001478 return 0;
1479}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001480
Steve Naroff44e81222008-04-14 22:03:09 +00001481Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001482 // Create a new string expression.
1483 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001484 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001485 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001486 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1487 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001488 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001489 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001490
Chris Lattner4478db92007-11-30 22:53:43 +00001491 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001492 delete Exp;
1493 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001494}
1495
Steve Naroff44e81222008-04-14 22:03:09 +00001496Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001497 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1498 // Create a call to sel_registerName("selName").
1499 llvm::SmallVector<Expr*, 8> SelExprs;
1500 QualType argType = Context->getPointerType(Context->CharTy);
1501 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1502 Exp->getSelector().getName().size(),
1503 false, argType, SourceLocation(),
1504 SourceLocation()));
1505 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1506 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001507 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001508 delete Exp;
1509 return SelExp;
1510}
1511
Steve Naroff44e81222008-04-14 22:03:09 +00001512CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001513 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001514 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001515 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001516
1517 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001518 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001519
1520 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001521 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001522 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1523
1524 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001525
Steve Naroff71226032007-10-24 22:48:43 +00001526 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1527}
1528
Steve Naroffc8a92d12007-11-01 13:24:47 +00001529static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1530 const char *&startRef, const char *&endRef) {
1531 while (startBuf < endBuf) {
1532 if (*startBuf == '<')
1533 startRef = startBuf; // mark the start.
1534 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001535 if (startRef && *startRef == '<') {
1536 endRef = startBuf; // mark the end.
1537 return true;
1538 }
1539 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001540 }
1541 startBuf++;
1542 }
1543 return false;
1544}
1545
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001546static void scanToNextArgument(const char *&argRef) {
1547 int angle = 0;
1548 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1549 if (*argRef == '<')
1550 angle++;
1551 else if (*argRef == '>')
1552 angle--;
1553 argRef++;
1554 }
1555 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1556}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001557
Steve Naroff44e81222008-04-14 22:03:09 +00001558bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001559
Ted Kremenek42730c52008-01-07 19:49:32 +00001560 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001561 return true;
1562
Steve Naroffc8a92d12007-11-01 13:24:47 +00001563 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001564 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001565 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001566 return true; // we have "Class <Protocol> *".
1567 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001568 return false;
1569}
1570
Steve Naroffd06c88d2008-07-29 18:15:38 +00001571void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1572 QualType Type = E->getType();
1573 if (needToScanForQualifiers(Type)) {
1574 SourceLocation Loc = E->getLocStart();
1575 const char *startBuf = SM->getCharacterData(Loc);
1576 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1577 const char *startRef = 0, *endRef = 0;
1578 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1579 // Get the locations of the startRef, endRef.
1580 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1581 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1582 // Comment out the protocol references.
1583 InsertText(LessLoc, "/*", 2);
1584 InsertText(GreaterLoc, "*/", 2);
1585 }
1586 }
1587}
1588
Steve Naroff44e81222008-04-14 22:03:09 +00001589void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001590 SourceLocation Loc;
1591 QualType Type;
1592 const FunctionTypeProto *proto = 0;
1593 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1594 Loc = VD->getLocation();
1595 Type = VD->getType();
1596 }
1597 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1598 Loc = FD->getLocation();
1599 // Check for ObjC 'id' and class types that have been adorned with protocol
1600 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1601 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1602 assert(funcType && "missing function type");
1603 proto = dyn_cast<FunctionTypeProto>(funcType);
1604 if (!proto)
1605 return;
1606 Type = proto->getResultType();
1607 }
1608 else
1609 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001610
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001611 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001612 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001613
1614 const char *endBuf = SM->getCharacterData(Loc);
1615 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001616 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001617 startBuf--; // scan backward (from the decl location) for return type.
1618 const char *startRef = 0, *endRef = 0;
1619 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1620 // Get the locations of the startRef, endRef.
1621 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1622 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1623 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001624 InsertText(LessLoc, "/*", 2);
1625 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001626 }
1627 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001628 if (!proto)
1629 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001630 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001631 const char *startBuf = SM->getCharacterData(Loc);
1632 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001633 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1634 if (needToScanForQualifiers(proto->getArgType(i))) {
1635 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001636
Steve Naroffc8a92d12007-11-01 13:24:47 +00001637 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001638 // scan forward (from the decl location) for argument types.
1639 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001640 const char *startRef = 0, *endRef = 0;
1641 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1642 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001643 SourceLocation LessLoc =
1644 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1645 SourceLocation GreaterLoc =
1646 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001647 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001648 InsertText(LessLoc, "/*", 2);
1649 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001650 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001651 startBuf = ++endBuf;
1652 }
1653 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001654 // If the function name is derived from a macro expansion, then the
1655 // argument buffer will not follow the name. Need to speak with Chris.
1656 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001657 startBuf++; // scan forward (from the decl location) for argument types.
1658 startBuf++;
1659 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001660 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001661}
1662
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001663// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001664void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001665 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1666 llvm::SmallVector<QualType, 16> ArgTys;
1667 ArgTys.push_back(Context->getPointerType(
1668 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001669 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001670 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001671 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001672 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001673 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001674 SelGetUidIdent, getFuncType,
1675 FunctionDecl::Extern, false, 0);
1676}
1677
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001678// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001679void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001680 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1681 llvm::SmallVector<QualType, 16> ArgTys;
1682 ArgTys.push_back(Context->getPointerType(
1683 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001684 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001685 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001686 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001687 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001688 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001689 SelGetProtoIdent, getFuncType,
1690 FunctionDecl::Extern, false, 0);
1691}
1692
Steve Naroff44e81222008-04-14 22:03:09 +00001693void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001694 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001695 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001696 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001697 return;
1698 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001699 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001700}
1701
Steve Naroffbec4bf52008-03-11 17:37:02 +00001702// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001703void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001704 if (SuperContructorFunctionDecl)
1705 return;
1706 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1707 llvm::SmallVector<QualType, 16> ArgTys;
1708 QualType argT = Context->getObjCIdType();
1709 assert(!argT.isNull() && "Can't find 'id' type");
1710 ArgTys.push_back(argT);
1711 ArgTys.push_back(argT);
1712 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1713 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001714 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001715 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001716 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001717 msgSendIdent, msgSendType,
1718 FunctionDecl::Extern, false, 0);
1719}
1720
Steve Naroff02a82aa2007-10-30 23:14:51 +00001721// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001722void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001723 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1724 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001725 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001726 assert(!argT.isNull() && "Can't find 'id' type");
1727 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001728 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001729 assert(!argT.isNull() && "Can't find 'SEL' type");
1730 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001731 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001732 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001733 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001734 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001735 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001736 msgSendIdent, msgSendType,
1737 FunctionDecl::Extern, false, 0);
1738}
1739
Steve Naroff764c1ae2007-11-15 10:28:18 +00001740// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001741void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001742 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1743 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001744 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001745 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001746 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001747 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1748 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1749 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001750 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001751 assert(!argT.isNull() && "Can't find 'SEL' type");
1752 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001753 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001754 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001755 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001756 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001757 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001758 msgSendIdent, msgSendType,
1759 FunctionDecl::Extern, false, 0);
1760}
1761
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001762// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001763void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001764 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1765 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001766 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001767 assert(!argT.isNull() && "Can't find 'id' type");
1768 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001769 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001770 assert(!argT.isNull() && "Can't find 'SEL' type");
1771 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001772 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001773 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001774 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001775 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001776 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001777 msgSendIdent, msgSendType,
1778 FunctionDecl::Extern, false, 0);
1779}
1780
1781// SynthMsgSendSuperStretFunctionDecl -
1782// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001783void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001784 IdentifierInfo *msgSendIdent =
1785 &Context->Idents.get("objc_msgSendSuper_stret");
1786 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001787 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001788 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001789 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001790 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1791 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1792 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001793 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001794 assert(!argT.isNull() && "Can't find 'SEL' type");
1795 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001796 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001797 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001798 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001799 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001800 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001801 msgSendIdent, msgSendType,
1802 FunctionDecl::Extern, false, 0);
1803}
1804
Steve Naroff31316a12008-05-08 22:02:18 +00001805// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001806void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001807 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1808 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001809 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001810 assert(!argT.isNull() && "Can't find 'id' type");
1811 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001812 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001813 assert(!argT.isNull() && "Can't find 'SEL' type");
1814 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001815 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001816 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001817 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001818 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001819 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001820 msgSendIdent, msgSendType,
1821 FunctionDecl::Extern, false, 0);
1822}
1823
Steve Naroff02a82aa2007-10-30 23:14:51 +00001824// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001825void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001826 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1827 llvm::SmallVector<QualType, 16> ArgTys;
1828 ArgTys.push_back(Context->getPointerType(
1829 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001830 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001831 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001832 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001833 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001834 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001835 getClassIdent, getClassType,
1836 FunctionDecl::Extern, false, 0);
1837}
1838
Steve Naroff3b1caac2007-12-07 03:50:46 +00001839// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001840void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001841 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1842 llvm::SmallVector<QualType, 16> ArgTys;
1843 ArgTys.push_back(Context->getPointerType(
1844 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001845 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001846 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001847 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001848 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001849 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001850 getClassIdent, getClassType,
1851 FunctionDecl::Extern, false, 0);
1852}
1853
Steve Naroff44e81222008-04-14 22:03:09 +00001854Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001855 QualType strType = getConstantStringStructType();
1856
1857 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001858
1859 std::string tmpName = InFileName;
1860 unsigned i;
1861 for (i=0; i < tmpName.length(); i++) {
1862 char c = tmpName.at(i);
1863 // replace any non alphanumeric characters with '_'.
1864 if (!isalpha(c) && (c < '0' || c > '9'))
1865 tmpName[i] = '_';
1866 }
1867 S += tmpName;
1868 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001869 S += utostr(NumObjCStringLiterals++);
1870
Steve Narofffef037c2008-03-27 22:29:16 +00001871 Preamble += "static __NSConstantStringImpl " + S;
1872 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1873 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001874 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001875 std::string prettyBufS;
1876 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001877 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001878 Preamble += prettyBuf.str();
1879 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001880 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001881 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001882
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001883 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001884 &Context->Idents.get(S.c_str()), strType,
1885 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001886 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1887 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1888 Context->getPointerType(DRE->getType()),
1889 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001890 // cast to NSConstantString *
Douglas Gregor035d0882008-10-28 15:36:24 +00001891 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00001892 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001893 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001894 delete Exp;
1895 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001896}
1897
Steve Naroff44e81222008-04-14 22:03:09 +00001898ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001899 // check if we are sending a message to 'super'
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001900 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00001901
Douglas Gregord8606632008-11-04 14:56:14 +00001902 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1903 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00001904 assert(PT);
1905 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1906 return IT->getDecl();
1907 }
1908 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001909}
1910
1911// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001912QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001913 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001914 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001915 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001916 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001917 QualType FieldTypes[2];
1918
1919 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001920 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001921 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001922 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001923 // Create fields
1924 FieldDecl *FieldDecls[2];
1925
1926 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001927 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001928 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001929
Ted Kremenek46a837c2008-09-05 17:16:31 +00001930 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001931 }
1932 return Context->getTagDeclType(SuperStructDecl);
1933}
1934
Steve Naroff44e81222008-04-14 22:03:09 +00001935QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001936 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001937 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001938 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001939 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00001940 QualType FieldTypes[4];
1941
1942 // struct objc_object *receiver;
1943 FieldTypes[0] = Context->getObjCIdType();
1944 // int flags;
1945 FieldTypes[1] = Context->IntTy;
1946 // char *str;
1947 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1948 // long length;
1949 FieldTypes[3] = Context->LongTy;
1950 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001951 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001952
1953 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001954 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001955 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001956
Ted Kremenek46a837c2008-09-05 17:16:31 +00001957 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001958 }
1959 return Context->getTagDeclType(ConstantStringDecl);
1960}
1961
Steve Naroff44e81222008-04-14 22:03:09 +00001962Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001963 if (!SelGetUidFunctionDecl)
1964 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001965 if (!MsgSendFunctionDecl)
1966 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001967 if (!MsgSendSuperFunctionDecl)
1968 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001969 if (!MsgSendStretFunctionDecl)
1970 SynthMsgSendStretFunctionDecl();
1971 if (!MsgSendSuperStretFunctionDecl)
1972 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001973 if (!MsgSendFpretFunctionDecl)
1974 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001975 if (!GetClassFunctionDecl)
1976 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001977 if (!GetMetaClassFunctionDecl)
1978 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001979
Steve Naroff764c1ae2007-11-15 10:28:18 +00001980 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001981 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1982 // May need to use objc_msgSend_stret() as well.
1983 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001984 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001985 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00001986 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001987 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00001988 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001989 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001990 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001991
Steve Naroff71226032007-10-24 22:48:43 +00001992 // Synthesize a call to objc_msgSend().
1993 llvm::SmallVector<Expr*, 8> MsgExprs;
1994 IdentifierInfo *clsName = Exp->getClassName();
1995
1996 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1997 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00001998 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
1999 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002000 if (!strcmp(clsName->getName(), "super")) {
2001 MsgSendFlavor = MsgSendSuperFunctionDecl;
2002 if (MsgSendStretFlavor)
2003 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2004 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2005
Ted Kremenek42730c52008-01-07 19:49:32 +00002006 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002007 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002008
2009 llvm::SmallVector<Expr*, 4> InitExprs;
2010
2011 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002012 InitExprs.push_back(new DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002013 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002014 Context->getObjCIdType(),
2015 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002016 llvm::SmallVector<Expr*, 8> ClsExprs;
2017 QualType argType = Context->getPointerType(Context->CharTy);
2018 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2019 SuperDecl->getIdentifier()->getLength(),
2020 false, argType, SourceLocation(),
2021 SourceLocation()));
2022 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2023 &ClsExprs[0],
2024 ClsExprs.size());
2025 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002026 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002027 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002028 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002029 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002030 // struct objc_super
2031 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002032 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002033
Steve Naroffdee066b2008-03-11 18:14:26 +00002034 if (LangOpts.Microsoft) {
2035 SynthSuperContructorFunctionDecl();
2036 // Simulate a contructor call...
2037 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2038 superType, SourceLocation());
2039 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2040 superType, SourceLocation());
2041 } else {
2042 // (struct objc_super) { <exprs from above> }
2043 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2044 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002045 SourceLocation(), false);
2046 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2047 false);
Steve Naroffdee066b2008-03-11 18:14:26 +00002048 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002049 // struct objc_super *
2050 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2051 Context->getPointerType(SuperRep->getType()),
2052 SourceLocation());
2053 MsgExprs.push_back(Unop);
2054 } else {
2055 llvm::SmallVector<Expr*, 8> ClsExprs;
2056 QualType argType = Context->getPointerType(Context->CharTy);
2057 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2058 clsName->getLength(),
2059 false, argType, SourceLocation(),
2060 SourceLocation()));
2061 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2062 &ClsExprs[0],
2063 ClsExprs.size());
2064 MsgExprs.push_back(Cls);
2065 }
Steve Naroff885e2122007-11-14 23:54:14 +00002066 } else { // instance message.
2067 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002068
Ted Kremenek42730c52008-01-07 19:49:32 +00002069 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002070 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002071 if (MsgSendStretFlavor)
2072 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002073 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2074
2075 llvm::SmallVector<Expr*, 4> InitExprs;
2076
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002077 InitExprs.push_back(
Douglas Gregor035d0882008-10-28 15:36:24 +00002078 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002079 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002080 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002081 SourceLocation()),
2082 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002083 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002084
2085 llvm::SmallVector<Expr*, 8> ClsExprs;
2086 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002087 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2088 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002089 false, argType, SourceLocation(),
2090 SourceLocation()));
2091 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002092 &ClsExprs[0],
2093 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002094 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002095 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002096 // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002097 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002098 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002099 // struct objc_super
2100 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002101 Expr *SuperRep;
2102
2103 if (LangOpts.Microsoft) {
2104 SynthSuperContructorFunctionDecl();
2105 // Simulate a contructor call...
2106 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2107 superType, SourceLocation());
2108 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2109 superType, SourceLocation());
2110 } else {
2111 // (struct objc_super) { <exprs from above> }
2112 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2113 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002114 SourceLocation(), false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002115 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2116 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002117 // struct objc_super *
2118 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2119 Context->getPointerType(SuperRep->getType()),
2120 SourceLocation());
2121 MsgExprs.push_back(Unop);
2122 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002123 // Remove all type-casts because it may contain objc-style types; e.g.
2124 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002125 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002126 recExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002127 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002128 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002129 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002130 MsgExprs.push_back(recExpr);
2131 }
Steve Naroff885e2122007-11-14 23:54:14 +00002132 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002133 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002134 llvm::SmallVector<Expr*, 8> SelExprs;
2135 QualType argType = Context->getPointerType(Context->CharTy);
2136 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2137 Exp->getSelector().getName().size(),
2138 false, argType, SourceLocation(),
2139 SourceLocation()));
2140 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2141 &SelExprs[0], SelExprs.size());
2142 MsgExprs.push_back(SelExp);
2143
2144 // Now push any user supplied arguments.
2145 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002146 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002147 // Make all implicit casts explicit...ICE comes in handy:-)
2148 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2149 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002150 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002151 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002152 : ICE->getType();
Steve Naroff7f1412d2008-11-03 23:29:32 +00002153 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002154 }
2155 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002156 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002157 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002158 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002159 userExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002160 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002161 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002162 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002163 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002164 }
Steve Naroff885e2122007-11-14 23:54:14 +00002165 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002166 // We've transferred the ownership to MsgExprs. Null out the argument in
2167 // the original expression, since we will delete it below.
2168 Exp->setArg(i, 0);
2169 }
Steve Naroff0744c472007-11-04 22:37:50 +00002170 // Generate the funky cast.
2171 CastExpr *cast;
2172 llvm::SmallVector<QualType, 8> ArgTypes;
2173 QualType returnType;
2174
2175 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002176 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2177 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2178 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002179 ArgTypes.push_back(Context->getObjCIdType());
2180 ArgTypes.push_back(Context->getObjCSelType());
2181 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002182 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002183 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002184 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2185 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002186 : mDecl->getParamDecl(i)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002187 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2188 if (isBlockPointerType(t)) {
2189 const BlockPointerType *BPT = t->getAsBlockPointerType();
2190 t = Context->getPointerType(BPT->getPointeeType());
2191 }
Steve Naroff4242b972007-11-05 14:36:37 +00002192 ArgTypes.push_back(t);
2193 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002194 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2195 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002196 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002197 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002198 }
2199 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002200 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002201
2202 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002203 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2204 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002205
2206 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2207 // If we don't do this cast, we get the following bizarre warning/note:
2208 // xx.m:13: warning: function called through a non-compatible type
2209 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor035d0882008-10-28 15:36:24 +00002210 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002211 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002212 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002213
Steve Naroff0744c472007-11-04 22:37:50 +00002214 // Now do the "normal" pointer to function cast.
2215 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002216 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002217 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002218 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002219 castType = Context->getPointerType(castType);
Steve Naroff7f1412d2008-11-03 23:29:32 +00002220 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002221
2222 // Don't forget the parens to enforce the proper binding.
2223 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2224
2225 const FunctionType *FT = msgSendType->getAsFunctionType();
2226 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2227 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002228 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002229 if (MsgSendStretFlavor) {
2230 // We have the method which returns a struct/union. Must also generate
2231 // call to objc_msgSend_stret and hang both varieties on a conditional
2232 // expression which dictate which one to envoke depending on size of
2233 // method's return type.
2234
2235 // Create a reference to the objc_msgSend_stret() declaration.
2236 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2237 SourceLocation());
2238 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor035d0882008-10-28 15:36:24 +00002239 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002240 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002241 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002242 // Now do the "normal" pointer to function cast.
2243 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002244 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002245 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002246 castType = Context->getPointerType(castType);
Steve Naroff7f1412d2008-11-03 23:29:32 +00002247 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002248
2249 // Don't forget the parens to enforce the proper binding.
2250 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2251
2252 FT = msgSendType->getAsFunctionType();
2253 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2254 FT->getResultType(), SourceLocation());
2255
2256 // Build sizeof(returnType)
2257 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2258 returnType, Context->getSizeType(),
2259 SourceLocation(), SourceLocation());
2260 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2261 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2262 // For X86 it is more complicated and some kind of target specific routine
2263 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002264 unsigned IntSize =
2265 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002266 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2267 Context->IntTy,
2268 SourceLocation());
2269 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2270 BinaryOperator::LE,
2271 Context->IntTy,
2272 SourceLocation());
2273 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2274 ConditionalOperator *CondExpr =
2275 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002276 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002277 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002278 return ReplacingStmt;
2279}
2280
Steve Naroff44e81222008-04-14 22:03:09 +00002281Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002282 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002283
Steve Naroff71226032007-10-24 22:48:43 +00002284 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002285 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002286
Chris Lattner0021f452007-10-24 16:57:36 +00002287 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002288 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002289}
2290
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002291/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2292/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002293Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002294 if (!GetProtocolFunctionDecl)
2295 SynthGetProtocolFunctionDecl();
2296 // Create a call to objc_getProtocol("ProtocolName").
2297 llvm::SmallVector<Expr*, 8> ProtoExprs;
2298 QualType argType = Context->getPointerType(Context->CharTy);
2299 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2300 strlen(Exp->getProtocol()->getName()),
2301 false, argType, SourceLocation(),
2302 SourceLocation()));
2303 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2304 &ProtoExprs[0],
2305 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002306 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002307 delete Exp;
2308 return ProtoExp;
2309
2310}
2311
Steve Naroffef82b742008-05-31 14:15:04 +00002312bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2313 const char *endBuf) {
2314 while (startBuf < endBuf) {
2315 if (*startBuf == '#') {
2316 // Skip whitespace.
2317 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2318 ;
2319 if (!strncmp(startBuf, "if", strlen("if")) ||
2320 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2321 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2322 !strncmp(startBuf, "define", strlen("define")) ||
2323 !strncmp(startBuf, "undef", strlen("undef")) ||
2324 !strncmp(startBuf, "else", strlen("else")) ||
2325 !strncmp(startBuf, "elif", strlen("elif")) ||
2326 !strncmp(startBuf, "endif", strlen("endif")) ||
2327 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2328 !strncmp(startBuf, "include", strlen("include")) ||
2329 !strncmp(startBuf, "import", strlen("import")) ||
2330 !strncmp(startBuf, "include_next", strlen("include_next")))
2331 return true;
2332 }
2333 startBuf++;
2334 }
2335 return false;
2336}
2337
Ted Kremenek42730c52008-01-07 19:49:32 +00002338/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002339/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002340void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002341 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002342 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2343 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002344 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002345 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002346 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002347 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002348 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002349 SourceLocation LocStart = CDecl->getLocStart();
2350 SourceLocation LocEnd = CDecl->getLocEnd();
2351
2352 const char *startBuf = SM->getCharacterData(LocStart);
2353 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002354
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002355 // If no ivars and no root or if its root, directly or indirectly,
2356 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002357 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2358 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002359 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002360 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002361 return;
2362 }
2363
2364 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002365 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002366 Result += "\nstruct ";
2367 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002368 if (LangOpts.Microsoft)
2369 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002370
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002371 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002372 const char *cursor = strchr(startBuf, '{');
2373 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002374 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002375 // If the buffer contains preprocessor directives, we do more fine-grained
2376 // rewrites. This is intended to fix code that looks like (which occurs in
2377 // NSURL.h, for example):
2378 //
2379 // #ifdef XYZ
2380 // @interface Foo : NSObject
2381 // #else
2382 // @interface FooBar : NSObject
2383 // #endif
2384 // {
2385 // int i;
2386 // }
2387 // @end
2388 //
2389 // This clause is segregated to avoid breaking the common case.
2390 if (BufferContainsPPDirectives(startBuf, cursor)) {
2391 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2392 CDecl->getClassLoc();
2393 const char *endHeader = SM->getCharacterData(L);
2394 endHeader += Lexer::MeasureTokenLength(L, *SM);
2395
Chris Lattner8bcb5252008-07-21 18:19:38 +00002396 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002397 // advance to the end of the referenced protocols.
2398 while (endHeader < cursor && *endHeader != '>') endHeader++;
2399 endHeader++;
2400 }
2401 // rewrite the original header
2402 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2403 } else {
2404 // rewrite the original header *without* disturbing the '{'
2405 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2406 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002407 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002408 Result = "\n struct ";
2409 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002410 Result += "_IMPL ";
2411 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002412 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002413
2414 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002415 SourceLocation OnePastCurly =
2416 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2417 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002418 }
2419 cursor++; // past '{'
2420
2421 // Now comment out any visibility specifiers.
2422 while (cursor < endBuf) {
2423 if (*cursor == '@') {
2424 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002425 // Skip whitespace.
2426 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2427 /*scan*/;
2428
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002429 // FIXME: presence of @public, etc. inside comment results in
2430 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002431 if (!strncmp(cursor, "public", strlen("public")) ||
2432 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002433 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002434 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002435 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002436 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002437 // FIXME: If there are cases where '<' is used in ivar declaration part
2438 // of user code, then scan the ivar list and use needToScanForQualifiers
2439 // for type checking.
2440 else if (*cursor == '<') {
2441 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002442 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002443 cursor = strchr(cursor, '>');
2444 cursor++;
2445 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002446 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002447 } else if (*cursor == '^') { // rewrite block specifier.
2448 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2449 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002450 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002451 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002452 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002453 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002454 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002455 } else { // we don't have any instance variables - insert super struct.
2456 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2457 Result += " {\n struct ";
2458 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002459 Result += "_IMPL ";
2460 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002461 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002462 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002463 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002464 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002465 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002466 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002467}
2468
Ted Kremenek42730c52008-01-07 19:49:32 +00002469// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002470/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002471void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002472 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002473 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002474 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002475 const char *ClassName,
2476 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002477 if (MethodBegin == MethodEnd) return;
2478
Fariborz Jahanian04455192007-10-22 21:41:37 +00002479 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002480 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002481 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002482 SEL _cmd;
2483 char *method_types;
2484 void *_imp;
2485 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002486 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002487 Result += "\nstruct _objc_method {\n";
2488 Result += "\tSEL _cmd;\n";
2489 Result += "\tchar *method_types;\n";
2490 Result += "\tvoid *_imp;\n";
2491 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002492
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002493 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002494 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002495
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002496 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002497
2498 /* struct {
2499 struct _objc_method_list *next_method;
2500 int method_count;
2501 struct _objc_method method_list[];
2502 }
2503 */
2504 Result += "\nstatic struct {\n";
2505 Result += "\tstruct _objc_method_list *next_method;\n";
2506 Result += "\tint method_count;\n";
2507 Result += "\tstruct _objc_method method_list[";
2508 Result += utostr(MethodEnd-MethodBegin);
2509 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002510 Result += prefix;
2511 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2512 Result += "_METHODS_";
2513 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002514 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002515 Result += IsInstanceMethod ? "inst" : "cls";
2516 Result += "_meth\")))= ";
2517 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002518
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002519 Result += "\t,{{(SEL)\"";
2520 Result += (*MethodBegin)->getSelector().getName().c_str();
2521 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002522 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002523 Result += "\", \"";
2524 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002525 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002526 Result += MethodInternalNames[*MethodBegin];
2527 Result += "}\n";
2528 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2529 Result += "\t ,{(SEL)\"";
2530 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002531 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002532 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002533 Result += "\", \"";
2534 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002535 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002536 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002537 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002538 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002539 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002540}
2541
Ted Kremenek42730c52008-01-07 19:49:32 +00002542/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002543void RewriteObjC::
2544RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2545 const char *prefix,
2546 const char *ClassName,
2547 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002548 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002549 if (Protocols.empty()) return;
2550
2551 for (unsigned i = 0; i != Protocols.size(); i++) {
2552 ObjCProtocolDecl *PDecl = Protocols[i];
2553 // Output struct protocol_methods holder of method selector and type.
2554 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2555 /* struct protocol_methods {
2556 SEL _cmd;
2557 char *method_types;
2558 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002559 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002560 Result += "\nstruct protocol_methods {\n";
2561 Result += "\tSEL _cmd;\n";
2562 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002563 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002564
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002565 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002566 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002567 // Do not synthesize the protocol more than once.
2568 if (ObjCSynthesizedProtocols.count(PDecl))
2569 continue;
2570
2571 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2572 unsigned NumMethods = PDecl->getNumInstanceMethods();
2573 /* struct _objc_protocol_method_list {
2574 int protocol_method_count;
2575 struct protocol_methods protocols[];
2576 }
2577 */
2578 Result += "\nstatic struct {\n";
2579 Result += "\tint protocol_method_count;\n";
2580 Result += "\tstruct protocol_methods protocols[";
2581 Result += utostr(NumMethods);
2582 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2583 Result += PDecl->getName();
2584 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2585 "{\n\t" + utostr(NumMethods) + "\n";
2586
2587 // Output instance methods declared in this protocol.
2588 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2589 E = PDecl->instmeth_end(); I != E; ++I) {
2590 if (I == PDecl->instmeth_begin())
2591 Result += "\t ,{{(SEL)\"";
2592 else
2593 Result += "\t ,{(SEL)\"";
2594 Result += (*I)->getSelector().getName().c_str();
2595 std::string MethodTypeString;
2596 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2597 Result += "\", \"";
2598 Result += MethodTypeString;
2599 Result += "\"}\n";
2600 }
2601 Result += "\t }\n};\n";
2602 }
2603
2604 // Output class methods declared in this protocol.
2605 int NumMethods = PDecl->getNumClassMethods();
2606 if (NumMethods > 0) {
2607 /* struct _objc_protocol_method_list {
2608 int protocol_method_count;
2609 struct protocol_methods protocols[];
2610 }
2611 */
2612 Result += "\nstatic struct {\n";
2613 Result += "\tint protocol_method_count;\n";
2614 Result += "\tstruct protocol_methods protocols[";
2615 Result += utostr(NumMethods);
2616 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2617 Result += PDecl->getName();
2618 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2619 "{\n\t";
2620 Result += utostr(NumMethods);
2621 Result += "\n";
2622
2623 // Output instance methods declared in this protocol.
2624 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2625 E = PDecl->classmeth_end(); I != E; ++I) {
2626 if (I == PDecl->classmeth_begin())
2627 Result += "\t ,{{(SEL)\"";
2628 else
2629 Result += "\t ,{(SEL)\"";
2630 Result += (*I)->getSelector().getName().c_str();
2631 std::string MethodTypeString;
2632 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2633 Result += "\", \"";
2634 Result += MethodTypeString;
2635 Result += "\"}\n";
2636 }
2637 Result += "\t }\n};\n";
2638 }
2639
2640 // Output:
2641 /* struct _objc_protocol {
2642 // Objective-C 1.0 extensions
2643 struct _objc_protocol_extension *isa;
2644 char *protocol_name;
2645 struct _objc_protocol **protocol_list;
2646 struct _objc_protocol_method_list *instance_methods;
2647 struct _objc_protocol_method_list *class_methods;
2648 };
Steve Naroff27429432008-03-12 01:06:30 +00002649 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002650 static bool objc_protocol = false;
2651 if (!objc_protocol) {
2652 Result += "\nstruct _objc_protocol {\n";
2653 Result += "\tstruct _objc_protocol_extension *isa;\n";
2654 Result += "\tchar *protocol_name;\n";
2655 Result += "\tstruct _objc_protocol **protocol_list;\n";
2656 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2657 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2658 Result += "};\n";
2659
2660 objc_protocol = true;
2661 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002662
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002663 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2664 Result += PDecl->getName();
2665 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2666 "{\n\t0, \"";
2667 Result += PDecl->getName();
2668 Result += "\", 0, ";
2669 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2670 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2671 Result += PDecl->getName();
2672 Result += ", ";
2673 }
2674 else
2675 Result += "0, ";
2676 if (PDecl->getNumClassMethods() > 0) {
2677 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2678 Result += PDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002679 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002680 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002681 else
2682 Result += "0\n";
2683 Result += "};\n";
2684
2685 // Mark this protocol as having been generated.
2686 if (!ObjCSynthesizedProtocols.insert(PDecl))
2687 assert(false && "protocol already synthesized");
2688 }
2689 // Output the top lovel protocol meta-data for the class.
2690 /* struct _objc_protocol_list {
2691 struct _objc_protocol_list *next;
2692 int protocol_count;
2693 struct _objc_protocol *class_protocols[];
2694 }
2695 */
2696 Result += "\nstatic struct {\n";
2697 Result += "\tstruct _objc_protocol_list *next;\n";
2698 Result += "\tint protocol_count;\n";
2699 Result += "\tstruct _objc_protocol *class_protocols[";
2700 Result += utostr(Protocols.size());
2701 Result += "];\n} _OBJC_";
2702 Result += prefix;
2703 Result += "_PROTOCOLS_";
2704 Result += ClassName;
2705 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2706 "{\n\t0, ";
2707 Result += utostr(Protocols.size());
2708 Result += "\n";
2709
2710 Result += "\t,{&_OBJC_PROTOCOL_";
2711 Result += Protocols[0]->getName();
2712 Result += " \n";
2713
2714 for (unsigned i = 1; i != Protocols.size(); i++) {
2715 Result += "\t ,&_OBJC_PROTOCOL_";
2716 Result += Protocols[i]->getName();
2717 Result += "\n";
2718 }
2719 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002720}
2721
Ted Kremenek42730c52008-01-07 19:49:32 +00002722/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002723/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002724void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002725 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002726 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002727 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002728 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002729 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2730 CDecl = CDecl->getNextClassCategory())
2731 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2732 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002733
Chris Lattnera661a4d2007-12-23 01:40:15 +00002734 std::string FullCategoryName = ClassDecl->getName();
2735 FullCategoryName += '_';
2736 FullCategoryName += IDecl->getName();
2737
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002738 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002739 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002740 true, "CATEGORY_", FullCategoryName.c_str(),
2741 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002742
2743 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002744 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002745 false, "CATEGORY_", FullCategoryName.c_str(),
2746 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002747
2748 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002749 // Null CDecl is case of a category implementation with no category interface
2750 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002751 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002752 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002753
2754 /* struct _objc_category {
2755 char *category_name;
2756 char *class_name;
2757 struct _objc_method_list *instance_methods;
2758 struct _objc_method_list *class_methods;
2759 struct _objc_protocol_list *protocols;
2760 // Objective-C 1.0 extensions
2761 uint32_t size; // sizeof (struct _objc_category)
2762 struct _objc_property_list *instance_properties; // category's own
2763 // @property decl.
2764 };
2765 */
2766
2767 static bool objc_category = false;
2768 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002769 Result += "\nstruct _objc_category {\n";
2770 Result += "\tchar *category_name;\n";
2771 Result += "\tchar *class_name;\n";
2772 Result += "\tstruct _objc_method_list *instance_methods;\n";
2773 Result += "\tstruct _objc_method_list *class_methods;\n";
2774 Result += "\tstruct _objc_protocol_list *protocols;\n";
2775 Result += "\tunsigned int size;\n";
2776 Result += "\tstruct _objc_property_list *instance_properties;\n";
2777 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002778 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002779 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002780 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2781 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002782 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002783 Result += IDecl->getName();
2784 Result += "\"\n\t, \"";
2785 Result += ClassDecl->getName();
2786 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002787
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002788 if (IDecl->getNumInstanceMethods() > 0) {
2789 Result += "\t, (struct _objc_method_list *)"
2790 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2791 Result += FullCategoryName;
2792 Result += "\n";
2793 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002794 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002795 Result += "\t, 0\n";
2796 if (IDecl->getNumClassMethods() > 0) {
2797 Result += "\t, (struct _objc_method_list *)"
2798 "&_OBJC_CATEGORY_CLASS_METHODS_";
2799 Result += FullCategoryName;
2800 Result += "\n";
2801 }
2802 else
2803 Result += "\t, 0\n";
2804
Chris Lattner0be08822008-07-21 21:32:27 +00002805 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002806 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2807 Result += FullCategoryName;
2808 Result += "\n";
2809 }
2810 else
2811 Result += "\t, 0\n";
2812 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002813}
2814
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002815/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2816/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002817void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002818 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002819 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002820 if (ivar->isBitField()) {
2821 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2822 // place all bitfields at offset 0.
2823 Result += "0";
2824 } else {
2825 Result += "__OFFSETOFIVAR__(struct ";
2826 Result += IDecl->getName();
2827 if (LangOpts.Microsoft)
2828 Result += "_IMPL";
2829 Result += ", ";
2830 Result += ivar->getName();
2831 Result += ")";
2832 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002833}
2834
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002835//===----------------------------------------------------------------------===//
2836// Meta Data Emission
2837//===----------------------------------------------------------------------===//
2838
Steve Naroff44e81222008-04-14 22:03:09 +00002839void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002840 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002841 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002842
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002843 // Explictly declared @interface's are already synthesized.
2844 if (CDecl->ImplicitInterfaceDecl()) {
2845 // FIXME: Implementation of a class with no @interface (legacy) doese not
2846 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002847 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002848 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002849
Chris Lattnerc7b06752007-12-12 07:56:42 +00002850 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002851 unsigned NumIvars = !IDecl->ivar_empty()
2852 ? IDecl->ivar_size()
2853 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002854 if (NumIvars > 0) {
2855 static bool objc_ivar = false;
2856 if (!objc_ivar) {
2857 /* struct _objc_ivar {
2858 char *ivar_name;
2859 char *ivar_type;
2860 int ivar_offset;
2861 };
2862 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002863 Result += "\nstruct _objc_ivar {\n";
2864 Result += "\tchar *ivar_name;\n";
2865 Result += "\tchar *ivar_type;\n";
2866 Result += "\tint ivar_offset;\n";
2867 Result += "};\n";
2868
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002869 objc_ivar = true;
2870 }
2871
Steve Naroffc723eec2008-03-11 00:12:29 +00002872 /* struct {
2873 int ivar_count;
2874 struct _objc_ivar ivar_list[nIvars];
2875 };
2876 */
2877 Result += "\nstatic struct {\n";
2878 Result += "\tint ivar_count;\n";
2879 Result += "\tstruct _objc_ivar ivar_list[";
2880 Result += utostr(NumIvars);
2881 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002882 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002883 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002884 "{\n\t";
2885 Result += utostr(NumIvars);
2886 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002887
Ted Kremenek42730c52008-01-07 19:49:32 +00002888 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002889 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002890 IVI = IDecl->ivar_begin();
2891 IVE = IDecl->ivar_end();
2892 } else {
2893 IVI = CDecl->ivar_begin();
2894 IVE = CDecl->ivar_end();
2895 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002896 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002897 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002898 Result += "\", \"";
2899 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002900 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002901 Result += StrEncoding;
2902 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002903 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002904 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002905 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002906 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002907 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002908 Result += "\", \"";
2909 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002910 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002911 Result += StrEncoding;
2912 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002913 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002914 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002915 }
2916
2917 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002918 }
2919
2920 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002921 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002922 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002923
2924 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002925 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002926 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002927
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002928 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00002929 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002930 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002931
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002932
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002933 // Declaration of class/meta-class metadata
2934 /* struct _objc_class {
2935 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002936 const char *super_class_name;
2937 char *name;
2938 long version;
2939 long info;
2940 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002941 struct _objc_ivar_list *ivars;
2942 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002943 struct objc_cache *cache;
2944 struct objc_protocol_list *protocols;
2945 const char *ivar_layout;
2946 struct _objc_class_ext *ext;
2947 };
2948 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002949 static bool objc_class = false;
2950 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002951 Result += "\nstruct _objc_class {\n";
2952 Result += "\tstruct _objc_class *isa;\n";
2953 Result += "\tconst char *super_class_name;\n";
2954 Result += "\tchar *name;\n";
2955 Result += "\tlong version;\n";
2956 Result += "\tlong info;\n";
2957 Result += "\tlong instance_size;\n";
2958 Result += "\tstruct _objc_ivar_list *ivars;\n";
2959 Result += "\tstruct _objc_method_list *methods;\n";
2960 Result += "\tstruct objc_cache *cache;\n";
2961 Result += "\tstruct _objc_protocol_list *protocols;\n";
2962 Result += "\tconst char *ivar_layout;\n";
2963 Result += "\tstruct _objc_class_ext *ext;\n";
2964 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002965 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002966 }
2967
2968 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002969 ObjCInterfaceDecl *RootClass = 0;
2970 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002971 while (SuperClass) {
2972 RootClass = SuperClass;
2973 SuperClass = SuperClass->getSuperClass();
2974 }
2975 SuperClass = CDecl->getSuperClass();
2976
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002977 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2978 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002979 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002980 "{\n\t(struct _objc_class *)\"";
2981 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2982 Result += "\"";
2983
2984 if (SuperClass) {
2985 Result += ", \"";
2986 Result += SuperClass->getName();
2987 Result += "\", \"";
2988 Result += CDecl->getName();
2989 Result += "\"";
2990 }
2991 else {
2992 Result += ", 0, \"";
2993 Result += CDecl->getName();
2994 Result += "\"";
2995 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002996 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002997 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002998 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002999 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003000 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00003001 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003002 Result += "\n";
3003 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003004 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003005 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003006 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003007 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003008 Result += CDecl->getName();
3009 Result += ",0,0\n";
3010 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003011 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003012 Result += "\t,0,0,0,0\n";
3013 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003014
3015 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003016 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3017 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003018 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003019 "{\n\t&_OBJC_METACLASS_";
3020 Result += CDecl->getName();
3021 if (SuperClass) {
3022 Result += ", \"";
3023 Result += SuperClass->getName();
3024 Result += "\", \"";
3025 Result += CDecl->getName();
3026 Result += "\"";
3027 }
3028 else {
3029 Result += ", 0, \"";
3030 Result += CDecl->getName();
3031 Result += "\"";
3032 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003033 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003034 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003035 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003036 Result += ",0";
3037 else {
3038 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003039 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003040 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003041 if (LangOpts.Microsoft)
3042 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003043 Result += ")";
3044 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003045 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003046 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003047 Result += CDecl->getName();
3048 Result += "\n\t";
3049 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003050 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003051 Result += ",0";
3052 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003053 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003054 Result += CDecl->getName();
3055 Result += ", 0\n\t";
3056 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003057 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003058 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003059 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003060 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003061 Result += CDecl->getName();
3062 Result += ", 0,0\n";
3063 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003064 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003065 Result += ",0,0,0\n";
3066 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003067}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003068
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003069/// RewriteImplementations - This routine rewrites all method implementations
3070/// and emits meta-data.
3071
Steve Naroff44e81222008-04-14 22:03:09 +00003072void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003073 int ClsDefCount = ClassImplementation.size();
3074 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003075
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003076 if (ClsDefCount == 0 && CatDefCount == 0)
3077 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003078 // Rewrite implemented methods
3079 for (int i = 0; i < ClsDefCount; i++)
3080 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003081
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003082 for (int i = 0; i < CatDefCount; i++)
3083 RewriteImplementationDecl(CategoryImplementation[i]);
3084
Steve Naroff5bf10222008-05-07 21:23:49 +00003085 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003086 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003087 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003088 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003089 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003090
3091 // For each implemented category, write out all its meta data.
3092 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003093 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003094
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003095 // Write objc_symtab metadata
3096 /*
3097 struct _objc_symtab
3098 {
3099 long sel_ref_cnt;
3100 SEL *refs;
3101 short cls_def_cnt;
3102 short cat_def_cnt;
3103 void *defs[cls_def_cnt + cat_def_cnt];
3104 };
3105 */
3106
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003107 Result += "\nstruct _objc_symtab {\n";
3108 Result += "\tlong sel_ref_cnt;\n";
3109 Result += "\tSEL *refs;\n";
3110 Result += "\tshort cls_def_cnt;\n";
3111 Result += "\tshort cat_def_cnt;\n";
3112 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3113 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003114
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003115 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003116 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003117 Result += "\t0, 0, " + utostr(ClsDefCount)
3118 + ", " + utostr(CatDefCount) + "\n";
3119 for (int i = 0; i < ClsDefCount; i++) {
3120 Result += "\t,&_OBJC_CLASS_";
3121 Result += ClassImplementation[i]->getName();
3122 Result += "\n";
3123 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003124
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003125 for (int i = 0; i < CatDefCount; i++) {
3126 Result += "\t,&_OBJC_CATEGORY_";
3127 Result += CategoryImplementation[i]->getClassInterface()->getName();
3128 Result += "_";
3129 Result += CategoryImplementation[i]->getName();
3130 Result += "\n";
3131 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003132
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003133 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003134
3135 // Write objc_module metadata
3136
3137 /*
3138 struct _objc_module {
3139 long version;
3140 long size;
3141 const char *name;
3142 struct _objc_symtab *symtab;
3143 }
3144 */
3145
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003146 Result += "\nstruct _objc_module {\n";
3147 Result += "\tlong version;\n";
3148 Result += "\tlong size;\n";
3149 Result += "\tconst char *name;\n";
3150 Result += "\tstruct _objc_symtab *symtab;\n";
3151 Result += "};\n\n";
3152 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003153 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003154 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3155 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003156 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003157
3158 if (LangOpts.Microsoft) {
3159 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003160 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003161 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3162 Result += "&_OBJC_MODULES;\n";
3163 Result += "#pragma data_seg(pop)\n\n";
3164 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003165}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003166
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003167std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3168 const char *funcName,
3169 std::string Tag) {
3170 const FunctionType *AFT = CE->getFunctionType();
3171 QualType RT = AFT->getResultType();
3172 std::string StructRef = "struct " + Tag;
3173 std::string S = "static " + RT.getAsString() + " __" +
3174 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003175
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003176 BlockDecl *BD = CE->getBlockDecl();
3177
3178 if (isa<FunctionTypeNoProto>(AFT)) {
3179 S += "()";
3180 } else if (BD->param_empty()) {
3181 S += "(" + StructRef + " *__cself)";
3182 } else {
3183 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3184 assert(FT && "SynthesizeBlockFunc: No function proto");
3185 S += '(';
3186 // first add the implicit argument.
3187 S += StructRef + " *__cself, ";
3188 std::string ParamStr;
3189 for (BlockDecl::param_iterator AI = BD->param_begin(),
3190 E = BD->param_end(); AI != E; ++AI) {
3191 if (AI != BD->param_begin()) S += ", ";
3192 ParamStr = (*AI)->getName();
3193 (*AI)->getType().getAsStringInternal(ParamStr);
3194 S += ParamStr;
3195 }
3196 if (FT->isVariadic()) {
3197 if (!BD->param_empty()) S += ", ";
3198 S += "...";
3199 }
3200 S += ')';
3201 }
3202 S += " {\n";
3203
3204 // Create local declarations to avoid rewriting all closure decl ref exprs.
3205 // First, emit a declaration for all "by ref" decls.
3206 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3207 E = BlockByRefDecls.end(); I != E; ++I) {
3208 S += " ";
3209 std::string Name = (*I)->getName();
3210 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3211 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3212 }
3213 // Next, emit a declaration for all "by copy" declarations.
3214 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3215 E = BlockByCopyDecls.end(); I != E; ++I) {
3216 S += " ";
3217 std::string Name = (*I)->getName();
3218 // Handle nested closure invocation. For example:
3219 //
3220 // void (^myImportedClosure)(void);
3221 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3222 //
3223 // void (^anotherClosure)(void);
3224 // anotherClosure = ^(void) {
3225 // myImportedClosure(); // import and invoke the closure
3226 // };
3227 //
3228 if (isBlockPointerType((*I)->getType()))
3229 S += "struct __block_impl *";
3230 else
3231 (*I)->getType().getAsStringInternal(Name);
3232 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3233 }
3234 std::string RewrittenStr = RewrittenBlockExprs[CE];
3235 const char *cstr = RewrittenStr.c_str();
3236 while (*cstr++ != '{') ;
3237 S += cstr;
3238 S += "\n";
3239 return S;
3240}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003241
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003242std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3243 const char *funcName,
3244 std::string Tag) {
3245 std::string StructRef = "struct " + Tag;
3246 std::string S = "static void __";
3247
3248 S += funcName;
3249 S += "_block_copy_" + utostr(i);
3250 S += "(" + StructRef;
3251 S += "*dst, " + StructRef;
3252 S += "*src) {";
3253 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3254 E = ImportedBlockDecls.end(); I != E; ++I) {
3255 S += "_Block_copy_assign(&dst->";
3256 S += (*I)->getName();
3257 S += ", src->";
3258 S += (*I)->getName();
3259 S += ");}";
3260 }
3261 S += "\nstatic void __";
3262 S += funcName;
3263 S += "_block_dispose_" + utostr(i);
3264 S += "(" + StructRef;
3265 S += "*src) {";
3266 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3267 E = ImportedBlockDecls.end(); I != E; ++I) {
3268 S += "_Block_destroy(src->";
3269 S += (*I)->getName();
3270 S += ");";
3271 }
3272 S += "}\n";
3273 return S;
3274}
3275
3276std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3277 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003278 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003279 std::string Constructor = " " + Tag;
3280
3281 S += " {\n struct __block_impl impl;\n";
3282
3283 if (hasCopyDisposeHelpers)
3284 S += " void *copy;\n void *dispose;\n";
3285
3286 Constructor += "(void *fp";
3287
3288 if (hasCopyDisposeHelpers)
3289 Constructor += ", void *copyHelp, void *disposeHelp";
3290
3291 if (BlockDeclRefs.size()) {
3292 // Output all "by copy" declarations.
3293 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3294 E = BlockByCopyDecls.end(); I != E; ++I) {
3295 S += " ";
3296 std::string FieldName = (*I)->getName();
3297 std::string ArgName = "_" + FieldName;
3298 // Handle nested closure invocation. For example:
3299 //
3300 // void (^myImportedBlock)(void);
3301 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3302 //
3303 // void (^anotherBlock)(void);
3304 // anotherBlock = ^(void) {
3305 // myImportedBlock(); // import and invoke the closure
3306 // };
3307 //
3308 if (isBlockPointerType((*I)->getType())) {
3309 S += "struct __block_impl *";
3310 Constructor += ", void *" + ArgName;
3311 } else {
3312 (*I)->getType().getAsStringInternal(FieldName);
3313 (*I)->getType().getAsStringInternal(ArgName);
3314 Constructor += ", " + ArgName;
3315 }
3316 S += FieldName + ";\n";
3317 }
3318 // Output all "by ref" declarations.
3319 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3320 E = BlockByRefDecls.end(); I != E; ++I) {
3321 S += " ";
3322 std::string FieldName = (*I)->getName();
3323 std::string ArgName = "_" + FieldName;
3324 // Handle nested closure invocation. For example:
3325 //
3326 // void (^myImportedBlock)(void);
3327 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3328 //
3329 // void (^anotherBlock)(void);
3330 // anotherBlock = ^(void) {
3331 // myImportedBlock(); // import and invoke the closure
3332 // };
3333 //
3334 if (isBlockPointerType((*I)->getType())) {
3335 S += "struct __block_impl *";
3336 Constructor += ", void *" + ArgName;
3337 } else {
3338 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3339 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3340 Constructor += ", " + ArgName;
3341 }
3342 S += FieldName + "; // by ref\n";
3343 }
3344 // Finish writing the constructor.
3345 // FIXME: handle NSConcreteGlobalBlock.
3346 Constructor += ", int flags=0) {\n";
3347 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3348 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3349
3350 if (hasCopyDisposeHelpers)
3351 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3352
3353 // Initialize all "by copy" arguments.
3354 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3355 E = BlockByCopyDecls.end(); I != E; ++I) {
3356 std::string Name = (*I)->getName();
3357 Constructor += " ";
3358 if (isBlockPointerType((*I)->getType()))
3359 Constructor += Name + " = (struct __block_impl *)_";
3360 else
3361 Constructor += Name + " = _";
3362 Constructor += Name + ";\n";
3363 }
3364 // Initialize all "by ref" arguments.
3365 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3366 E = BlockByRefDecls.end(); I != E; ++I) {
3367 std::string Name = (*I)->getName();
3368 Constructor += " ";
3369 if (isBlockPointerType((*I)->getType()))
3370 Constructor += Name + " = (struct __block_impl *)_";
3371 else
3372 Constructor += Name + " = _";
3373 Constructor += Name + ";\n";
3374 }
3375 } else {
3376 // Finish writing the constructor.
3377 // FIXME: handle NSConcreteGlobalBlock.
3378 Constructor += ", int flags=0) {\n";
3379 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3380 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3381 if (hasCopyDisposeHelpers)
3382 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3383 }
3384 Constructor += " ";
3385 Constructor += "}\n";
3386 S += Constructor;
3387 S += "};\n";
3388 return S;
3389}
3390
3391void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3392 const char *FunName) {
3393 // Insert closures that were part of the function.
3394 for (unsigned i = 0; i < Blocks.size(); i++) {
3395
3396 CollectBlockDeclRefInfo(Blocks[i]);
3397
3398 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3399
3400 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3401 ImportedBlockDecls.size() > 0);
3402
3403 InsertText(FunLocStart, CI.c_str(), CI.size());
3404
3405 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3406
3407 InsertText(FunLocStart, CF.c_str(), CF.size());
3408
3409 if (ImportedBlockDecls.size()) {
3410 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3411 InsertText(FunLocStart, HF.c_str(), HF.size());
3412 }
3413
3414 BlockDeclRefs.clear();
3415 BlockByRefDecls.clear();
3416 BlockByCopyDecls.clear();
3417 BlockCallExprs.clear();
3418 ImportedBlockDecls.clear();
3419 }
3420 Blocks.clear();
3421 RewrittenBlockExprs.clear();
3422}
3423
3424void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3425 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3426 const char *FuncName = FD->getName();
3427
3428 SynthesizeBlockLiterals(FunLocStart, FuncName);
3429}
3430
3431void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003432 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3433 //SourceLocation FunLocStart = MD->getLocStart();
3434 // FIXME: This hack works around a bug in Rewrite.InsertText().
3435 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003436 std::string FuncName = std::string(MD->getSelector().getName());
3437 // Convert colons to underscores.
3438 std::string::size_type loc = 0;
3439 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3440 FuncName.replace(loc, 1, "_");
3441
3442 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3443}
3444
3445void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3446 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3447 CI != E; ++CI)
3448 if (*CI) {
3449 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3450 GetBlockDeclRefExprs(CBE->getBody());
3451 else
3452 GetBlockDeclRefExprs(*CI);
3453 }
3454 // Handle specific things.
3455 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3456 // FIXME: Handle enums.
3457 if (!isa<FunctionDecl>(CDRE->getDecl()))
3458 BlockDeclRefs.push_back(CDRE);
3459 return;
3460}
3461
3462void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3463 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3464 CI != E; ++CI)
3465 if (*CI) {
3466 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3467 GetBlockCallExprs(CBE->getBody());
3468 else
3469 GetBlockCallExprs(*CI);
3470 }
3471
3472 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3473 if (CE->getCallee()->getType()->isBlockPointerType()) {
3474 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3475 }
3476 }
3477 return;
3478}
3479
Steve Naroff85eb17b2008-10-30 10:07:53 +00003480Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003481 // Navigate to relevant type information.
3482 const char *closureName = 0;
3483 const BlockPointerType *CPT = 0;
3484
3485 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3486 closureName = DRE->getDecl()->getName();
3487 CPT = DRE->getType()->getAsBlockPointerType();
3488 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3489 closureName = CDRE->getDecl()->getName();
3490 CPT = CDRE->getType()->getAsBlockPointerType();
3491 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3492 closureName = MExpr->getMemberDecl()->getName();
3493 CPT = MExpr->getType()->getAsBlockPointerType();
3494 } else {
3495 assert(1 && "RewriteBlockClass: Bad type");
3496 }
3497 assert(CPT && "RewriteBlockClass: Bad type");
3498 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3499 assert(FT && "RewriteBlockClass: Bad type");
3500 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3501 // FTP will be null for closures that don't take arguments.
3502
Steve Naroff85eb17b2008-10-30 10:07:53 +00003503 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3504 SourceLocation(),
3505 &Context->Idents.get("__block_impl"));
3506 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003507
Steve Naroff85eb17b2008-10-30 10:07:53 +00003508 // Generate a funky cast.
3509 llvm::SmallVector<QualType, 8> ArgTypes;
3510
3511 // Push the block argument type.
3512 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003513 if (FTP) {
3514 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003515 E = FTP->arg_type_end(); I && (I != E); ++I) {
3516 QualType t = *I;
3517 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3518 if (isBlockPointerType(t)) {
3519 const BlockPointerType *BPT = t->getAsBlockPointerType();
3520 t = Context->getPointerType(BPT->getPointeeType());
3521 }
3522 ArgTypes.push_back(t);
3523 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003524 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003525 // Now do the pointer to function cast.
3526 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3527 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3528
3529 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003530
Steve Naroff7f1412d2008-11-03 23:29:32 +00003531 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003532 // Don't forget the parens to enforce the proper binding.
3533 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3534 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003535
Steve Naroff85eb17b2008-10-30 10:07:53 +00003536 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3537 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3538 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3539
Steve Naroff7f1412d2008-11-03 23:29:32 +00003540 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003541 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3542
3543 llvm::SmallVector<Expr*, 8> BlkExprs;
3544 // Add the implicit argument.
3545 BlkExprs.push_back(BlkCast);
3546 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003547 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3548 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003549 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003550 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003551 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3552 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003553}
3554
3555void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003556 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3557 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003558}
3559
3560void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3561 // FIXME: Add more elaborate code generation required by the ABI.
3562 InsertText(BDRE->getLocStart(), "*", 1);
3563}
3564
Steve Naroff7f1412d2008-11-03 23:29:32 +00003565void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3566 SourceLocation LocStart = CE->getLParenLoc();
3567 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003568
3569 // Need to avoid trying to rewrite synthesized casts.
3570 if (LocStart.isInvalid())
3571 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003572 // Need to avoid trying to rewrite casts contained in macros.
3573 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3574 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003575
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003576 const char *startBuf = SM->getCharacterData(LocStart);
3577 const char *endBuf = SM->getCharacterData(LocEnd);
3578
3579 // advance the location to startArgList.
3580 const char *argPtr = startBuf;
3581
3582 while (*argPtr++ && (argPtr < endBuf)) {
3583 switch (*argPtr) {
3584 case '^':
3585 // Replace the '^' with '*'.
3586 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3587 ReplaceText(LocStart, 1, "*", 1);
3588 break;
3589 }
3590 }
3591 return;
3592}
3593
3594void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3595 SourceLocation DeclLoc = FD->getLocation();
3596 unsigned parenCount = 0;
3597
3598 // We have 1 or more arguments that have closure pointers.
3599 const char *startBuf = SM->getCharacterData(DeclLoc);
3600 const char *startArgList = strchr(startBuf, '(');
3601
3602 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3603
3604 parenCount++;
3605 // advance the location to startArgList.
3606 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3607 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3608
3609 const char *argPtr = startArgList;
3610
3611 while (*argPtr++ && parenCount) {
3612 switch (*argPtr) {
3613 case '^':
3614 // Replace the '^' with '*'.
3615 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3616 ReplaceText(DeclLoc, 1, "*", 1);
3617 break;
3618 case '(':
3619 parenCount++;
3620 break;
3621 case ')':
3622 parenCount--;
3623 break;
3624 }
3625 }
3626 return;
3627}
3628
3629bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3630 const FunctionTypeProto *FTP;
3631 const PointerType *PT = QT->getAsPointerType();
3632 if (PT) {
3633 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3634 } else {
3635 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3636 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3637 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3638 }
3639 if (FTP) {
3640 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3641 E = FTP->arg_type_end(); I != E; ++I)
3642 if (isBlockPointerType(*I))
3643 return true;
3644 }
3645 return false;
3646}
3647
3648void RewriteObjC::GetExtentOfArgList(const char *Name,
3649 const char *&LParen, const char *&RParen) {
3650 const char *argPtr = strchr(Name, '(');
3651 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3652
3653 LParen = argPtr; // output the start.
3654 argPtr++; // skip past the left paren.
3655 unsigned parenCount = 1;
3656
3657 while (*argPtr && parenCount) {
3658 switch (*argPtr) {
3659 case '(': parenCount++; break;
3660 case ')': parenCount--; break;
3661 default: break;
3662 }
3663 if (parenCount) argPtr++;
3664 }
3665 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3666 RParen = argPtr; // output the end
3667}
3668
3669void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3671 RewriteBlockPointerFunctionArgs(FD);
3672 return;
3673 }
3674 // Handle Variables and Typedefs.
3675 SourceLocation DeclLoc = ND->getLocation();
3676 QualType DeclT;
3677 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3678 DeclT = VD->getType();
3679 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3680 DeclT = TDD->getUnderlyingType();
3681 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3682 DeclT = FD->getType();
3683 else
3684 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3685
3686 const char *startBuf = SM->getCharacterData(DeclLoc);
3687 const char *endBuf = startBuf;
3688 // scan backward (from the decl location) for the end of the previous decl.
3689 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3690 startBuf--;
3691
3692 // *startBuf != '^' if we are dealing with a pointer to function that
3693 // may take block argument types (which will be handled below).
3694 if (*startBuf == '^') {
3695 // Replace the '^' with '*', computing a negative offset.
3696 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3697 ReplaceText(DeclLoc, 1, "*", 1);
3698 }
3699 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3700 // Replace the '^' with '*' for arguments.
3701 DeclLoc = ND->getLocation();
3702 startBuf = SM->getCharacterData(DeclLoc);
3703 const char *argListBegin, *argListEnd;
3704 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3705 while (argListBegin < argListEnd) {
3706 if (*argListBegin == '^') {
3707 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3708 ReplaceText(CaretLoc, 1, "*", 1);
3709 }
3710 argListBegin++;
3711 }
3712 }
3713 return;
3714}
3715
3716void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3717 // Add initializers for any closure decl refs.
3718 GetBlockDeclRefExprs(Exp->getBody());
3719 if (BlockDeclRefs.size()) {
3720 // Unique all "by copy" declarations.
3721 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3722 if (!BlockDeclRefs[i]->isByRef())
3723 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3724 // Unique all "by ref" declarations.
3725 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3726 if (BlockDeclRefs[i]->isByRef()) {
3727 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3728 }
3729 // Find any imported blocks...they will need special attention.
3730 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3731 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
3732 GetBlockCallExprs(Blocks[i]);
3733 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3734 }
3735 }
3736}
3737
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003738FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3739 IdentifierInfo *ID = &Context->Idents.get(name);
3740 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3741 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3742 ID, FType, FunctionDecl::Extern, false, 0);
3743}
3744
Steve Naroff80c54752008-10-29 18:15:37 +00003745Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003746 Blocks.push_back(Exp);
3747
3748 CollectBlockDeclRefInfo(Exp);
3749 std::string FuncName;
3750
3751 if (CurFunctionDef)
3752 FuncName = std::string(CurFunctionDef->getName());
3753 else if (CurMethodDef) {
3754 FuncName = std::string(CurMethodDef->getSelector().getName());
3755 // Convert colons to underscores.
3756 std::string::size_type loc = 0;
3757 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3758 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00003759 } else if (GlobalVarDecl)
3760 FuncName = std::string(GlobalVarDecl->getName());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003761
3762 std::string BlockNumber = utostr(Blocks.size()-1);
3763
3764 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3765 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3766
3767 // Get a pointer to the function type so we can cast appropriately.
3768 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3769
3770 FunctionDecl *FD;
3771 Expr *NewRep;
3772
3773 // Simulate a contructor call...
3774 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3775 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3776
3777 llvm::SmallVector<Expr*, 4> InitExprs;
3778
Steve Naroffd0419d62008-10-29 21:23:59 +00003779 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003780 FD = SynthBlockInitFunctionDecl(Func.c_str());
3781 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3782 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003783 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003784 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003785
3786 if (ImportedBlockDecls.size()) {
3787 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00003788 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3789 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3790 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003791 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00003792 InitExprs.push_back(castExpr);
3793
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003794 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00003795 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3796 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3797 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003798 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00003799 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003800 }
3801 // Add initializers for any closure decl refs.
3802 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003803 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003804 // Output all "by copy" declarations.
3805 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3806 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003807 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003808 // FIXME: Conform to ABI ([[obj retain] autorelease]).
3809 FD = SynthBlockInitFunctionDecl((*I)->getName());
3810 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003811 } else if (isBlockPointerType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003812 FD = SynthBlockInitFunctionDecl((*I)->getName());
3813 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3814 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroff7f1412d2008-11-03 23:29:32 +00003815 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003816 } else {
Steve Naroffd0419d62008-10-29 21:23:59 +00003817 FD = SynthBlockInitFunctionDecl((*I)->getName());
3818 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003819 }
Steve Naroffd0419d62008-10-29 21:23:59 +00003820 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003821 }
3822 // Output all "by ref" declarations.
3823 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3824 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroffd0419d62008-10-29 21:23:59 +00003825 FD = SynthBlockInitFunctionDecl((*I)->getName());
3826 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3827 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3828 Context->getPointerType(Exp->getType()),
3829 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003830 }
3831 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003832 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3833 FType, SourceLocation());
3834 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3835 Context->getPointerType(NewRep->getType()),
3836 SourceLocation());
Steve Naroff7f1412d2008-11-03 23:29:32 +00003837 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003838 BlockDeclRefs.clear();
3839 BlockByRefDecls.clear();
3840 BlockByCopyDecls.clear();
3841 ImportedBlockDecls.clear();
3842 return NewRep;
3843}
3844
3845//===----------------------------------------------------------------------===//
3846// Function Body / Expression rewriting
3847//===----------------------------------------------------------------------===//
3848
3849Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3850 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3851 isa<DoStmt>(S) || isa<ForStmt>(S))
3852 Stmts.push_back(S);
3853 else if (isa<ObjCForCollectionStmt>(S)) {
3854 Stmts.push_back(S);
3855 ObjCBcLabelNo.push_back(++BcLabelCount);
3856 }
3857
3858 SourceRange OrigStmtRange = S->getSourceRange();
3859
3860 // Perform a bottom up rewrite of all children.
3861 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3862 CI != E; ++CI)
3863 if (*CI) {
3864 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3865 if (newStmt)
3866 *CI = newStmt;
3867 }
3868
3869 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3870 // Rewrite the block body in place.
3871 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3872
3873 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00003874 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3875 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003876
3877 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3878 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00003879 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003880 return blockTranscribed;
3881 }
3882 // Handle specific things.
3883 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3884 return RewriteAtEncode(AtEncode);
3885
3886 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3887 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3888
3889 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3890 return RewriteAtSelector(AtSelector);
3891
3892 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3893 return RewriteObjCStringLiteral(AtString);
3894
3895 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3896 // Before we rewrite it, put the original message expression in a comment.
3897 SourceLocation startLoc = MessExpr->getLocStart();
3898 SourceLocation endLoc = MessExpr->getLocEnd();
3899
3900 const char *startBuf = SM->getCharacterData(startLoc);
3901 const char *endBuf = SM->getCharacterData(endLoc);
3902
3903 std::string messString;
3904 messString += "// ";
3905 messString.append(startBuf, endBuf-startBuf+1);
3906 messString += "\n";
3907
3908 // FIXME: Missing definition of
3909 // InsertText(clang::SourceLocation, char const*, unsigned int).
3910 // InsertText(startLoc, messString.c_str(), messString.size());
3911 // Tried this, but it didn't work either...
3912 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3913 return RewriteMessageExpr(MessExpr);
3914 }
3915
3916 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3917 return RewriteObjCTryStmt(StmtTry);
3918
3919 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3920 return RewriteObjCSynchronizedStmt(StmtTry);
3921
3922 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3923 return RewriteObjCThrowStmt(StmtThrow);
3924
3925 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3926 return RewriteObjCProtocolExpr(ProtocolExp);
3927
3928 if (ObjCForCollectionStmt *StmtForCollection =
3929 dyn_cast<ObjCForCollectionStmt>(S))
3930 return RewriteObjCForCollectionStmt(StmtForCollection,
3931 OrigStmtRange.getEnd());
3932 if (BreakStmt *StmtBreakStmt =
3933 dyn_cast<BreakStmt>(S))
3934 return RewriteBreakStmt(StmtBreakStmt);
3935 if (ContinueStmt *StmtContinueStmt =
3936 dyn_cast<ContinueStmt>(S))
3937 return RewriteContinueStmt(StmtContinueStmt);
3938
3939 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3940 // and cast exprs.
3941 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3942 // FIXME: What we're doing here is modifying the type-specifier that
3943 // precedes the first Decl. In the future the DeclGroup should have
3944 // a separate type-specifier that we can rewrite.
3945 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3946
3947 // Blocks rewrite rules.
3948 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3949 DI != DE; ++DI) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003950 ScopedDecl *SD = *DI;
3951 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3952 if (isBlockPointerType(ND->getType()))
3953 RewriteBlockPointerDecl(ND);
3954 else if (ND->getType()->isFunctionPointerType())
3955 CheckFunctionPointerDecl(ND->getType(), ND);
3956 }
3957 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3958 if (isBlockPointerType(TD->getUnderlyingType()))
3959 RewriteBlockPointerDecl(TD);
3960 else if (TD->getUnderlyingType()->isFunctionPointerType())
3961 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3962 }
3963 }
3964 }
3965
3966 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3967 RewriteObjCQualifiedInterfaceTypes(CE);
3968
3969 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3970 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3971 assert(!Stmts.empty() && "Statement stack is empty");
3972 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3973 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3974 && "Statement stack mismatch");
3975 Stmts.pop_back();
3976 }
3977 // Handle blocks rewriting.
3978 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3979 if (BDRE->isByRef())
3980 RewriteBlockDeclRefExpr(BDRE);
3981 }
3982 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003983 if (CE->getCallee()->getType()->isBlockPointerType()) {
3984 Stmt *BlockCall = SynthesizeBlockCall(CE);
3985 ReplaceStmt(S, BlockCall);
3986 return BlockCall;
3987 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003988 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00003989 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003990 RewriteCastExpr(CE);
3991 }
3992#if 0
3993 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
3994 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
3995 // Get the new text.
3996 std::string SStr;
3997 llvm::raw_string_ostream Buf(SStr);
3998 Replacement->printPretty(Buf);
3999 const std::string &Str = Buf.str();
4000
4001 printf("CAST = %s\n", &Str[0]);
4002 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4003 delete S;
4004 return Replacement;
4005 }
4006#endif
4007 // Return this stmt unmodified.
4008 return S;
4009}
4010
4011/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4012/// main file of the input.
4013void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4015 // Since function prototypes don't have ParmDecl's, we check the function
4016 // prototype. This enables us to rewrite function declarations and
4017 // definitions using the same code.
4018 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4019
4020 if (Stmt *Body = FD->getBody()) {
4021 CurFunctionDef = FD;
4022 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4023 // This synthesizes and inserts the block "impl" struct, invoke function,
4024 // and any copy/dispose helper functions.
4025 InsertBlockLiteralsWithinFunction(FD);
4026 CurFunctionDef = 0;
4027 }
4028 return;
4029 }
4030 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4031 if (Stmt *Body = MD->getBody()) {
4032 //Body->dump();
4033 CurMethodDef = MD;
4034 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4035 InsertBlockLiteralsWithinMethod(MD);
4036 CurMethodDef = 0;
4037 }
4038 }
4039 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4040 ClassImplementation.push_back(CI);
4041 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4042 CategoryImplementation.push_back(CI);
4043 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4044 RewriteForwardClassDecl(CD);
4045 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4046 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004047 if (isBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004048 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004049 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004050 CheckFunctionPointerDecl(VD->getType(), VD);
4051 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004052 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004053 RewriteCastExpr(CE);
4054 }
4055 }
4056 }
Steve Naroff80c54752008-10-29 18:15:37 +00004057 if (VD->getInit()) {
4058 GlobalVarDecl = VD;
4059 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4060 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4061 GlobalVarDecl = 0;
4062
4063 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004064 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004065 RewriteCastExpr(CE);
4066 }
4067 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004068 return;
4069 }
4070 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4071 if (isBlockPointerType(TD->getUnderlyingType()))
4072 RewriteBlockPointerDecl(TD);
4073 else if (TD->getUnderlyingType()->isFunctionPointerType())
4074 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4075 return;
4076 }
4077 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4078 if (RD->isDefinition()) {
4079 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4080 e = RD->field_end(); i != e; ++i) {
4081 FieldDecl *FD = *i;
4082 if (isBlockPointerType(FD->getType()))
4083 RewriteBlockPointerDecl(FD);
4084 }
4085 }
4086 return;
4087 }
4088 // Nothing yet.
4089}
4090
4091void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4092 // Get the top-level buffer that this corresponds to.
4093
4094 // Rewrite tabs if we care.
4095 //RewriteTabs();
4096
4097 if (Diags.hasErrorOccurred())
4098 return;
4099
4100 // Create the output file.
4101
4102 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4103 llvm::raw_ostream *OutFile;
4104 if (OutFileName == "-") {
4105 OutFile = &llvm::outs();
4106 } else if (!OutFileName.empty()) {
4107 std::string Err;
4108 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
4109 OwnedStream.reset(OutFile);
4110 } else if (InFileName == "-") {
4111 OutFile = &llvm::outs();
4112 } else {
4113 llvm::sys::Path Path(InFileName);
4114 Path.eraseSuffix();
4115 Path.appendSuffix("cpp");
4116 std::string Err;
4117 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
4118 OwnedStream.reset(OutFile);
4119 }
4120
4121 RewriteInclude();
4122
4123 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4124 Preamble.c_str(), Preamble.size(), false);
4125
4126 // Rewrite Objective-c meta data*
4127 std::string ResultStr;
4128 RewriteImplementations(ResultStr);
4129
4130 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4131 // we are done.
4132 if (const RewriteBuffer *RewriteBuf =
4133 Rewrite.getRewriteBufferFor(MainFileID)) {
4134 //printf("Changed:\n");
4135 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4136 } else {
4137 fprintf(stderr, "No changes\n");
4138 }
4139 // Emit metadata.
4140 *OutFile << ResultStr;
4141 OutFile->flush();
4142}
4143