blob: 4eba8cc816c1ee2a092e4924209ee64689edc055 [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;
108
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000109 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000110 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000111 virtual void Initialize(ASTContext &context);
112
113 virtual void InitializeTU(TranslationUnit &TU) {
114 TU.SetOwnsDecls(false);
115 Initialize(TU.getContext());
116 }
Chris Lattner12499682008-01-31 19:38:44 +0000117
Chris Lattner569faa62007-10-11 18:38:32 +0000118
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000119 // Top Level Driver code.
120 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000121 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000122 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000123 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000124
125 ~RewriteObjC() {}
126
127 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerb1548372008-01-31 19:37:57 +0000128
129 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000130 // If replacement succeeded or warning disabled return with no warning.
131 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000132 return;
133
Chris Lattnerb1548372008-01-31 19:37:57 +0000134 SourceRange Range = Old->getSourceRange();
135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
136 0, 0, &Range, 1);
137 }
138
Steve Narofffef037c2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000148
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000156
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
172 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000173 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000174 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
175 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
176 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
177 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
178 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000179 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000180 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000181 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000182 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000183 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000184 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000185 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000186 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000187 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000188
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000189 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000190 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000191 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000192 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff296b74f2007-11-05 14:50:49 +0000193 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000194 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000195 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000196 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000197 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000198 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000199 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
200 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
201 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000202 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
203 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000204 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
205 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000206 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000207 Stmt *RewriteBreakStmt(BreakStmt *S);
208 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000209 void SynthCountByEnumWithState(std::string &buf);
210
Steve Naroff02a82aa2007-10-30 23:14:51 +0000211 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000212 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000213 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000214 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000215 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000216 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000217 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000218 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000219 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000220 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000221
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000222 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000223 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000224 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000225
Ted Kremenek42730c52008-01-07 19:49:32 +0000226 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000228
Ted Kremenek42730c52008-01-07 19:49:32 +0000229 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
230 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000231 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000232 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000233 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000234 const char *ClassName,
235 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000236
Chris Lattner0be08822008-07-21 21:32:27 +0000237 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
238 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000239 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000240 const char *ClassName,
241 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000242 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000243 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000244 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
245 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000246 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000247 void RewriteImplementations(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000248
249 // Block rewriting.
250 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
251 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
252
253 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
254 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
255
256 // Block specific rewrite rules.
257 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
258
259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
270 std::string SynthesizeBlockCall(CallExpr *Exp);
271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
302 void RewriteCastExpr(CastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000303
304 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
305 Stmt *SynthBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000306 };
307}
308
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000309void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
310 NamedDecl *D) {
311 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
312 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
313 E = fproto->arg_type_end(); I && (I != E); ++I)
314 if (isBlockPointerType(*I)) {
315 // All the args are checked/rewritten. Don't call twice!
316 RewriteBlockPointerDecl(D);
317 break;
318 }
319 }
320}
321
322void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
323 const PointerType *PT = funcType->getAsPointerType();
324 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
325 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
326}
327
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000328static bool IsHeaderFile(const std::string &Filename) {
329 std::string::size_type DotPos = Filename.rfind('.');
330
331 if (DotPos == std::string::npos) {
332 // no file extension
333 return false;
334 }
335
336 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
337 // C header: .h
338 // C++ header: .hh or .H;
339 return Ext == "h" || Ext == "hh" || Ext == "H";
340}
341
Steve Naroff44e81222008-04-14 22:03:09 +0000342RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000343 Diagnostic &D, const LangOptions &LOpts)
344 : Diags(D), LangOpts(LOpts) {
345 IsHeader = IsHeaderFile(inFile);
346 InFileName = inFile;
347 OutFileName = outFile;
348 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
349 "rewriting sub-expression within a macro (may not be correct)");
350}
351
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000352ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000353 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000354 Diagnostic &Diags,
355 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000356 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000357}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000358
Steve Naroff44e81222008-04-14 22:03:09 +0000359void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000360 Context = &context;
361 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000362 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000363 MsgSendFunctionDecl = 0;
364 MsgSendSuperFunctionDecl = 0;
365 MsgSendStretFunctionDecl = 0;
366 MsgSendSuperStretFunctionDecl = 0;
367 MsgSendFpretFunctionDecl = 0;
368 GetClassFunctionDecl = 0;
369 GetMetaClassFunctionDecl = 0;
370 SelGetUidFunctionDecl = 0;
371 CFStringFunctionDecl = 0;
372 GetProtocolFunctionDecl = 0;
373 ConstantStringClassReference = 0;
374 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000375 CurMethodDef = 0;
376 CurFunctionDef = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000377 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000378 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000379 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000380 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000381 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000382
383 // Get the ID and start/end of the main file.
384 MainFileID = SM->getMainFileID();
385 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
386 MainFileStart = MainBuf->getBufferStart();
387 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000388
Chris Lattner12499682008-01-31 19:38:44 +0000389 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000390
Chris Lattner12499682008-01-31 19:38:44 +0000391 // declaring objc_selector outside the parameter list removes a silly
392 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000393 if (IsHeader)
394 Preamble = "#pragma once\n";
395 Preamble += "struct objc_selector; struct objc_class;\n";
396 Preamble += "#ifndef OBJC_SUPER\n";
397 Preamble += "struct objc_super { struct objc_object *object; ";
398 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000399 if (LangOpts.Microsoft) {
400 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000401 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
402 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000403 }
Steve Narofffef037c2008-03-27 22:29:16 +0000404 Preamble += "};\n";
405 Preamble += "#define OBJC_SUPER\n";
406 Preamble += "#endif\n";
407 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
408 Preamble += "typedef struct objc_object Protocol;\n";
409 Preamble += "#define _REWRITER_typedef_Protocol\n";
410 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000411 if (LangOpts.Microsoft)
Steve Naroff618c6a42008-05-06 22:45:19 +0000412 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
413 else
414 Preamble += "#define __OBJC_RW_EXTERN extern\n";
415 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000416 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff31316a12008-05-08 22:02:18 +0000423 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroffa9636222008-05-08 17:52:16 +0000425 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000426 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000434 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000435 // @synchronized hooks.
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff618c6a42008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000439 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
440 Preamble += "struct __objcFastEnumerationState {\n\t";
441 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000442 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000443 Preamble += "unsigned long *mutationsPtr;\n\t";
444 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff37157242008-06-02 20:23:21 +0000445 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000446 Preamble += "#define __FASTENUMERATIONSTATE\n";
447 Preamble += "#endif\n";
448 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
449 Preamble += "struct __NSConstantStringImpl {\n";
450 Preamble += " int *isa;\n";
451 Preamble += " int flags;\n";
452 Preamble += " char *str;\n";
453 Preamble += " long length;\n";
454 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000455 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
456 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
457 Preamble += "#else\n";
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000458 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000459 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000460 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
461 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000462 // Blocks preamble.
463 Preamble += "#ifndef BLOCK_IMPL\n";
464 Preamble += "#define BLOCK_IMPL\n";
465 Preamble += "struct __block_impl {\n";
466 Preamble += " void *isa;\n";
467 Preamble += " int Flags;\n";
468 Preamble += " int Size;\n";
469 Preamble += " void *FuncPtr;\n";
470 Preamble += "};\n";
471 Preamble += "enum {\n";
472 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
473 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
474 Preamble += "};\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000475 Preamble += "// Runtime copy/destroy helper functions\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
481 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
482 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000483 if (LangOpts.Microsoft) {
484 Preamble += "#undef __OBJC_RW_EXTERN\n";
485 Preamble += "#define __attribute__(X)\n";
486 }
Chris Lattner12499682008-01-31 19:38:44 +0000487}
488
489
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000490//===----------------------------------------------------------------------===//
491// Top Level Driver Code
492//===----------------------------------------------------------------------===//
493
Steve Naroff44e81222008-04-14 22:03:09 +0000494void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000495 // Two cases: either the decl could be in the main file, or it could be in a
496 // #included file. If the former, rewrite it now. If the later, check to see
497 // if we rewrote the #include/#import.
498 SourceLocation Loc = D->getLocation();
499 Loc = SM->getLogicalLoc(Loc);
500
501 // If this is for a builtin, ignore it.
502 if (Loc.isInvalid()) return;
503
Steve Naroffe9780582007-10-23 23:50:29 +0000504 // Look for built-in declarations that we need to refer during the rewrite.
505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000506 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000507 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000508 // declared in <Foundation/NSString.h>
509 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
510 ConstantStringClassReference = FVD;
511 return;
512 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000513 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000514 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000515 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000516 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000517 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000518 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000519 } else if (ObjCForwardProtocolDecl *FP =
520 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000521 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000522 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000523 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000524 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000525 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000526}
527
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000528//===----------------------------------------------------------------------===//
529// Syntactic (non-AST) Rewriting Code
530//===----------------------------------------------------------------------===//
531
Steve Naroff44e81222008-04-14 22:03:09 +0000532void RewriteObjC::RewriteInclude() {
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000533 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
534 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
535 const char *MainBufStart = MainBuf.first;
536 const char *MainBufEnd = MainBuf.second;
537 size_t ImportLen = strlen("import");
538 size_t IncludeLen = strlen("include");
539
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000540 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000541 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
542 if (*BufPtr == '#') {
543 if (++BufPtr == MainBufEnd)
544 return;
545 while (*BufPtr == ' ' || *BufPtr == '\t')
546 if (++BufPtr == MainBufEnd)
547 return;
548 if (!strncmp(BufPtr, "import", ImportLen)) {
549 // replace import with include
550 SourceLocation ImportLoc =
551 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000552 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000553 BufPtr += ImportLen;
554 }
555 }
556 }
Chris Lattner74db1682007-10-16 21:07:07 +0000557}
558
Steve Naroff44e81222008-04-14 22:03:09 +0000559void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000560 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
561 const char *MainBufStart = MainBuf.first;
562 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000563
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000564 // Loop over the whole file, looking for tabs.
565 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
566 if (*BufPtr != '\t')
567 continue;
568
569 // Okay, we found a tab. This tab will turn into at least one character,
570 // but it depends on which 'virtual column' it is in. Compute that now.
571 unsigned VCol = 0;
572 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
573 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
574 ++VCol;
575
576 // Okay, now that we know the virtual column, we know how many spaces to
577 // insert. We assume 8-character tab-stops.
578 unsigned Spaces = 8-(VCol & 7);
579
580 // Get the location of the tab.
581 SourceLocation TabLoc =
582 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
583
584 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000585 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000586 }
Chris Lattner569faa62007-10-11 18:38:32 +0000587}
588
589
Steve Naroff44e81222008-04-14 22:03:09 +0000590void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000591 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000592 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000593
594 // Get the start location and compute the semi location.
595 SourceLocation startLoc = ClassDecl->getLocation();
596 const char *startBuf = SM->getCharacterData(startLoc);
597 const char *semiPtr = strchr(startBuf, ';');
598
599 // Translate to typedef's that forward reference structs with the same name
600 // as the class. As a convenience, we include the original declaration
601 // as a comment.
602 std::string typedefString;
603 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000604 typedefString.append(startBuf, semiPtr-startBuf+1);
605 typedefString += "\n";
606 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000607 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000608 typedefString += "#ifndef _REWRITER_typedef_";
609 typedefString += ForwardDecl->getName();
610 typedefString += "\n";
611 typedefString += "#define _REWRITER_typedef_";
612 typedefString += ForwardDecl->getName();
613 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000614 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000615 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000616 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000617 }
618
619 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000620 ReplaceText(startLoc, semiPtr-startBuf+1,
621 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000622}
623
Steve Naroff44e81222008-04-14 22:03:09 +0000624void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000625 SourceLocation LocStart = Method->getLocStart();
626 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000627
Steve Naroff2ce399a2007-12-14 23:37:57 +0000628 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000629 InsertText(LocStart, "#if 0\n", 6);
630 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000631 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000632 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000633 }
634}
635
Steve Naroff44e81222008-04-14 22:03:09 +0000636void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000637{
Chris Lattnercffe3662008-03-16 21:23:50 +0000638 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000639 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000640 SourceLocation Loc = Property->getLocation();
641
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000642 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000643
644 // FIXME: handle properties that are declared across multiple lines.
645 }
646}
647
Steve Naroff44e81222008-04-14 22:03:09 +0000648void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000649 SourceLocation LocStart = CatDecl->getLocStart();
650
651 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000652 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000653
Ted Kremenek42730c52008-01-07 19:49:32 +0000654 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000655 E = CatDecl->instmeth_end(); I != E; ++I)
656 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000657 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000658 E = CatDecl->classmeth_end(); I != E; ++I)
659 RewriteMethodDeclaration(*I);
660
Steve Naroff667f1682007-10-30 13:30:57 +0000661 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000662 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000663}
664
Steve Naroff44e81222008-04-14 22:03:09 +0000665void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000666 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000667
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000668 SourceLocation LocStart = PDecl->getLocStart();
669
670 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000671 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000672
Ted Kremenek42730c52008-01-07 19:49:32 +0000673 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000674 E = PDecl->instmeth_end(); I != E; ++I)
675 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000676 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000677 E = PDecl->classmeth_end(); I != E; ++I)
678 RewriteMethodDeclaration(*I);
679
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000680 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000681 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000682 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000683
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000684 // Must comment out @optional/@required
685 const char *startBuf = SM->getCharacterData(LocStart);
686 const char *endBuf = SM->getCharacterData(LocEnd);
687 for (const char *p = startBuf; p < endBuf; p++) {
688 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
689 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000690 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000691 ReplaceText(OptionalLoc, strlen("@optional"),
692 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000693
694 }
695 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
696 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000697 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000698 ReplaceText(OptionalLoc, strlen("@required"),
699 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000700
701 }
702 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000703}
704
Steve Naroff44e81222008-04-14 22:03:09 +0000705void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000706 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000707 if (LocStart.isInvalid())
708 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000709 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000710 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000711}
712
Steve Naroff44e81222008-04-14 22:03:09 +0000713void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000714 std::string &ResultStr) {
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();
797 PDecl->getType().getAsStringInternal(Name);
798 ResultStr += Name;
799 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000800 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000801 if (OMD->isVariadic())
802 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000803 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000804
Steve Naroff91044cf2008-07-16 14:40:40 +0000805 if (FPRetType) {
806 ResultStr += ")"; // close the precedence "scope" for "*".
807
808 // Now, emit the argument types (if any).
809 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
810 ResultStr += "(";
811 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
812 if (i) ResultStr += ", ";
813 std::string ParamStr = FT->getArgType(i).getAsString();
814 ResultStr += ParamStr;
815 }
816 if (FT->isVariadic()) {
817 if (FT->getNumArgs()) ResultStr += ", ";
818 ResultStr += "...";
819 }
820 ResultStr += ")";
821 } else {
822 ResultStr += "()";
823 }
824 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000825}
Steve Naroff44e81222008-04-14 22:03:09 +0000826void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000827 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
828 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000829
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000830 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000831 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000832 else
Chris Lattner6216f292008-01-31 19:42:41 +0000833 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000834
Ted Kremenek42730c52008-01-07 19:49:32 +0000835 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000836 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
837 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000838 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000839 ObjCMethodDecl *OMD = *I;
840 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000841 SourceLocation LocStart = OMD->getLocStart();
842 SourceLocation LocEnd = OMD->getBody()->getLocStart();
843
844 const char *startBuf = SM->getCharacterData(LocStart);
845 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000846 ReplaceText(LocStart, endBuf-startBuf,
847 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000848 }
849
Ted Kremenek42730c52008-01-07 19:49:32 +0000850 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000851 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
852 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000853 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000854 ObjCMethodDecl *OMD = *I;
855 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000856 SourceLocation LocStart = OMD->getLocStart();
857 SourceLocation LocEnd = OMD->getBody()->getLocStart();
858
859 const char *startBuf = SM->getCharacterData(LocStart);
860 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000861 ReplaceText(LocStart, endBuf-startBuf,
862 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000863 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000864 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000865 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000866 else
Chris Lattner6216f292008-01-31 19:42:41 +0000867 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000868}
869
Steve Naroff44e81222008-04-14 22:03:09 +0000870void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000871 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000872 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000873 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000874 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000875 ResultStr += ClassDecl->getName();
876 ResultStr += "\n";
877 ResultStr += "#define _REWRITER_typedef_";
878 ResultStr += ClassDecl->getName();
879 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000880 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000881 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000882 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000883 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000884 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000885 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000886 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000887
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000888 RewriteProperties(ClassDecl->getNumPropertyDecl(),
889 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000890 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000891 E = ClassDecl->instmeth_end(); I != E; ++I)
892 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000893 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000894 E = ClassDecl->classmeth_end(); I != E; ++I)
895 RewriteMethodDeclaration(*I);
896
Steve Naroff1ccf4632007-10-30 03:43:13 +0000897 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000898 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000899}
900
Chris Lattner343c82b2008-05-23 20:40:52 +0000901Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
902 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000903 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000904 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000905 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000906 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
907 // lookup which class implements the instance variable.
908 ObjCInterfaceDecl *clsDeclared = 0;
909 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
910 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
911
912 // Synthesize an explicit cast to gain access to the ivar.
913 std::string RecName = clsDeclared->getIdentifier()->getName();
914 RecName += "_IMPL";
915 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000916 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000917 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +0000918 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
919 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +0000920 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor21a04f32008-10-27 19:41:14 +0000921 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +0000922 // Don't forget the parens to enforce the proper binding.
Chris Lattner343c82b2008-05-23 20:40:52 +0000923 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
924 IV->getBase()->getLocEnd(),
925 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +0000926 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000927 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner343c82b2008-05-23 20:40:52 +0000928 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
929 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +0000930 ReplaceStmt(IV, ME);
931 delete IV;
932 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +0000933 }
Chris Lattner343c82b2008-05-23 20:40:52 +0000934
935 ReplaceStmt(IV->getBase(), PE);
936 // Cannot delete IV->getBase(), since PE points to it.
937 // Replace the old base with the cast. This is important when doing
938 // embedded rewrites. For example, [newInv->_container addObject:0].
939 IV->setBase(PE);
940 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000941 }
Steve Naroffe6155362008-04-18 21:55:08 +0000942 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +0000943 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
944
945 // Explicit ivar refs need to have a cast inserted.
946 // FIXME: consider sharing some of this code with the code above.
947 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +0000948 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000949 // lookup which class implements the instance variable.
950 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +0000951 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000952 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
953
954 // Synthesize an explicit cast to gain access to the ivar.
955 std::string RecName = clsDeclared->getIdentifier()->getName();
956 RecName += "_IMPL";
957 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000958 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +0000959 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000960 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
961 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor035d0882008-10-28 15:36:24 +0000962 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor21a04f32008-10-27 19:41:14 +0000963 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +0000964 // Don't forget the parens to enforce the proper binding.
Chris Lattner3cca6612008-05-28 16:38:23 +0000965 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
966 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +0000967 ReplaceStmt(IV->getBase(), PE);
968 // Cannot delete IV->getBase(), since PE points to it.
969 // Replace the old base with the cast. This is important when doing
970 // embedded rewrites. For example, [newInv->_container addObject:0].
971 IV->setBase(PE);
972 return IV;
973 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000974 }
Steve Naroffe6155362008-04-18 21:55:08 +0000975 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000976}
977
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000978/// SynthCountByEnumWithState - To print:
979/// ((unsigned int (*)
980/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
981/// (void *)objc_msgSend)((id)l_collection,
982/// sel_registerName(
983/// "countByEnumeratingWithState:objects:count:"),
984/// &enumState,
985/// (id *)items, (unsigned int)16)
986///
Steve Naroff44e81222008-04-14 22:03:09 +0000987void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000988 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
989 "id *, unsigned int))(void *)objc_msgSend)";
990 buf += "\n\t\t";
991 buf += "((id)l_collection,\n\t\t";
992 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
993 buf += "\n\t\t";
994 buf += "&enumState, "
995 "(id *)items, (unsigned int)16)";
996}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000997
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000998/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
999/// statement to exit to its outer synthesized loop.
1000///
Steve Naroff44e81222008-04-14 22:03:09 +00001001Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001002 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1003 return S;
1004 // replace break with goto __break_label
1005 std::string buf;
1006
1007 SourceLocation startLoc = S->getLocStart();
1008 buf = "goto __break_label_";
1009 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001010 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001011
1012 return 0;
1013}
1014
1015/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1016/// statement to continue with its inner synthesized loop.
1017///
Steve Naroff44e81222008-04-14 22:03:09 +00001018Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001019 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1020 return S;
1021 // replace continue with goto __continue_label
1022 std::string buf;
1023
1024 SourceLocation startLoc = S->getLocStart();
1025 buf = "goto __continue_label_";
1026 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001027 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001028
1029 return 0;
1030}
1031
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001032/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001033/// It rewrites:
1034/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001035
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001036/// Into:
1037/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001038/// type elem;
1039/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001040/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001041/// id l_collection = (id)collection;
1042/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1043/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001044/// if (limit) {
1045/// unsigned long startMutations = *enumState.mutationsPtr;
1046/// do {
1047/// unsigned long counter = 0;
1048/// do {
1049/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001050/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001051/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001052/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001053/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001054/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001055/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1056/// objects:items count:16]);
1057/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001058/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001059/// }
1060/// else
1061/// elem = nil;
1062/// }
1063///
Steve Naroff44e81222008-04-14 22:03:09 +00001064Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001065 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001066 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1067 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1068 "ObjCForCollectionStmt Statement stack mismatch");
1069 assert(!ObjCBcLabelNo.empty() &&
1070 "ObjCForCollectionStmt - Label No stack empty");
1071
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001072 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001073 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001074 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001075 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001076 std::string buf;
1077 buf = "\n{\n\t";
1078 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1079 // type elem;
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001080 ScopedDecl* D = DS->getSolitaryDecl();
1081 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001082 elementTypeAsString = ElementType.getAsString();
1083 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001084 buf += " ";
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001085 elementName = D->getName();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001086 buf += elementName;
1087 buf += ";\n\t";
1088 }
Chris Lattner690c2872008-04-08 05:52:18 +00001089 else {
1090 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001091 elementName = DR->getDecl()->getName();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001092 elementTypeAsString
1093 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001094 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001095
1096 // struct __objcFastEnumerationState enumState = { 0 };
1097 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1098 // id items[16];
1099 buf += "id items[16];\n\t";
1100 // id l_collection = (id)
1101 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001102 // Find start location of 'collection' the hard way!
1103 const char *startCollectionBuf = startBuf;
1104 startCollectionBuf += 3; // skip 'for'
1105 startCollectionBuf = strchr(startCollectionBuf, '(');
1106 startCollectionBuf++; // skip '('
1107 // find 'in' and skip it.
1108 while (*startCollectionBuf != ' ' ||
1109 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1110 (*(startCollectionBuf+3) != ' ' &&
1111 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1112 startCollectionBuf++;
1113 startCollectionBuf += 3;
1114
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001115 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001116 ReplaceText(startLoc, startCollectionBuf - startBuf,
1117 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001118 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001119 SourceLocation rightParenLoc = S->getRParenLoc();
1120 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1121 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001122 buf = ";\n\t";
1123
1124 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1125 // objects:items count:16];
1126 // which is synthesized into:
1127 // unsigned int limit =
1128 // ((unsigned int (*)
1129 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1130 // (void *)objc_msgSend)((id)l_collection,
1131 // sel_registerName(
1132 // "countByEnumeratingWithState:objects:count:"),
1133 // (struct __objcFastEnumerationState *)&state,
1134 // (id *)items, (unsigned int)16);
1135 buf += "unsigned long limit =\n\t\t";
1136 SynthCountByEnumWithState(buf);
1137 buf += ";\n\t";
1138 /// if (limit) {
1139 /// unsigned long startMutations = *enumState.mutationsPtr;
1140 /// do {
1141 /// unsigned long counter = 0;
1142 /// do {
1143 /// if (startMutations != *enumState.mutationsPtr)
1144 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001145 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001146 buf += "if (limit) {\n\t";
1147 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1148 buf += "do {\n\t\t";
1149 buf += "unsigned long counter = 0;\n\t\t";
1150 buf += "do {\n\t\t\t";
1151 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1152 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1153 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001154 buf += " = (";
1155 buf += elementTypeAsString;
1156 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001157 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001158 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001159
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001160 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001161 /// } while (counter < limit);
1162 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1163 /// objects:items count:16]);
1164 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001165 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001166 /// }
1167 /// else
1168 /// elem = nil;
1169 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001170 ///
1171 buf = ";\n\t";
1172 buf += "__continue_label_";
1173 buf += utostr(ObjCBcLabelNo.back());
1174 buf += ": ;";
1175 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001176 buf += "} while (counter < limit);\n\t";
1177 buf += "} while (limit = ";
1178 SynthCountByEnumWithState(buf);
1179 buf += ");\n\t";
1180 buf += elementName;
1181 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001182 buf += "__break_label_";
1183 buf += utostr(ObjCBcLabelNo.back());
1184 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001185 buf += "}\n\t";
1186 buf += "else\n\t\t";
1187 buf += elementName;
1188 buf += " = nil;\n";
1189 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001190
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001191 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001192 if (isa<CompoundStmt>(S->getBody())) {
1193 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1194 InsertText(endBodyLoc, buf.c_str(), buf.size());
1195 } else {
1196 /* Need to treat single statements specially. For example:
1197 *
1198 * for (A *a in b) if (stuff()) break;
1199 * for (A *a in b) xxxyy;
1200 *
1201 * The following code simply scans ahead to the semi to find the actual end.
1202 */
1203 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1204 const char *semiBuf = strchr(stmtBuf, ';');
1205 assert(semiBuf && "Can't find ';'");
1206 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1207 InsertText(endBodyLoc, buf.c_str(), buf.size());
1208 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001209 Stmts.pop_back();
1210 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001211 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001212}
1213
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001214/// RewriteObjCSynchronizedStmt -
1215/// This routine rewrites @synchronized(expr) stmt;
1216/// into:
1217/// objc_sync_enter(expr);
1218/// @try stmt @finally { objc_sync_exit(expr); }
1219///
Steve Naroff44e81222008-04-14 22:03:09 +00001220Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001221 // Get the start location and compute the semi location.
1222 SourceLocation startLoc = S->getLocStart();
1223 const char *startBuf = SM->getCharacterData(startLoc);
1224
1225 assert((*startBuf == '@') && "bogus @synchronized location");
1226
1227 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001228 buf = "objc_sync_enter((id)";
1229 const char *lparenBuf = startBuf;
1230 while (*lparenBuf != '(') lparenBuf++;
1231 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001232 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1233 // the sync expression is typically a message expression that's already
1234 // been rewritten! (which implies the SourceLocation's are invalid).
1235 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001236 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001237 while (*endBuf != ')') endBuf--;
1238 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001239 buf = ");\n";
1240 // declare a new scope with two variables, _stack and _rethrow.
1241 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1242 buf += "int buf[18/*32-bit i386*/];\n";
1243 buf += "char *pointers[4];} _stack;\n";
1244 buf += "id volatile _rethrow = 0;\n";
1245 buf += "objc_exception_try_enter(&_stack);\n";
1246 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001247 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001248 startLoc = S->getSynchBody()->getLocEnd();
1249 startBuf = SM->getCharacterData(startLoc);
1250
Steve Naroff027cd0b2008-08-19 13:04:19 +00001251 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001252 SourceLocation lastCurlyLoc = startLoc;
1253 buf = "}\nelse {\n";
1254 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1255 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001256 buf += " objc_sync_exit(";
Douglas Gregor035d0882008-10-28 15:36:24 +00001257 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00001258 S->getSynchExpr(),
1259 Context->getObjCIdType(),
1260 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001261 std::string syncExprBufS;
1262 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001263 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001264 buf += syncExprBuf.str();
1265 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001266 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1267 buf += "}\n";
1268 buf += "}";
1269
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001270 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001271 return 0;
1272}
1273
Steve Naroff44e81222008-04-14 22:03:09 +00001274Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001275 // Get the start location and compute the semi location.
1276 SourceLocation startLoc = S->getLocStart();
1277 const char *startBuf = SM->getCharacterData(startLoc);
1278
1279 assert((*startBuf == '@') && "bogus @try location");
1280
1281 std::string buf;
1282 // declare a new scope with two variables, _stack and _rethrow.
1283 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1284 buf += "int buf[18/*32-bit i386*/];\n";
1285 buf += "char *pointers[4];} _stack;\n";
1286 buf += "id volatile _rethrow = 0;\n";
1287 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001288 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001289
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001290 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001291
1292 startLoc = S->getTryBody()->getLocEnd();
1293 startBuf = SM->getCharacterData(startLoc);
1294
1295 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001296
Steve Naroffe9f69842007-11-07 04:08:17 +00001297 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001298 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1299 if (catchList) {
1300 startLoc = startLoc.getFileLocWithOffset(1);
1301 buf = " /* @catch begin */ else {\n";
1302 buf += " id _caught = objc_exception_extract(&_stack);\n";
1303 buf += " objc_exception_try_enter (&_stack);\n";
1304 buf += " if (_setjmp(_stack.buf))\n";
1305 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1306 buf += " else { /* @catch continue */";
1307
1308 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001309 } else { /* no catch list */
1310 buf = "}\nelse {\n";
1311 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1312 buf += "}";
1313 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001314 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001315 bool sawIdTypedCatch = false;
1316 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001317 while (catchList) {
1318 Stmt *catchStmt = catchList->getCatchParamStmt();
1319
1320 if (catchList == S->getCatchStmts())
1321 buf = "if ("; // we are generating code for the first catch clause
1322 else
1323 buf = "else if (";
1324 startLoc = catchList->getLocStart();
1325 startBuf = SM->getCharacterData(startLoc);
1326
1327 assert((*startBuf == '@') && "bogus @catch location");
1328
1329 const char *lParenLoc = strchr(startBuf, '(');
1330
Steve Naroff397c4ce2008-02-01 22:08:12 +00001331 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001332 // Now rewrite the body...
1333 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001334 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1335 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001336 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1337 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001338 assert((*bodyBuf == '{') && "bogus @catch body location");
1339
1340 buf += "1) { id _tmp = _caught;";
1341 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1342 buf.c_str(), buf.size());
1343 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek91034202008-10-06 22:39:38 +00001344 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001345 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001346 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001347 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001348 sawIdTypedCatch = true;
1349 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001350 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001351
Ted Kremenek42730c52008-01-07 19:49:32 +00001352 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001353 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001354 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001355 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001356 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001357 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001358 }
1359 }
1360 // Now rewrite the body...
1361 lastCatchBody = catchList->getCatchBody();
1362 SourceLocation rParenLoc = catchList->getRParenLoc();
1363 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1364 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1365 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1366 assert((*rParenBuf == ')') && "bogus @catch paren location");
1367 assert((*bodyBuf == '{') && "bogus @catch body location");
1368
1369 buf = " = _caught;";
1370 // Here we replace ") {" with "= _caught;" (which initializes and
1371 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001372 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001373 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001374 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001375 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001376 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001377 catchList = catchList->getNextCatchStmt();
1378 }
1379 // Complete the catch list...
1380 if (lastCatchBody) {
1381 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001382 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1383 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001384
Steve Naroff31325c12008-09-11 15:29:03 +00001385 // Insert the last (implicit) else clause *before* the right curly brace.
1386 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1387 buf = "} /* last catch end */\n";
1388 buf += "else {\n";
1389 buf += " _rethrow = _caught;\n";
1390 buf += " objc_exception_try_exit(&_stack);\n";
1391 buf += "} } /* @catch end */\n";
1392 if (!S->getFinallyStmt())
1393 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001394 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001395
1396 // Set lastCurlyLoc
1397 lastCurlyLoc = lastCatchBody->getLocEnd();
1398 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001399 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001400 startLoc = finalStmt->getLocStart();
1401 startBuf = SM->getCharacterData(startLoc);
1402 assert((*startBuf == '@') && "bogus @finally start");
1403
1404 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001405 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001406
1407 Stmt *body = finalStmt->getFinallyBody();
1408 SourceLocation startLoc = body->getLocStart();
1409 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001410 assert(*SM->getCharacterData(startLoc) == '{' &&
1411 "bogus @finally body location");
1412 assert(*SM->getCharacterData(endLoc) == '}' &&
1413 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001414
1415 startLoc = startLoc.getFileLocWithOffset(1);
1416 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001417 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001418 endLoc = endLoc.getFileLocWithOffset(-1);
1419 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001420 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001421
1422 // Set lastCurlyLoc
1423 lastCurlyLoc = body->getLocEnd();
Steve Naroff31325c12008-09-11 15:29:03 +00001424 } else { /* no finally clause - make sure we synthesize an implicit one */
1425 buf = "{ /* implicit finally clause */\n";
1426 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1427 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1428 buf += "}";
1429 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001430 }
1431 // Now emit the final closing curly brace...
1432 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1433 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001434 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001435 return 0;
1436}
1437
Steve Naroff44e81222008-04-14 22:03:09 +00001438Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001439 return 0;
1440}
1441
Steve Naroff44e81222008-04-14 22:03:09 +00001442Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001443 return 0;
1444}
1445
Chris Lattnerb1548372008-01-31 19:37:57 +00001446// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001447// the throw expression is typically a message expression that's already
1448// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001449Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001450 // Get the start location and compute the semi location.
1451 SourceLocation startLoc = S->getLocStart();
1452 const char *startBuf = SM->getCharacterData(startLoc);
1453
1454 assert((*startBuf == '@') && "bogus @throw location");
1455
1456 std::string buf;
1457 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001458 if (S->getThrowExpr())
1459 buf = "objc_exception_throw(";
1460 else // add an implicit argument
1461 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001462
1463 // handle "@ throw" correctly.
1464 const char *wBuf = strchr(startBuf, 'w');
1465 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1466 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1467
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001468 const char *semiBuf = strchr(startBuf, ';');
1469 assert((*semiBuf == ';') && "@throw: can't find ';'");
1470 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1471 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001472 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001473 return 0;
1474}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001475
Steve Naroff44e81222008-04-14 22:03:09 +00001476Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001477 // Create a new string expression.
1478 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001479 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001480 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001481 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1482 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001483 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001484 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001485
Chris Lattner4478db92007-11-30 22:53:43 +00001486 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001487 delete Exp;
1488 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001489}
1490
Steve Naroff44e81222008-04-14 22:03:09 +00001491Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff296b74f2007-11-05 14:50:49 +00001492 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1493 // Create a call to sel_registerName("selName").
1494 llvm::SmallVector<Expr*, 8> SelExprs;
1495 QualType argType = Context->getPointerType(Context->CharTy);
1496 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1497 Exp->getSelector().getName().size(),
1498 false, argType, SourceLocation(),
1499 SourceLocation()));
1500 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1501 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001502 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001503 delete Exp;
1504 return SelExp;
1505}
1506
Steve Naroff44e81222008-04-14 22:03:09 +00001507CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001508 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001509 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001510 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001511
1512 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001513 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001514
1515 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001516 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001517 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1518
1519 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001520
Steve Naroff71226032007-10-24 22:48:43 +00001521 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1522}
1523
Steve Naroffc8a92d12007-11-01 13:24:47 +00001524static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1525 const char *&startRef, const char *&endRef) {
1526 while (startBuf < endBuf) {
1527 if (*startBuf == '<')
1528 startRef = startBuf; // mark the start.
1529 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001530 if (startRef && *startRef == '<') {
1531 endRef = startBuf; // mark the end.
1532 return true;
1533 }
1534 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001535 }
1536 startBuf++;
1537 }
1538 return false;
1539}
1540
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001541static void scanToNextArgument(const char *&argRef) {
1542 int angle = 0;
1543 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1544 if (*argRef == '<')
1545 angle++;
1546 else if (*argRef == '>')
1547 angle--;
1548 argRef++;
1549 }
1550 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1551}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001552
Steve Naroff44e81222008-04-14 22:03:09 +00001553bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001554
Ted Kremenek42730c52008-01-07 19:49:32 +00001555 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001556 return true;
1557
Steve Naroffc8a92d12007-11-01 13:24:47 +00001558 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001559 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001560 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001561 return true; // we have "Class <Protocol> *".
1562 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001563 return false;
1564}
1565
Steve Naroffd06c88d2008-07-29 18:15:38 +00001566void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1567 QualType Type = E->getType();
1568 if (needToScanForQualifiers(Type)) {
1569 SourceLocation Loc = E->getLocStart();
1570 const char *startBuf = SM->getCharacterData(Loc);
1571 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1572 const char *startRef = 0, *endRef = 0;
1573 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1574 // Get the locations of the startRef, endRef.
1575 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1576 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1577 // Comment out the protocol references.
1578 InsertText(LessLoc, "/*", 2);
1579 InsertText(GreaterLoc, "*/", 2);
1580 }
1581 }
1582}
1583
Steve Naroff44e81222008-04-14 22:03:09 +00001584void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001585 SourceLocation Loc;
1586 QualType Type;
1587 const FunctionTypeProto *proto = 0;
1588 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1589 Loc = VD->getLocation();
1590 Type = VD->getType();
1591 }
1592 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1593 Loc = FD->getLocation();
1594 // Check for ObjC 'id' and class types that have been adorned with protocol
1595 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1596 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1597 assert(funcType && "missing function type");
1598 proto = dyn_cast<FunctionTypeProto>(funcType);
1599 if (!proto)
1600 return;
1601 Type = proto->getResultType();
1602 }
1603 else
1604 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001605
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001606 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001607 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001608
1609 const char *endBuf = SM->getCharacterData(Loc);
1610 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001611 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001612 startBuf--; // scan backward (from the decl location) for return type.
1613 const char *startRef = 0, *endRef = 0;
1614 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1615 // Get the locations of the startRef, endRef.
1616 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1617 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1618 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001619 InsertText(LessLoc, "/*", 2);
1620 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001621 }
1622 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001623 if (!proto)
1624 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001625 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001626 const char *startBuf = SM->getCharacterData(Loc);
1627 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001628 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1629 if (needToScanForQualifiers(proto->getArgType(i))) {
1630 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001631
Steve Naroffc8a92d12007-11-01 13:24:47 +00001632 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001633 // scan forward (from the decl location) for argument types.
1634 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001635 const char *startRef = 0, *endRef = 0;
1636 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1637 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001638 SourceLocation LessLoc =
1639 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1640 SourceLocation GreaterLoc =
1641 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001642 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001643 InsertText(LessLoc, "/*", 2);
1644 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001645 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001646 startBuf = ++endBuf;
1647 }
1648 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001649 // If the function name is derived from a macro expansion, then the
1650 // argument buffer will not follow the name. Need to speak with Chris.
1651 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001652 startBuf++; // scan forward (from the decl location) for argument types.
1653 startBuf++;
1654 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001655 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001656}
1657
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001658// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001659void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001660 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1661 llvm::SmallVector<QualType, 16> ArgTys;
1662 ArgTys.push_back(Context->getPointerType(
1663 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001664 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001665 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001666 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001667 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001668 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001669 SelGetUidIdent, getFuncType,
1670 FunctionDecl::Extern, false, 0);
1671}
1672
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001673// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001674void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001675 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1676 llvm::SmallVector<QualType, 16> ArgTys;
1677 ArgTys.push_back(Context->getPointerType(
1678 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001679 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001680 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001681 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001682 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001683 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001684 SelGetProtoIdent, getFuncType,
1685 FunctionDecl::Extern, false, 0);
1686}
1687
Steve Naroff44e81222008-04-14 22:03:09 +00001688void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001689 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001690 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001691 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001692 return;
1693 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001694 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001695}
1696
Steve Naroffbec4bf52008-03-11 17:37:02 +00001697// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001698void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001699 if (SuperContructorFunctionDecl)
1700 return;
1701 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1702 llvm::SmallVector<QualType, 16> ArgTys;
1703 QualType argT = Context->getObjCIdType();
1704 assert(!argT.isNull() && "Can't find 'id' type");
1705 ArgTys.push_back(argT);
1706 ArgTys.push_back(argT);
1707 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1708 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001709 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001710 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001711 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001712 msgSendIdent, msgSendType,
1713 FunctionDecl::Extern, false, 0);
1714}
1715
Steve Naroff02a82aa2007-10-30 23:14:51 +00001716// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001717void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001718 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1719 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001720 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001721 assert(!argT.isNull() && "Can't find 'id' type");
1722 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001723 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001724 assert(!argT.isNull() && "Can't find 'SEL' type");
1725 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001726 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001727 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001728 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001729 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001730 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001731 msgSendIdent, msgSendType,
1732 FunctionDecl::Extern, false, 0);
1733}
1734
Steve Naroff764c1ae2007-11-15 10:28:18 +00001735// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001736void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001737 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1738 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001739 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001740 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001741 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001742 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1743 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1744 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001745 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001746 assert(!argT.isNull() && "Can't find 'SEL' type");
1747 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001748 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001749 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001750 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001751 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001752 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001753 msgSendIdent, msgSendType,
1754 FunctionDecl::Extern, false, 0);
1755}
1756
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001757// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001758void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001759 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1760 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001761 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001762 assert(!argT.isNull() && "Can't find 'id' type");
1763 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001764 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001765 assert(!argT.isNull() && "Can't find 'SEL' type");
1766 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001767 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001768 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001769 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001770 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001771 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001772 msgSendIdent, msgSendType,
1773 FunctionDecl::Extern, false, 0);
1774}
1775
1776// SynthMsgSendSuperStretFunctionDecl -
1777// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001778void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001779 IdentifierInfo *msgSendIdent =
1780 &Context->Idents.get("objc_msgSendSuper_stret");
1781 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001782 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001783 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001784 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001785 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1786 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1787 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001788 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001789 assert(!argT.isNull() && "Can't find 'SEL' type");
1790 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001791 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001792 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001793 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001794 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00001795 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001796 msgSendIdent, msgSendType,
1797 FunctionDecl::Extern, false, 0);
1798}
1799
Steve Naroff31316a12008-05-08 22:02:18 +00001800// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001801void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001802 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1803 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001804 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001805 assert(!argT.isNull() && "Can't find 'id' type");
1806 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001808 assert(!argT.isNull() && "Can't find 'SEL' type");
1809 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00001810 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001811 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001812 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001813 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001814 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001815 msgSendIdent, msgSendType,
1816 FunctionDecl::Extern, false, 0);
1817}
1818
Steve Naroff02a82aa2007-10-30 23:14:51 +00001819// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001820void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001821 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1822 llvm::SmallVector<QualType, 16> ArgTys;
1823 ArgTys.push_back(Context->getPointerType(
1824 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001825 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001826 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001827 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001828 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001829 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001830 getClassIdent, getClassType,
1831 FunctionDecl::Extern, false, 0);
1832}
1833
Steve Naroff3b1caac2007-12-07 03:50:46 +00001834// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00001835void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001836 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1837 llvm::SmallVector<QualType, 16> ArgTys;
1838 ArgTys.push_back(Context->getPointerType(
1839 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001840 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001841 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001842 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001843 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001844 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001845 getClassIdent, getClassType,
1846 FunctionDecl::Extern, false, 0);
1847}
1848
Steve Naroff44e81222008-04-14 22:03:09 +00001849Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001850 QualType strType = getConstantStringStructType();
1851
1852 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00001853
1854 std::string tmpName = InFileName;
1855 unsigned i;
1856 for (i=0; i < tmpName.length(); i++) {
1857 char c = tmpName.at(i);
1858 // replace any non alphanumeric characters with '_'.
1859 if (!isalpha(c) && (c < '0' || c > '9'))
1860 tmpName[i] = '_';
1861 }
1862 S += tmpName;
1863 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001864 S += utostr(NumObjCStringLiterals++);
1865
Steve Narofffef037c2008-03-27 22:29:16 +00001866 Preamble += "static __NSConstantStringImpl " + S;
1867 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1868 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001869 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001870 std::string prettyBufS;
1871 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001872 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001873 Preamble += prettyBuf.str();
1874 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001875 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001876 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001877
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001878 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001879 &Context->Idents.get(S.c_str()), strType,
1880 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001881 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1882 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1883 Context->getPointerType(DRE->getType()),
1884 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001885 // cast to NSConstantString *
Douglas Gregor035d0882008-10-28 15:36:24 +00001886 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Douglas Gregor21a04f32008-10-27 19:41:14 +00001887 Exp->getType(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001888 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001889 delete Exp;
1890 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001891}
1892
Steve Naroff44e81222008-04-14 22:03:09 +00001893ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001894 // check if we are sending a message to 'super'
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001895 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00001896
Chris Lattner69909292008-08-10 01:53:14 +00001897 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
1898 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner4423d372008-06-21 18:04:54 +00001899 const PointerType *PT = PDE->getType()->getAsPointerType();
1900 assert(PT);
1901 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1902 return IT->getDecl();
1903 }
1904 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001905}
1906
1907// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00001908QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001909 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001910 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001911 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001912 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00001913 QualType FieldTypes[2];
1914
1915 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001916 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001917 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001918 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001919 // Create fields
1920 FieldDecl *FieldDecls[2];
1921
1922 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001923 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001924 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001925
Ted Kremenek46a837c2008-09-05 17:16:31 +00001926 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001927 }
1928 return Context->getTagDeclType(SuperStructDecl);
1929}
1930
Steve Naroff44e81222008-04-14 22:03:09 +00001931QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001932 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001933 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00001934 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001935 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00001936 QualType FieldTypes[4];
1937
1938 // struct objc_object *receiver;
1939 FieldTypes[0] = Context->getObjCIdType();
1940 // int flags;
1941 FieldTypes[1] = Context->IntTy;
1942 // char *str;
1943 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1944 // long length;
1945 FieldTypes[3] = Context->LongTy;
1946 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001947 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001948
1949 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001950 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001951 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001952
Ted Kremenek46a837c2008-09-05 17:16:31 +00001953 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001954 }
1955 return Context->getTagDeclType(ConstantStringDecl);
1956}
1957
Steve Naroff44e81222008-04-14 22:03:09 +00001958Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001959 if (!SelGetUidFunctionDecl)
1960 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001961 if (!MsgSendFunctionDecl)
1962 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001963 if (!MsgSendSuperFunctionDecl)
1964 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001965 if (!MsgSendStretFunctionDecl)
1966 SynthMsgSendStretFunctionDecl();
1967 if (!MsgSendSuperStretFunctionDecl)
1968 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001969 if (!MsgSendFpretFunctionDecl)
1970 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001971 if (!GetClassFunctionDecl)
1972 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001973 if (!GetMetaClassFunctionDecl)
1974 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001975
Steve Naroff764c1ae2007-11-15 10:28:18 +00001976 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001977 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1978 // May need to use objc_msgSend_stret() as well.
1979 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001980 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001981 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00001982 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001983 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00001984 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001985 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001986 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001987
Steve Naroff71226032007-10-24 22:48:43 +00001988 // Synthesize a call to objc_msgSend().
1989 llvm::SmallVector<Expr*, 8> MsgExprs;
1990 IdentifierInfo *clsName = Exp->getClassName();
1991
1992 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1993 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00001994 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
1995 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001996 if (!strcmp(clsName->getName(), "super")) {
1997 MsgSendFlavor = MsgSendSuperFunctionDecl;
1998 if (MsgSendStretFlavor)
1999 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2000 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2001
Ted Kremenek42730c52008-01-07 19:49:32 +00002002 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002003 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002004
2005 llvm::SmallVector<Expr*, 4> InitExprs;
2006
2007 // set the receiver to self, the first argument to all methods.
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002008 InitExprs.push_back(new DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002009 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002010 Context->getObjCIdType(),
2011 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002012 llvm::SmallVector<Expr*, 8> ClsExprs;
2013 QualType argType = Context->getPointerType(Context->CharTy);
2014 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2015 SuperDecl->getIdentifier()->getLength(),
2016 false, argType, SourceLocation(),
2017 SourceLocation()));
2018 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2019 &ClsExprs[0],
2020 ClsExprs.size());
2021 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002022 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002023 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002024 Cls, Context->getObjCIdType(),
2025 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002026 // struct objc_super
2027 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002028 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002029
Steve Naroffdee066b2008-03-11 18:14:26 +00002030 if (LangOpts.Microsoft) {
2031 SynthSuperContructorFunctionDecl();
2032 // Simulate a contructor call...
2033 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2034 superType, SourceLocation());
2035 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2036 superType, SourceLocation());
2037 } else {
2038 // (struct objc_super) { <exprs from above> }
2039 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2040 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002041 SourceLocation(), false);
2042 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2043 false);
Steve Naroffdee066b2008-03-11 18:14:26 +00002044 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002045 // struct objc_super *
2046 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2047 Context->getPointerType(SuperRep->getType()),
2048 SourceLocation());
2049 MsgExprs.push_back(Unop);
2050 } else {
2051 llvm::SmallVector<Expr*, 8> ClsExprs;
2052 QualType argType = Context->getPointerType(Context->CharTy);
2053 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2054 clsName->getLength(),
2055 false, argType, SourceLocation(),
2056 SourceLocation()));
2057 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2058 &ClsExprs[0],
2059 ClsExprs.size());
2060 MsgExprs.push_back(Cls);
2061 }
Steve Naroff885e2122007-11-14 23:54:14 +00002062 } else { // instance message.
2063 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002064
Ted Kremenek42730c52008-01-07 19:49:32 +00002065 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002066 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002067 if (MsgSendStretFlavor)
2068 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002069 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2070
2071 llvm::SmallVector<Expr*, 4> InitExprs;
2072
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002073 InitExprs.push_back(
Douglas Gregor035d0882008-10-28 15:36:24 +00002074 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002075 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002076 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002077 SourceLocation()),
2078 Context->getObjCIdType(),
Steve Naroff23528612008-07-16 22:35:27 +00002079 SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002080
2081 llvm::SmallVector<Expr*, 8> ClsExprs;
2082 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002083 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2084 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002085 false, argType, SourceLocation(),
2086 SourceLocation()));
2087 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002088 &ClsExprs[0],
2089 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002090 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002091 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002092 // set 'super class', using objc_getClass().
Douglas Gregor035d0882008-10-28 15:36:24 +00002093 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002094 Cls, Context->getObjCIdType(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002095 // struct objc_super
2096 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002097 Expr *SuperRep;
2098
2099 if (LangOpts.Microsoft) {
2100 SynthSuperContructorFunctionDecl();
2101 // Simulate a contructor call...
2102 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2103 superType, SourceLocation());
2104 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2105 superType, SourceLocation());
2106 } else {
2107 // (struct objc_super) { <exprs from above> }
2108 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2109 &InitExprs[0], InitExprs.size(),
Chris Lattner71ca8c82008-10-26 23:43:26 +00002110 SourceLocation(), false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002111 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2112 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002113 // struct objc_super *
2114 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2115 Context->getPointerType(SuperRep->getType()),
2116 SourceLocation());
2117 MsgExprs.push_back(Unop);
2118 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002119 // Remove all type-casts because it may contain objc-style types; e.g.
2120 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002121 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002122 recExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002123 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002124 Context->getObjCIdType(),
2125 SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002126 MsgExprs.push_back(recExpr);
2127 }
Steve Naroff885e2122007-11-14 23:54:14 +00002128 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002129 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002130 llvm::SmallVector<Expr*, 8> SelExprs;
2131 QualType argType = Context->getPointerType(Context->CharTy);
2132 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2133 Exp->getSelector().getName().size(),
2134 false, argType, SourceLocation(),
2135 SourceLocation()));
2136 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2137 &SelExprs[0], SelExprs.size());
2138 MsgExprs.push_back(SelExp);
2139
2140 // Now push any user supplied arguments.
2141 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002142 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002143 // Make all implicit casts explicit...ICE comes in handy:-)
2144 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2145 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002146 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002147 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002148 : ICE->getType();
Douglas Gregor035d0882008-10-28 15:36:24 +00002149 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002150 }
2151 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002152 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002153 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002154 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002155 userExpr = CE->getSubExpr();
Douglas Gregor035d0882008-10-28 15:36:24 +00002156 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002157 userExpr, Context->getObjCIdType(),
2158 SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002159 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002160 }
Steve Naroff885e2122007-11-14 23:54:14 +00002161 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002162 // We've transferred the ownership to MsgExprs. Null out the argument in
2163 // the original expression, since we will delete it below.
2164 Exp->setArg(i, 0);
2165 }
Steve Naroff0744c472007-11-04 22:37:50 +00002166 // Generate the funky cast.
2167 CastExpr *cast;
2168 llvm::SmallVector<QualType, 8> ArgTypes;
2169 QualType returnType;
2170
2171 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002172 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2173 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2174 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002175 ArgTypes.push_back(Context->getObjCIdType());
2176 ArgTypes.push_back(Context->getObjCSelType());
2177 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002178 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002179 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002180 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2181 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002182 : mDecl->getParamDecl(i)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002183 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2184 if (isBlockPointerType(t)) {
2185 const BlockPointerType *BPT = t->getAsBlockPointerType();
2186 t = Context->getPointerType(BPT->getPointeeType());
2187 }
Steve Naroff4242b972007-11-05 14:36:37 +00002188 ArgTypes.push_back(t);
2189 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002190 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2191 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002192 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002193 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002194 }
2195 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002196 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002197
2198 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002199 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2200 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002201
2202 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2203 // If we don't do this cast, we get the following bizarre warning/note:
2204 // xx.m:13: warning: function called through a non-compatible type
2205 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor035d0882008-10-28 15:36:24 +00002206 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002207 Context->getPointerType(Context->VoidTy),
2208 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002209
Steve Naroff0744c472007-11-04 22:37:50 +00002210 // Now do the "normal" pointer to function cast.
2211 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002212 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002213 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002214 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002215 castType = Context->getPointerType(castType);
Douglas Gregor035d0882008-10-28 15:36:24 +00002216 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002217
2218 // Don't forget the parens to enforce the proper binding.
2219 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2220
2221 const FunctionType *FT = msgSendType->getAsFunctionType();
2222 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2223 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002224 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002225 if (MsgSendStretFlavor) {
2226 // We have the method which returns a struct/union. Must also generate
2227 // call to objc_msgSend_stret and hang both varieties on a conditional
2228 // expression which dictate which one to envoke depending on size of
2229 // method's return type.
2230
2231 // Create a reference to the objc_msgSend_stret() declaration.
2232 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2233 SourceLocation());
2234 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor035d0882008-10-28 15:36:24 +00002235 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002236 Context->getPointerType(Context->VoidTy),
2237 SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002238 // Now do the "normal" pointer to function cast.
2239 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002240 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002241 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002242 castType = Context->getPointerType(castType);
Douglas Gregor035d0882008-10-28 15:36:24 +00002243 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002244
2245 // Don't forget the parens to enforce the proper binding.
2246 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2247
2248 FT = msgSendType->getAsFunctionType();
2249 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2250 FT->getResultType(), SourceLocation());
2251
2252 // Build sizeof(returnType)
2253 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2254 returnType, Context->getSizeType(),
2255 SourceLocation(), SourceLocation());
2256 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2257 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2258 // For X86 it is more complicated and some kind of target specific routine
2259 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002260 unsigned IntSize =
2261 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002262 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2263 Context->IntTy,
2264 SourceLocation());
2265 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2266 BinaryOperator::LE,
2267 Context->IntTy,
2268 SourceLocation());
2269 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2270 ConditionalOperator *CondExpr =
2271 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002272 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002273 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002274 return ReplacingStmt;
2275}
2276
Steve Naroff44e81222008-04-14 22:03:09 +00002277Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002278 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002279
Steve Naroff71226032007-10-24 22:48:43 +00002280 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002281 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002282
Chris Lattner0021f452007-10-24 16:57:36 +00002283 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002284 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002285}
2286
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002287/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2288/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002289Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002290 if (!GetProtocolFunctionDecl)
2291 SynthGetProtocolFunctionDecl();
2292 // Create a call to objc_getProtocol("ProtocolName").
2293 llvm::SmallVector<Expr*, 8> ProtoExprs;
2294 QualType argType = Context->getPointerType(Context->CharTy);
2295 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2296 strlen(Exp->getProtocol()->getName()),
2297 false, argType, SourceLocation(),
2298 SourceLocation()));
2299 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2300 &ProtoExprs[0],
2301 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002302 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002303 delete Exp;
2304 return ProtoExp;
2305
2306}
2307
Steve Naroffef82b742008-05-31 14:15:04 +00002308bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2309 const char *endBuf) {
2310 while (startBuf < endBuf) {
2311 if (*startBuf == '#') {
2312 // Skip whitespace.
2313 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2314 ;
2315 if (!strncmp(startBuf, "if", strlen("if")) ||
2316 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2317 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2318 !strncmp(startBuf, "define", strlen("define")) ||
2319 !strncmp(startBuf, "undef", strlen("undef")) ||
2320 !strncmp(startBuf, "else", strlen("else")) ||
2321 !strncmp(startBuf, "elif", strlen("elif")) ||
2322 !strncmp(startBuf, "endif", strlen("endif")) ||
2323 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2324 !strncmp(startBuf, "include", strlen("include")) ||
2325 !strncmp(startBuf, "import", strlen("import")) ||
2326 !strncmp(startBuf, "include_next", strlen("include_next")))
2327 return true;
2328 }
2329 startBuf++;
2330 }
2331 return false;
2332}
2333
Ted Kremenek42730c52008-01-07 19:49:32 +00002334/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002335/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002336void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002337 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002338 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2339 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002340 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002341 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002342 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002343 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002344 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002345 SourceLocation LocStart = CDecl->getLocStart();
2346 SourceLocation LocEnd = CDecl->getLocEnd();
2347
2348 const char *startBuf = SM->getCharacterData(LocStart);
2349 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002350
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002351 // If no ivars and no root or if its root, directly or indirectly,
2352 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002353 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2354 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002355 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002356 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002357 return;
2358 }
2359
2360 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002361 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002362 Result += "\nstruct ";
2363 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002364 if (LangOpts.Microsoft)
2365 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002366
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002367 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002368 const char *cursor = strchr(startBuf, '{');
2369 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002370 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002371 // If the buffer contains preprocessor directives, we do more fine-grained
2372 // rewrites. This is intended to fix code that looks like (which occurs in
2373 // NSURL.h, for example):
2374 //
2375 // #ifdef XYZ
2376 // @interface Foo : NSObject
2377 // #else
2378 // @interface FooBar : NSObject
2379 // #endif
2380 // {
2381 // int i;
2382 // }
2383 // @end
2384 //
2385 // This clause is segregated to avoid breaking the common case.
2386 if (BufferContainsPPDirectives(startBuf, cursor)) {
2387 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2388 CDecl->getClassLoc();
2389 const char *endHeader = SM->getCharacterData(L);
2390 endHeader += Lexer::MeasureTokenLength(L, *SM);
2391
Chris Lattner8bcb5252008-07-21 18:19:38 +00002392 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002393 // advance to the end of the referenced protocols.
2394 while (endHeader < cursor && *endHeader != '>') endHeader++;
2395 endHeader++;
2396 }
2397 // rewrite the original header
2398 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2399 } else {
2400 // rewrite the original header *without* disturbing the '{'
2401 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2402 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002403 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002404 Result = "\n struct ";
2405 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002406 Result += "_IMPL ";
2407 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002408 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002409
2410 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002411 SourceLocation OnePastCurly =
2412 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2413 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002414 }
2415 cursor++; // past '{'
2416
2417 // Now comment out any visibility specifiers.
2418 while (cursor < endBuf) {
2419 if (*cursor == '@') {
2420 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002421 // Skip whitespace.
2422 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2423 /*scan*/;
2424
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002425 // FIXME: presence of @public, etc. inside comment results in
2426 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002427 if (!strncmp(cursor, "public", strlen("public")) ||
2428 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002429 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002430 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002431 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002432 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002433 // FIXME: If there are cases where '<' is used in ivar declaration part
2434 // of user code, then scan the ivar list and use needToScanForQualifiers
2435 // for type checking.
2436 else if (*cursor == '<') {
2437 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002438 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002439 cursor = strchr(cursor, '>');
2440 cursor++;
2441 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002442 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002443 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002444 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002445 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002446 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002447 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002448 } else { // we don't have any instance variables - insert super struct.
2449 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2450 Result += " {\n struct ";
2451 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002452 Result += "_IMPL ";
2453 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002454 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002455 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002456 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002457 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002458 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002459 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002460}
2461
Ted Kremenek42730c52008-01-07 19:49:32 +00002462// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002463/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002464void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002465 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002466 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002467 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002468 const char *ClassName,
2469 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002470 if (MethodBegin == MethodEnd) return;
2471
Fariborz Jahanian04455192007-10-22 21:41:37 +00002472 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002473 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002474 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002475 SEL _cmd;
2476 char *method_types;
2477 void *_imp;
2478 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002479 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002480 Result += "\nstruct _objc_method {\n";
2481 Result += "\tSEL _cmd;\n";
2482 Result += "\tchar *method_types;\n";
2483 Result += "\tvoid *_imp;\n";
2484 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002485
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002486 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002487 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002488
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002489 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002490
2491 /* struct {
2492 struct _objc_method_list *next_method;
2493 int method_count;
2494 struct _objc_method method_list[];
2495 }
2496 */
2497 Result += "\nstatic struct {\n";
2498 Result += "\tstruct _objc_method_list *next_method;\n";
2499 Result += "\tint method_count;\n";
2500 Result += "\tstruct _objc_method method_list[";
2501 Result += utostr(MethodEnd-MethodBegin);
2502 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002503 Result += prefix;
2504 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2505 Result += "_METHODS_";
2506 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002507 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002508 Result += IsInstanceMethod ? "inst" : "cls";
2509 Result += "_meth\")))= ";
2510 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002511
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002512 Result += "\t,{{(SEL)\"";
2513 Result += (*MethodBegin)->getSelector().getName().c_str();
2514 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002515 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002516 Result += "\", \"";
2517 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002518 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002519 Result += MethodInternalNames[*MethodBegin];
2520 Result += "}\n";
2521 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2522 Result += "\t ,{(SEL)\"";
2523 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002524 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002525 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002526 Result += "\", \"";
2527 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002528 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002529 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002530 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002531 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002532 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002533}
2534
Ted Kremenek42730c52008-01-07 19:49:32 +00002535/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002536void RewriteObjC::
2537RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2538 const char *prefix,
2539 const char *ClassName,
2540 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002541 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002542 if (Protocols.empty()) return;
2543
2544 for (unsigned i = 0; i != Protocols.size(); i++) {
2545 ObjCProtocolDecl *PDecl = Protocols[i];
2546 // Output struct protocol_methods holder of method selector and type.
2547 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2548 /* struct protocol_methods {
2549 SEL _cmd;
2550 char *method_types;
2551 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002552 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002553 Result += "\nstruct protocol_methods {\n";
2554 Result += "\tSEL _cmd;\n";
2555 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002556 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002557
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002558 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002559 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002560 // Do not synthesize the protocol more than once.
2561 if (ObjCSynthesizedProtocols.count(PDecl))
2562 continue;
2563
2564 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2565 unsigned NumMethods = PDecl->getNumInstanceMethods();
2566 /* struct _objc_protocol_method_list {
2567 int protocol_method_count;
2568 struct protocol_methods protocols[];
2569 }
2570 */
2571 Result += "\nstatic struct {\n";
2572 Result += "\tint protocol_method_count;\n";
2573 Result += "\tstruct protocol_methods protocols[";
2574 Result += utostr(NumMethods);
2575 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2576 Result += PDecl->getName();
2577 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2578 "{\n\t" + utostr(NumMethods) + "\n";
2579
2580 // Output instance methods declared in this protocol.
2581 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2582 E = PDecl->instmeth_end(); I != E; ++I) {
2583 if (I == PDecl->instmeth_begin())
2584 Result += "\t ,{{(SEL)\"";
2585 else
2586 Result += "\t ,{(SEL)\"";
2587 Result += (*I)->getSelector().getName().c_str();
2588 std::string MethodTypeString;
2589 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2590 Result += "\", \"";
2591 Result += MethodTypeString;
2592 Result += "\"}\n";
2593 }
2594 Result += "\t }\n};\n";
2595 }
2596
2597 // Output class methods declared in this protocol.
2598 int NumMethods = PDecl->getNumClassMethods();
2599 if (NumMethods > 0) {
2600 /* struct _objc_protocol_method_list {
2601 int protocol_method_count;
2602 struct protocol_methods protocols[];
2603 }
2604 */
2605 Result += "\nstatic struct {\n";
2606 Result += "\tint protocol_method_count;\n";
2607 Result += "\tstruct protocol_methods protocols[";
2608 Result += utostr(NumMethods);
2609 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2610 Result += PDecl->getName();
2611 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2612 "{\n\t";
2613 Result += utostr(NumMethods);
2614 Result += "\n";
2615
2616 // Output instance methods declared in this protocol.
2617 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2618 E = PDecl->classmeth_end(); I != E; ++I) {
2619 if (I == PDecl->classmeth_begin())
2620 Result += "\t ,{{(SEL)\"";
2621 else
2622 Result += "\t ,{(SEL)\"";
2623 Result += (*I)->getSelector().getName().c_str();
2624 std::string MethodTypeString;
2625 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2626 Result += "\", \"";
2627 Result += MethodTypeString;
2628 Result += "\"}\n";
2629 }
2630 Result += "\t }\n};\n";
2631 }
2632
2633 // Output:
2634 /* struct _objc_protocol {
2635 // Objective-C 1.0 extensions
2636 struct _objc_protocol_extension *isa;
2637 char *protocol_name;
2638 struct _objc_protocol **protocol_list;
2639 struct _objc_protocol_method_list *instance_methods;
2640 struct _objc_protocol_method_list *class_methods;
2641 };
Steve Naroff27429432008-03-12 01:06:30 +00002642 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002643 static bool objc_protocol = false;
2644 if (!objc_protocol) {
2645 Result += "\nstruct _objc_protocol {\n";
2646 Result += "\tstruct _objc_protocol_extension *isa;\n";
2647 Result += "\tchar *protocol_name;\n";
2648 Result += "\tstruct _objc_protocol **protocol_list;\n";
2649 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2650 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2651 Result += "};\n";
2652
2653 objc_protocol = true;
2654 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002655
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002656 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2657 Result += PDecl->getName();
2658 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2659 "{\n\t0, \"";
2660 Result += PDecl->getName();
2661 Result += "\", 0, ";
2662 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2663 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2664 Result += PDecl->getName();
2665 Result += ", ";
2666 }
2667 else
2668 Result += "0, ";
2669 if (PDecl->getNumClassMethods() > 0) {
2670 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2671 Result += PDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002672 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002673 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002674 else
2675 Result += "0\n";
2676 Result += "};\n";
2677
2678 // Mark this protocol as having been generated.
2679 if (!ObjCSynthesizedProtocols.insert(PDecl))
2680 assert(false && "protocol already synthesized");
2681 }
2682 // Output the top lovel protocol meta-data for the class.
2683 /* struct _objc_protocol_list {
2684 struct _objc_protocol_list *next;
2685 int protocol_count;
2686 struct _objc_protocol *class_protocols[];
2687 }
2688 */
2689 Result += "\nstatic struct {\n";
2690 Result += "\tstruct _objc_protocol_list *next;\n";
2691 Result += "\tint protocol_count;\n";
2692 Result += "\tstruct _objc_protocol *class_protocols[";
2693 Result += utostr(Protocols.size());
2694 Result += "];\n} _OBJC_";
2695 Result += prefix;
2696 Result += "_PROTOCOLS_";
2697 Result += ClassName;
2698 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2699 "{\n\t0, ";
2700 Result += utostr(Protocols.size());
2701 Result += "\n";
2702
2703 Result += "\t,{&_OBJC_PROTOCOL_";
2704 Result += Protocols[0]->getName();
2705 Result += " \n";
2706
2707 for (unsigned i = 1; i != Protocols.size(); i++) {
2708 Result += "\t ,&_OBJC_PROTOCOL_";
2709 Result += Protocols[i]->getName();
2710 Result += "\n";
2711 }
2712 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002713}
2714
Ted Kremenek42730c52008-01-07 19:49:32 +00002715/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002716/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00002717void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002718 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002719 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002720 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002721 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002722 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2723 CDecl = CDecl->getNextClassCategory())
2724 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2725 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002726
Chris Lattnera661a4d2007-12-23 01:40:15 +00002727 std::string FullCategoryName = ClassDecl->getName();
2728 FullCategoryName += '_';
2729 FullCategoryName += IDecl->getName();
2730
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002731 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002732 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002733 true, "CATEGORY_", FullCategoryName.c_str(),
2734 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002735
2736 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002737 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002738 false, "CATEGORY_", FullCategoryName.c_str(),
2739 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002740
2741 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002742 // Null CDecl is case of a category implementation with no category interface
2743 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00002744 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002745 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002746
2747 /* struct _objc_category {
2748 char *category_name;
2749 char *class_name;
2750 struct _objc_method_list *instance_methods;
2751 struct _objc_method_list *class_methods;
2752 struct _objc_protocol_list *protocols;
2753 // Objective-C 1.0 extensions
2754 uint32_t size; // sizeof (struct _objc_category)
2755 struct _objc_property_list *instance_properties; // category's own
2756 // @property decl.
2757 };
2758 */
2759
2760 static bool objc_category = false;
2761 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002762 Result += "\nstruct _objc_category {\n";
2763 Result += "\tchar *category_name;\n";
2764 Result += "\tchar *class_name;\n";
2765 Result += "\tstruct _objc_method_list *instance_methods;\n";
2766 Result += "\tstruct _objc_method_list *class_methods;\n";
2767 Result += "\tstruct _objc_protocol_list *protocols;\n";
2768 Result += "\tunsigned int size;\n";
2769 Result += "\tstruct _objc_property_list *instance_properties;\n";
2770 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002771 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002772 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002773 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2774 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002775 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002776 Result += IDecl->getName();
2777 Result += "\"\n\t, \"";
2778 Result += ClassDecl->getName();
2779 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002780
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002781 if (IDecl->getNumInstanceMethods() > 0) {
2782 Result += "\t, (struct _objc_method_list *)"
2783 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2784 Result += FullCategoryName;
2785 Result += "\n";
2786 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002787 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002788 Result += "\t, 0\n";
2789 if (IDecl->getNumClassMethods() > 0) {
2790 Result += "\t, (struct _objc_method_list *)"
2791 "&_OBJC_CATEGORY_CLASS_METHODS_";
2792 Result += FullCategoryName;
2793 Result += "\n";
2794 }
2795 else
2796 Result += "\t, 0\n";
2797
Chris Lattner0be08822008-07-21 21:32:27 +00002798 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002799 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2800 Result += FullCategoryName;
2801 Result += "\n";
2802 }
2803 else
2804 Result += "\t, 0\n";
2805 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002806}
2807
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002808/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2809/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00002810void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00002811 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002812 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00002813 if (ivar->isBitField()) {
2814 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2815 // place all bitfields at offset 0.
2816 Result += "0";
2817 } else {
2818 Result += "__OFFSETOFIVAR__(struct ";
2819 Result += IDecl->getName();
2820 if (LangOpts.Microsoft)
2821 Result += "_IMPL";
2822 Result += ", ";
2823 Result += ivar->getName();
2824 Result += ")";
2825 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002826}
2827
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002828//===----------------------------------------------------------------------===//
2829// Meta Data Emission
2830//===----------------------------------------------------------------------===//
2831
Steve Naroff44e81222008-04-14 22:03:09 +00002832void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002833 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002834 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002835
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002836 // Explictly declared @interface's are already synthesized.
2837 if (CDecl->ImplicitInterfaceDecl()) {
2838 // FIXME: Implementation of a class with no @interface (legacy) doese not
2839 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002840 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002841 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002842
Chris Lattnerc7b06752007-12-12 07:56:42 +00002843 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002844 unsigned NumIvars = !IDecl->ivar_empty()
2845 ? IDecl->ivar_size()
2846 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002847 if (NumIvars > 0) {
2848 static bool objc_ivar = false;
2849 if (!objc_ivar) {
2850 /* struct _objc_ivar {
2851 char *ivar_name;
2852 char *ivar_type;
2853 int ivar_offset;
2854 };
2855 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002856 Result += "\nstruct _objc_ivar {\n";
2857 Result += "\tchar *ivar_name;\n";
2858 Result += "\tchar *ivar_type;\n";
2859 Result += "\tint ivar_offset;\n";
2860 Result += "};\n";
2861
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002862 objc_ivar = true;
2863 }
2864
Steve Naroffc723eec2008-03-11 00:12:29 +00002865 /* struct {
2866 int ivar_count;
2867 struct _objc_ivar ivar_list[nIvars];
2868 };
2869 */
2870 Result += "\nstatic struct {\n";
2871 Result += "\tint ivar_count;\n";
2872 Result += "\tstruct _objc_ivar ivar_list[";
2873 Result += utostr(NumIvars);
2874 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002875 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002876 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002877 "{\n\t";
2878 Result += utostr(NumIvars);
2879 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002880
Ted Kremenek42730c52008-01-07 19:49:32 +00002881 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002882 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002883 IVI = IDecl->ivar_begin();
2884 IVE = IDecl->ivar_end();
2885 } else {
2886 IVI = CDecl->ivar_begin();
2887 IVE = CDecl->ivar_end();
2888 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002889 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002890 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002891 Result += "\", \"";
2892 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002893 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002894 Result += StrEncoding;
2895 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002896 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002897 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002898 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002899 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002900 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002901 Result += "\", \"";
2902 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002903 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002904 Result += StrEncoding;
2905 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002906 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002907 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002908 }
2909
2910 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002911 }
2912
2913 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002914 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002915 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002916
2917 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002918 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002919 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002920
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002921 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00002922 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002923 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002924
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002925
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002926 // Declaration of class/meta-class metadata
2927 /* struct _objc_class {
2928 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002929 const char *super_class_name;
2930 char *name;
2931 long version;
2932 long info;
2933 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002934 struct _objc_ivar_list *ivars;
2935 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002936 struct objc_cache *cache;
2937 struct objc_protocol_list *protocols;
2938 const char *ivar_layout;
2939 struct _objc_class_ext *ext;
2940 };
2941 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002942 static bool objc_class = false;
2943 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002944 Result += "\nstruct _objc_class {\n";
2945 Result += "\tstruct _objc_class *isa;\n";
2946 Result += "\tconst char *super_class_name;\n";
2947 Result += "\tchar *name;\n";
2948 Result += "\tlong version;\n";
2949 Result += "\tlong info;\n";
2950 Result += "\tlong instance_size;\n";
2951 Result += "\tstruct _objc_ivar_list *ivars;\n";
2952 Result += "\tstruct _objc_method_list *methods;\n";
2953 Result += "\tstruct objc_cache *cache;\n";
2954 Result += "\tstruct _objc_protocol_list *protocols;\n";
2955 Result += "\tconst char *ivar_layout;\n";
2956 Result += "\tstruct _objc_class_ext *ext;\n";
2957 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002958 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002959 }
2960
2961 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002962 ObjCInterfaceDecl *RootClass = 0;
2963 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002964 while (SuperClass) {
2965 RootClass = SuperClass;
2966 SuperClass = SuperClass->getSuperClass();
2967 }
2968 SuperClass = CDecl->getSuperClass();
2969
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002970 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2971 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002972 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002973 "{\n\t(struct _objc_class *)\"";
2974 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2975 Result += "\"";
2976
2977 if (SuperClass) {
2978 Result += ", \"";
2979 Result += SuperClass->getName();
2980 Result += "\", \"";
2981 Result += CDecl->getName();
2982 Result += "\"";
2983 }
2984 else {
2985 Result += ", 0, \"";
2986 Result += CDecl->getName();
2987 Result += "\"";
2988 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002989 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002990 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002991 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002992 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002993 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002994 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002995 Result += "\n";
2996 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002997 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002998 Result += ", 0\n";
Chris Lattner8bcb5252008-07-21 18:19:38 +00002999 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003000 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003001 Result += CDecl->getName();
3002 Result += ",0,0\n";
3003 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003004 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003005 Result += "\t,0,0,0,0\n";
3006 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003007
3008 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003009 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3010 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003011 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003012 "{\n\t&_OBJC_METACLASS_";
3013 Result += CDecl->getName();
3014 if (SuperClass) {
3015 Result += ", \"";
3016 Result += SuperClass->getName();
3017 Result += "\", \"";
3018 Result += CDecl->getName();
3019 Result += "\"";
3020 }
3021 else {
3022 Result += ", 0, \"";
3023 Result += CDecl->getName();
3024 Result += "\"";
3025 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003026 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003027 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003028 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003029 Result += ",0";
3030 else {
3031 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003032 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003033 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003034 if (LangOpts.Microsoft)
3035 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003036 Result += ")";
3037 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003038 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003039 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003040 Result += CDecl->getName();
3041 Result += "\n\t";
3042 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003043 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003044 Result += ",0";
3045 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003046 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003047 Result += CDecl->getName();
3048 Result += ", 0\n\t";
3049 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003050 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003051 Result += ",0,0";
Chris Lattner8bcb5252008-07-21 18:19:38 +00003052 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff27429432008-03-12 01:06:30 +00003053 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003054 Result += CDecl->getName();
3055 Result += ", 0,0\n";
3056 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003057 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003058 Result += ",0,0,0\n";
3059 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003060}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003061
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003062/// RewriteImplementations - This routine rewrites all method implementations
3063/// and emits meta-data.
3064
Steve Naroff44e81222008-04-14 22:03:09 +00003065void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003066 int ClsDefCount = ClassImplementation.size();
3067 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003068
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003069 if (ClsDefCount == 0 && CatDefCount == 0)
3070 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003071 // Rewrite implemented methods
3072 for (int i = 0; i < ClsDefCount; i++)
3073 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003074
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003075 for (int i = 0; i < CatDefCount; i++)
3076 RewriteImplementationDecl(CategoryImplementation[i]);
3077
Steve Naroff5bf10222008-05-07 21:23:49 +00003078 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003079 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003080 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003081 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003082 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003083
3084 // For each implemented category, write out all its meta data.
3085 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003086 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003087
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003088 // Write objc_symtab metadata
3089 /*
3090 struct _objc_symtab
3091 {
3092 long sel_ref_cnt;
3093 SEL *refs;
3094 short cls_def_cnt;
3095 short cat_def_cnt;
3096 void *defs[cls_def_cnt + cat_def_cnt];
3097 };
3098 */
3099
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003100 Result += "\nstruct _objc_symtab {\n";
3101 Result += "\tlong sel_ref_cnt;\n";
3102 Result += "\tSEL *refs;\n";
3103 Result += "\tshort cls_def_cnt;\n";
3104 Result += "\tshort cat_def_cnt;\n";
3105 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3106 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003107
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003108 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003109 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003110 Result += "\t0, 0, " + utostr(ClsDefCount)
3111 + ", " + utostr(CatDefCount) + "\n";
3112 for (int i = 0; i < ClsDefCount; i++) {
3113 Result += "\t,&_OBJC_CLASS_";
3114 Result += ClassImplementation[i]->getName();
3115 Result += "\n";
3116 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003117
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003118 for (int i = 0; i < CatDefCount; i++) {
3119 Result += "\t,&_OBJC_CATEGORY_";
3120 Result += CategoryImplementation[i]->getClassInterface()->getName();
3121 Result += "_";
3122 Result += CategoryImplementation[i]->getName();
3123 Result += "\n";
3124 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003125
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003126 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003127
3128 // Write objc_module metadata
3129
3130 /*
3131 struct _objc_module {
3132 long version;
3133 long size;
3134 const char *name;
3135 struct _objc_symtab *symtab;
3136 }
3137 */
3138
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003139 Result += "\nstruct _objc_module {\n";
3140 Result += "\tlong version;\n";
3141 Result += "\tlong size;\n";
3142 Result += "\tconst char *name;\n";
3143 Result += "\tstruct _objc_symtab *symtab;\n";
3144 Result += "};\n\n";
3145 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003146 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003147 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3148 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003149 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003150
3151 if (LangOpts.Microsoft) {
3152 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003153 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003154 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3155 Result += "&_OBJC_MODULES;\n";
3156 Result += "#pragma data_seg(pop)\n\n";
3157 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003158}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003159
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003160std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3161 const char *funcName,
3162 std::string Tag) {
3163 const FunctionType *AFT = CE->getFunctionType();
3164 QualType RT = AFT->getResultType();
3165 std::string StructRef = "struct " + Tag;
3166 std::string S = "static " + RT.getAsString() + " __" +
3167 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003168
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003169 BlockDecl *BD = CE->getBlockDecl();
3170
3171 if (isa<FunctionTypeNoProto>(AFT)) {
3172 S += "()";
3173 } else if (BD->param_empty()) {
3174 S += "(" + StructRef + " *__cself)";
3175 } else {
3176 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3177 assert(FT && "SynthesizeBlockFunc: No function proto");
3178 S += '(';
3179 // first add the implicit argument.
3180 S += StructRef + " *__cself, ";
3181 std::string ParamStr;
3182 for (BlockDecl::param_iterator AI = BD->param_begin(),
3183 E = BD->param_end(); AI != E; ++AI) {
3184 if (AI != BD->param_begin()) S += ", ";
3185 ParamStr = (*AI)->getName();
3186 (*AI)->getType().getAsStringInternal(ParamStr);
3187 S += ParamStr;
3188 }
3189 if (FT->isVariadic()) {
3190 if (!BD->param_empty()) S += ", ";
3191 S += "...";
3192 }
3193 S += ')';
3194 }
3195 S += " {\n";
3196
3197 // Create local declarations to avoid rewriting all closure decl ref exprs.
3198 // First, emit a declaration for all "by ref" decls.
3199 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3200 E = BlockByRefDecls.end(); I != E; ++I) {
3201 S += " ";
3202 std::string Name = (*I)->getName();
3203 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3204 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3205 }
3206 // Next, emit a declaration for all "by copy" declarations.
3207 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3208 E = BlockByCopyDecls.end(); I != E; ++I) {
3209 S += " ";
3210 std::string Name = (*I)->getName();
3211 // Handle nested closure invocation. For example:
3212 //
3213 // void (^myImportedClosure)(void);
3214 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3215 //
3216 // void (^anotherClosure)(void);
3217 // anotherClosure = ^(void) {
3218 // myImportedClosure(); // import and invoke the closure
3219 // };
3220 //
3221 if (isBlockPointerType((*I)->getType()))
3222 S += "struct __block_impl *";
3223 else
3224 (*I)->getType().getAsStringInternal(Name);
3225 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3226 }
3227 std::string RewrittenStr = RewrittenBlockExprs[CE];
3228 const char *cstr = RewrittenStr.c_str();
3229 while (*cstr++ != '{') ;
3230 S += cstr;
3231 S += "\n";
3232 return S;
3233}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003234
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003235std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3236 const char *funcName,
3237 std::string Tag) {
3238 std::string StructRef = "struct " + Tag;
3239 std::string S = "static void __";
3240
3241 S += funcName;
3242 S += "_block_copy_" + utostr(i);
3243 S += "(" + StructRef;
3244 S += "*dst, " + StructRef;
3245 S += "*src) {";
3246 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3247 E = ImportedBlockDecls.end(); I != E; ++I) {
3248 S += "_Block_copy_assign(&dst->";
3249 S += (*I)->getName();
3250 S += ", src->";
3251 S += (*I)->getName();
3252 S += ");}";
3253 }
3254 S += "\nstatic void __";
3255 S += funcName;
3256 S += "_block_dispose_" + utostr(i);
3257 S += "(" + StructRef;
3258 S += "*src) {";
3259 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3260 E = ImportedBlockDecls.end(); I != E; ++I) {
3261 S += "_Block_destroy(src->";
3262 S += (*I)->getName();
3263 S += ");";
3264 }
3265 S += "}\n";
3266 return S;
3267}
3268
3269std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3270 bool hasCopyDisposeHelpers) {
3271 std::string S = "struct " + Tag;
3272 std::string Constructor = " " + Tag;
3273
3274 S += " {\n struct __block_impl impl;\n";
3275
3276 if (hasCopyDisposeHelpers)
3277 S += " void *copy;\n void *dispose;\n";
3278
3279 Constructor += "(void *fp";
3280
3281 if (hasCopyDisposeHelpers)
3282 Constructor += ", void *copyHelp, void *disposeHelp";
3283
3284 if (BlockDeclRefs.size()) {
3285 // Output all "by copy" declarations.
3286 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3287 E = BlockByCopyDecls.end(); I != E; ++I) {
3288 S += " ";
3289 std::string FieldName = (*I)->getName();
3290 std::string ArgName = "_" + FieldName;
3291 // Handle nested closure invocation. For example:
3292 //
3293 // void (^myImportedBlock)(void);
3294 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3295 //
3296 // void (^anotherBlock)(void);
3297 // anotherBlock = ^(void) {
3298 // myImportedBlock(); // import and invoke the closure
3299 // };
3300 //
3301 if (isBlockPointerType((*I)->getType())) {
3302 S += "struct __block_impl *";
3303 Constructor += ", void *" + ArgName;
3304 } else {
3305 (*I)->getType().getAsStringInternal(FieldName);
3306 (*I)->getType().getAsStringInternal(ArgName);
3307 Constructor += ", " + ArgName;
3308 }
3309 S += FieldName + ";\n";
3310 }
3311 // Output all "by ref" declarations.
3312 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3313 E = BlockByRefDecls.end(); I != E; ++I) {
3314 S += " ";
3315 std::string FieldName = (*I)->getName();
3316 std::string ArgName = "_" + FieldName;
3317 // Handle nested closure invocation. For example:
3318 //
3319 // void (^myImportedBlock)(void);
3320 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3321 //
3322 // void (^anotherBlock)(void);
3323 // anotherBlock = ^(void) {
3324 // myImportedBlock(); // import and invoke the closure
3325 // };
3326 //
3327 if (isBlockPointerType((*I)->getType())) {
3328 S += "struct __block_impl *";
3329 Constructor += ", void *" + ArgName;
3330 } else {
3331 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3332 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3333 Constructor += ", " + ArgName;
3334 }
3335 S += FieldName + "; // by ref\n";
3336 }
3337 // Finish writing the constructor.
3338 // FIXME: handle NSConcreteGlobalBlock.
3339 Constructor += ", int flags=0) {\n";
3340 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3341 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3342
3343 if (hasCopyDisposeHelpers)
3344 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3345
3346 // Initialize all "by copy" arguments.
3347 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3348 E = BlockByCopyDecls.end(); I != E; ++I) {
3349 std::string Name = (*I)->getName();
3350 Constructor += " ";
3351 if (isBlockPointerType((*I)->getType()))
3352 Constructor += Name + " = (struct __block_impl *)_";
3353 else
3354 Constructor += Name + " = _";
3355 Constructor += Name + ";\n";
3356 }
3357 // Initialize all "by ref" arguments.
3358 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3359 E = BlockByRefDecls.end(); I != E; ++I) {
3360 std::string Name = (*I)->getName();
3361 Constructor += " ";
3362 if (isBlockPointerType((*I)->getType()))
3363 Constructor += Name + " = (struct __block_impl *)_";
3364 else
3365 Constructor += Name + " = _";
3366 Constructor += Name + ";\n";
3367 }
3368 } else {
3369 // Finish writing the constructor.
3370 // FIXME: handle NSConcreteGlobalBlock.
3371 Constructor += ", int flags=0) {\n";
3372 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3373 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3374 if (hasCopyDisposeHelpers)
3375 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3376 }
3377 Constructor += " ";
3378 Constructor += "}\n";
3379 S += Constructor;
3380 S += "};\n";
3381 return S;
3382}
3383
3384void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3385 const char *FunName) {
3386 // Insert closures that were part of the function.
3387 for (unsigned i = 0; i < Blocks.size(); i++) {
3388
3389 CollectBlockDeclRefInfo(Blocks[i]);
3390
3391 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3392
3393 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3394 ImportedBlockDecls.size() > 0);
3395
3396 InsertText(FunLocStart, CI.c_str(), CI.size());
3397
3398 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3399
3400 InsertText(FunLocStart, CF.c_str(), CF.size());
3401
3402 if (ImportedBlockDecls.size()) {
3403 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3404 InsertText(FunLocStart, HF.c_str(), HF.size());
3405 }
3406
3407 BlockDeclRefs.clear();
3408 BlockByRefDecls.clear();
3409 BlockByCopyDecls.clear();
3410 BlockCallExprs.clear();
3411 ImportedBlockDecls.clear();
3412 }
3413 Blocks.clear();
3414 RewrittenBlockExprs.clear();
3415}
3416
3417void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3418 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3419 const char *FuncName = FD->getName();
3420
3421 SynthesizeBlockLiterals(FunLocStart, FuncName);
3422}
3423
3424void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3425 SourceLocation FunLocStart = MD->getLocStart();
3426 std::string FuncName = std::string(MD->getSelector().getName());
3427 // Convert colons to underscores.
3428 std::string::size_type loc = 0;
3429 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3430 FuncName.replace(loc, 1, "_");
3431
3432 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3433}
3434
3435void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3436 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3437 CI != E; ++CI)
3438 if (*CI) {
3439 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3440 GetBlockDeclRefExprs(CBE->getBody());
3441 else
3442 GetBlockDeclRefExprs(*CI);
3443 }
3444 // Handle specific things.
3445 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3446 // FIXME: Handle enums.
3447 if (!isa<FunctionDecl>(CDRE->getDecl()))
3448 BlockDeclRefs.push_back(CDRE);
3449 return;
3450}
3451
3452void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3454 CI != E; ++CI)
3455 if (*CI) {
3456 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3457 GetBlockCallExprs(CBE->getBody());
3458 else
3459 GetBlockCallExprs(*CI);
3460 }
3461
3462 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3463 if (CE->getCallee()->getType()->isBlockPointerType()) {
3464 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3465 }
3466 }
3467 return;
3468}
3469
3470std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3471 // Navigate to relevant type information.
3472 const char *closureName = 0;
3473 const BlockPointerType *CPT = 0;
3474
3475 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3476 closureName = DRE->getDecl()->getName();
3477 CPT = DRE->getType()->getAsBlockPointerType();
3478 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3479 closureName = CDRE->getDecl()->getName();
3480 CPT = CDRE->getType()->getAsBlockPointerType();
3481 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3482 closureName = MExpr->getMemberDecl()->getName();
3483 CPT = MExpr->getType()->getAsBlockPointerType();
3484 } else {
3485 assert(1 && "RewriteBlockClass: Bad type");
3486 }
3487 assert(CPT && "RewriteBlockClass: Bad type");
3488 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3489 assert(FT && "RewriteBlockClass: Bad type");
3490 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3491 // FTP will be null for closures that don't take arguments.
3492
3493 // Build a closure call - start with a paren expr to enforce precedence.
3494 std::string BlockCall = "(";
3495
3496 // Synthesize the cast.
3497 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3498 BlockCall += "(struct __block_impl *";
3499 if (FTP) {
3500 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3501 E = FTP->arg_type_end(); I && (I != E); ++I)
3502 BlockCall += ", " + (*I).getAsString();
3503 }
3504 BlockCall += "))"; // close the argument list and paren expression.
3505
3506 // Invoke the closure. We need to cast it since the declaration type is
3507 // bogus (it's a function pointer type)
3508 BlockCall += "((struct __block_impl *)";
3509 std::string closureExprBufStr;
3510 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3511 Exp->getCallee()->printPretty(closureExprBuf);
3512 BlockCall += closureExprBuf.str();
3513 BlockCall += ")->FuncPtr)";
3514
3515 // Add the arguments.
3516 BlockCall += "((struct __block_impl *)";
3517 BlockCall += closureExprBuf.str();
3518 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3519 E = Exp->arg_end(); I != E; ++I) {
3520 std::string syncExprBufS;
3521 llvm::raw_string_ostream Buf(syncExprBufS);
3522 (*I)->printPretty(Buf);
3523 BlockCall += ", " + Buf.str();
3524 }
3525 return BlockCall;
3526}
3527
3528void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3529 std::string BlockCall = SynthesizeBlockCall(Exp);
3530
3531 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3532 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3533
3534 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3535 BlockCall.c_str(), BlockCall.size());
3536}
3537
3538void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3539 // FIXME: Add more elaborate code generation required by the ABI.
3540 InsertText(BDRE->getLocStart(), "*", 1);
3541}
3542
3543void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3544 SourceLocation LocStart = CE->getLocStart();
3545 SourceLocation LocEnd = CE->getLocEnd();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003546
3547 // Need to avoid trying to rewrite synthesized casts.
3548 if (LocStart.isInvalid())
3549 return;
3550
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003551 const char *startBuf = SM->getCharacterData(LocStart);
3552 const char *endBuf = SM->getCharacterData(LocEnd);
3553
3554 // advance the location to startArgList.
3555 const char *argPtr = startBuf;
3556
3557 while (*argPtr++ && (argPtr < endBuf)) {
3558 switch (*argPtr) {
3559 case '^':
3560 // Replace the '^' with '*'.
3561 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3562 ReplaceText(LocStart, 1, "*", 1);
3563 break;
3564 }
3565 }
3566 return;
3567}
3568
3569void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3570 SourceLocation DeclLoc = FD->getLocation();
3571 unsigned parenCount = 0;
3572
3573 // We have 1 or more arguments that have closure pointers.
3574 const char *startBuf = SM->getCharacterData(DeclLoc);
3575 const char *startArgList = strchr(startBuf, '(');
3576
3577 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3578
3579 parenCount++;
3580 // advance the location to startArgList.
3581 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3582 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3583
3584 const char *argPtr = startArgList;
3585
3586 while (*argPtr++ && parenCount) {
3587 switch (*argPtr) {
3588 case '^':
3589 // Replace the '^' with '*'.
3590 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3591 ReplaceText(DeclLoc, 1, "*", 1);
3592 break;
3593 case '(':
3594 parenCount++;
3595 break;
3596 case ')':
3597 parenCount--;
3598 break;
3599 }
3600 }
3601 return;
3602}
3603
3604bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3605 const FunctionTypeProto *FTP;
3606 const PointerType *PT = QT->getAsPointerType();
3607 if (PT) {
3608 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3609 } else {
3610 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3611 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3612 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3613 }
3614 if (FTP) {
3615 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3616 E = FTP->arg_type_end(); I != E; ++I)
3617 if (isBlockPointerType(*I))
3618 return true;
3619 }
3620 return false;
3621}
3622
3623void RewriteObjC::GetExtentOfArgList(const char *Name,
3624 const char *&LParen, const char *&RParen) {
3625 const char *argPtr = strchr(Name, '(');
3626 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3627
3628 LParen = argPtr; // output the start.
3629 argPtr++; // skip past the left paren.
3630 unsigned parenCount = 1;
3631
3632 while (*argPtr && parenCount) {
3633 switch (*argPtr) {
3634 case '(': parenCount++; break;
3635 case ')': parenCount--; break;
3636 default: break;
3637 }
3638 if (parenCount) argPtr++;
3639 }
3640 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3641 RParen = argPtr; // output the end
3642}
3643
3644void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3646 RewriteBlockPointerFunctionArgs(FD);
3647 return;
3648 }
3649 // Handle Variables and Typedefs.
3650 SourceLocation DeclLoc = ND->getLocation();
3651 QualType DeclT;
3652 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3653 DeclT = VD->getType();
3654 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3655 DeclT = TDD->getUnderlyingType();
3656 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3657 DeclT = FD->getType();
3658 else
3659 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3660
3661 const char *startBuf = SM->getCharacterData(DeclLoc);
3662 const char *endBuf = startBuf;
3663 // scan backward (from the decl location) for the end of the previous decl.
3664 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3665 startBuf--;
3666
3667 // *startBuf != '^' if we are dealing with a pointer to function that
3668 // may take block argument types (which will be handled below).
3669 if (*startBuf == '^') {
3670 // Replace the '^' with '*', computing a negative offset.
3671 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3672 ReplaceText(DeclLoc, 1, "*", 1);
3673 }
3674 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3675 // Replace the '^' with '*' for arguments.
3676 DeclLoc = ND->getLocation();
3677 startBuf = SM->getCharacterData(DeclLoc);
3678 const char *argListBegin, *argListEnd;
3679 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3680 while (argListBegin < argListEnd) {
3681 if (*argListBegin == '^') {
3682 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3683 ReplaceText(CaretLoc, 1, "*", 1);
3684 }
3685 argListBegin++;
3686 }
3687 }
3688 return;
3689}
3690
3691void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3692 // Add initializers for any closure decl refs.
3693 GetBlockDeclRefExprs(Exp->getBody());
3694 if (BlockDeclRefs.size()) {
3695 // Unique all "by copy" declarations.
3696 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3697 if (!BlockDeclRefs[i]->isByRef())
3698 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3699 // Unique all "by ref" declarations.
3700 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3701 if (BlockDeclRefs[i]->isByRef()) {
3702 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3703 }
3704 // Find any imported blocks...they will need special attention.
3705 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3706 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
3707 GetBlockCallExprs(Blocks[i]);
3708 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3709 }
3710 }
3711}
3712
3713std::string RewriteObjC::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
3714 Blocks.push_back(Exp);
3715
3716 CollectBlockDeclRefInfo(Exp);
3717 std::string FuncName;
3718
3719 if (CurFunctionDef)
3720 FuncName = std::string(CurFunctionDef->getName());
3721 else if (CurMethodDef) {
3722 FuncName = std::string(CurMethodDef->getSelector().getName());
3723 // Convert colons to underscores.
3724 std::string::size_type loc = 0;
3725 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3726 FuncName.replace(loc, 1, "_");
3727 } else if (VD)
3728 FuncName = std::string(VD->getName());
3729
3730 std::string BlockNumber = utostr(Blocks.size()-1);
3731
3732 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3733 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3734
3735 std::string FunkTypeStr;
3736
3737 // Get a pointer to the function type so we can cast appropriately.
3738 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
3739
3740 // Rewrite the closure block with a compound literal. The first cast is
3741 // to prevent warnings from the C compiler.
3742 std::string Init = "(" + FunkTypeStr;
3743
3744 Init += ")&" + Tag;
3745
3746 // Initialize the block function.
3747 Init += "((void*)" + Func;
3748
3749 if (ImportedBlockDecls.size()) {
3750 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
3751 Init += ",(void*)" + Buf;
3752 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
3753 Init += ",(void*)" + Buf;
3754 }
3755 // Add initializers for any closure decl refs.
3756 if (BlockDeclRefs.size()) {
3757 // Output all "by copy" declarations.
3758 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3759 E = BlockByCopyDecls.end(); I != E; ++I) {
3760 Init += ",";
3761 if (isObjCType((*I)->getType())) {
3762 Init += "[[";
3763 Init += (*I)->getName();
3764 Init += " retain] autorelease]";
3765 } else if (isBlockPointerType((*I)->getType())) {
3766 Init += "(void *)";
3767 Init += (*I)->getName();
3768 } else {
3769 Init += (*I)->getName();
3770 }
3771 }
3772 // Output all "by ref" declarations.
3773 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3774 E = BlockByRefDecls.end(); I != E; ++I) {
3775 Init += ",&";
3776 Init += (*I)->getName();
3777 }
3778 }
3779 Init += ")";
3780 BlockDeclRefs.clear();
3781 BlockByRefDecls.clear();
3782 BlockByCopyDecls.clear();
3783 ImportedBlockDecls.clear();
3784
3785 return Init;
3786}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003787
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003788FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3789 IdentifierInfo *ID = &Context->Idents.get(name);
3790 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3791 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3792 ID, FType, FunctionDecl::Extern, false, 0);
3793}
3794
3795Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
3796 Blocks.push_back(Exp);
3797
3798 CollectBlockDeclRefInfo(Exp);
3799 std::string FuncName;
3800
3801 if (CurFunctionDef)
3802 FuncName = std::string(CurFunctionDef->getName());
3803 else if (CurMethodDef) {
3804 FuncName = std::string(CurMethodDef->getSelector().getName());
3805 // Convert colons to underscores.
3806 std::string::size_type loc = 0;
3807 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3808 FuncName.replace(loc, 1, "_");
3809 } else if (VD)
3810 FuncName = std::string(VD->getName());
3811
3812 std::string BlockNumber = utostr(Blocks.size()-1);
3813
3814 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3815 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3816
3817 // Get a pointer to the function type so we can cast appropriately.
3818 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3819
3820 FunctionDecl *FD;
3821 Expr *NewRep;
3822
3823 // Simulate a contructor call...
3824 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3825 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3826
3827 llvm::SmallVector<Expr*, 4> InitExprs;
3828
3829 FD = SynthBlockInitFunctionDecl(Func.c_str());
3830 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3831 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
3832 Context->VoidPtrTy, SourceLocation());
3833 InitExprs.push_back(castExpr);
3834#if 0
3835 // Initialize the block function.
3836 Init += "((void*)" + Func;
3837
3838 if (ImportedBlockDecls.size()) {
3839 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
3840 Init += ",(void*)" + Buf;
3841 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
3842 Init += ",(void*)" + Buf;
3843 }
3844 // Add initializers for any closure decl refs.
3845 if (BlockDeclRefs.size()) {
3846 // Output all "by copy" declarations.
3847 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3848 E = BlockByCopyDecls.end(); I != E; ++I) {
3849 Init += ",";
3850 if (isObjCType((*I)->getType())) {
3851 Init += "[[";
3852 Init += (*I)->getName();
3853 Init += " retain] autorelease]";
3854 } else if (isBlockPointerType((*I)->getType())) {
3855 Init += "(void *)";
3856 Init += (*I)->getName();
3857 } else {
3858 Init += (*I)->getName();
3859 }
3860 }
3861 // Output all "by ref" declarations.
3862 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3863 E = BlockByRefDecls.end(); I != E; ++I) {
3864 Init += ",&";
3865 Init += (*I)->getName();
3866 }
3867 }
3868 Init += ")";
3869#endif
3870 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3871 FType, SourceLocation());
3872 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3873 Context->getPointerType(NewRep->getType()),
3874 SourceLocation());
3875 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation());
3876 BlockDeclRefs.clear();
3877 BlockByRefDecls.clear();
3878 BlockByCopyDecls.clear();
3879 ImportedBlockDecls.clear();
3880 return NewRep;
3881}
3882
3883//===----------------------------------------------------------------------===//
3884// Function Body / Expression rewriting
3885//===----------------------------------------------------------------------===//
3886
3887Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3888 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3889 isa<DoStmt>(S) || isa<ForStmt>(S))
3890 Stmts.push_back(S);
3891 else if (isa<ObjCForCollectionStmt>(S)) {
3892 Stmts.push_back(S);
3893 ObjCBcLabelNo.push_back(++BcLabelCount);
3894 }
3895
3896 SourceRange OrigStmtRange = S->getSourceRange();
3897
3898 // Perform a bottom up rewrite of all children.
3899 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3900 CI != E; ++CI)
3901 if (*CI) {
3902 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3903 if (newStmt)
3904 *CI = newStmt;
3905 }
3906
3907 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3908 // Rewrite the block body in place.
3909 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3910
3911 // Now we snarf the rewritten text and stash it away for later use.
3912 std::string S = Rewrite.getRewritenText(BE->getSourceRange());
3913 RewrittenBlockExprs[BE] = S;
3914
3915 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3916 //blockTranscribed->dump();
3917 return blockTranscribed;
3918 }
3919 // Handle specific things.
3920 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3921 return RewriteAtEncode(AtEncode);
3922
3923 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3924 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3925
3926 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3927 return RewriteAtSelector(AtSelector);
3928
3929 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3930 return RewriteObjCStringLiteral(AtString);
3931
3932 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3933 // Before we rewrite it, put the original message expression in a comment.
3934 SourceLocation startLoc = MessExpr->getLocStart();
3935 SourceLocation endLoc = MessExpr->getLocEnd();
3936
3937 const char *startBuf = SM->getCharacterData(startLoc);
3938 const char *endBuf = SM->getCharacterData(endLoc);
3939
3940 std::string messString;
3941 messString += "// ";
3942 messString.append(startBuf, endBuf-startBuf+1);
3943 messString += "\n";
3944
3945 // FIXME: Missing definition of
3946 // InsertText(clang::SourceLocation, char const*, unsigned int).
3947 // InsertText(startLoc, messString.c_str(), messString.size());
3948 // Tried this, but it didn't work either...
3949 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3950 return RewriteMessageExpr(MessExpr);
3951 }
3952
3953 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3954 return RewriteObjCTryStmt(StmtTry);
3955
3956 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3957 return RewriteObjCSynchronizedStmt(StmtTry);
3958
3959 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3960 return RewriteObjCThrowStmt(StmtThrow);
3961
3962 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3963 return RewriteObjCProtocolExpr(ProtocolExp);
3964
3965 if (ObjCForCollectionStmt *StmtForCollection =
3966 dyn_cast<ObjCForCollectionStmt>(S))
3967 return RewriteObjCForCollectionStmt(StmtForCollection,
3968 OrigStmtRange.getEnd());
3969 if (BreakStmt *StmtBreakStmt =
3970 dyn_cast<BreakStmt>(S))
3971 return RewriteBreakStmt(StmtBreakStmt);
3972 if (ContinueStmt *StmtContinueStmt =
3973 dyn_cast<ContinueStmt>(S))
3974 return RewriteContinueStmt(StmtContinueStmt);
3975
3976 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3977 // and cast exprs.
3978 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3979 // FIXME: What we're doing here is modifying the type-specifier that
3980 // precedes the first Decl. In the future the DeclGroup should have
3981 // a separate type-specifier that we can rewrite.
3982 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3983
3984 // Blocks rewrite rules.
3985 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3986 DI != DE; ++DI) {
3987
3988 ScopedDecl *SD = *DI;
3989 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3990 if (isBlockPointerType(ND->getType()))
3991 RewriteBlockPointerDecl(ND);
3992 else if (ND->getType()->isFunctionPointerType())
3993 CheckFunctionPointerDecl(ND->getType(), ND);
3994 }
3995 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3996 if (isBlockPointerType(TD->getUnderlyingType()))
3997 RewriteBlockPointerDecl(TD);
3998 else if (TD->getUnderlyingType()->isFunctionPointerType())
3999 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4000 }
4001 }
4002 }
4003
4004 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4005 RewriteObjCQualifiedInterfaceTypes(CE);
4006
4007 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4008 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4009 assert(!Stmts.empty() && "Statement stack is empty");
4010 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4011 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4012 && "Statement stack mismatch");
4013 Stmts.pop_back();
4014 }
4015 // Handle blocks rewriting.
4016 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4017 if (BDRE->isByRef())
4018 RewriteBlockDeclRefExpr(BDRE);
4019 }
4020 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4021 if (CE->getCallee()->getType()->isBlockPointerType())
4022 RewriteBlockCall(CE);
4023 }
4024 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
4025 RewriteCastExpr(CE);
4026 }
4027#if 0
4028 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4029 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4030 // Get the new text.
4031 std::string SStr;
4032 llvm::raw_string_ostream Buf(SStr);
4033 Replacement->printPretty(Buf);
4034 const std::string &Str = Buf.str();
4035
4036 printf("CAST = %s\n", &Str[0]);
4037 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4038 delete S;
4039 return Replacement;
4040 }
4041#endif
4042 // Return this stmt unmodified.
4043 return S;
4044}
4045
4046/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4047/// main file of the input.
4048void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4049 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4050 // Since function prototypes don't have ParmDecl's, we check the function
4051 // prototype. This enables us to rewrite function declarations and
4052 // definitions using the same code.
4053 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4054
4055 if (Stmt *Body = FD->getBody()) {
4056 CurFunctionDef = FD;
4057 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4058 // This synthesizes and inserts the block "impl" struct, invoke function,
4059 // and any copy/dispose helper functions.
4060 InsertBlockLiteralsWithinFunction(FD);
4061 CurFunctionDef = 0;
4062 }
4063 return;
4064 }
4065 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4066 if (Stmt *Body = MD->getBody()) {
4067 //Body->dump();
4068 CurMethodDef = MD;
4069 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4070 InsertBlockLiteralsWithinMethod(MD);
4071 CurMethodDef = 0;
4072 }
4073 }
4074 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4075 ClassImplementation.push_back(CI);
4076 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4077 CategoryImplementation.push_back(CI);
4078 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4079 RewriteForwardClassDecl(CD);
4080 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4081 RewriteObjCQualifiedInterfaceTypes(VD);
4082 if (VD->getInit())
4083 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4084 }
4085 // Rewrite rules for blocks.
4086 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4087 if (isBlockPointerType(VD->getType())) {
4088 RewriteBlockPointerDecl(VD);
4089 if (VD->getInit()) {
4090 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
4091 RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
4092
4093 // We've just rewritten the block body in place.
4094 // Now we snarf the rewritten text and stash it away for later use.
4095 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
4096 RewrittenBlockExprs[CBE] = S;
4097 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
4098 // Do the rewrite, using S.size() which contains the rewritten size.
4099 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
4100 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4101 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
4102 RewriteCastExpr(CE);
4103 }
4104 }
4105 } else if (VD->getType()->isFunctionPointerType()) {
4106 CheckFunctionPointerDecl(VD->getType(), VD);
4107 if (VD->getInit()) {
4108 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
4109 RewriteCastExpr(CE);
4110 }
4111 }
4112 }
4113 return;
4114 }
4115 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4116 if (isBlockPointerType(TD->getUnderlyingType()))
4117 RewriteBlockPointerDecl(TD);
4118 else if (TD->getUnderlyingType()->isFunctionPointerType())
4119 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4120 return;
4121 }
4122 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4123 if (RD->isDefinition()) {
4124 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4125 e = RD->field_end(); i != e; ++i) {
4126 FieldDecl *FD = *i;
4127 if (isBlockPointerType(FD->getType()))
4128 RewriteBlockPointerDecl(FD);
4129 }
4130 }
4131 return;
4132 }
4133 // Nothing yet.
4134}
4135
4136void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4137 // Get the top-level buffer that this corresponds to.
4138
4139 // Rewrite tabs if we care.
4140 //RewriteTabs();
4141
4142 if (Diags.hasErrorOccurred())
4143 return;
4144
4145 // Create the output file.
4146
4147 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4148 llvm::raw_ostream *OutFile;
4149 if (OutFileName == "-") {
4150 OutFile = &llvm::outs();
4151 } else if (!OutFileName.empty()) {
4152 std::string Err;
4153 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
4154 OwnedStream.reset(OutFile);
4155 } else if (InFileName == "-") {
4156 OutFile = &llvm::outs();
4157 } else {
4158 llvm::sys::Path Path(InFileName);
4159 Path.eraseSuffix();
4160 Path.appendSuffix("cpp");
4161 std::string Err;
4162 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
4163 OwnedStream.reset(OutFile);
4164 }
4165
4166 RewriteInclude();
4167
4168 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4169 Preamble.c_str(), Preamble.size(), false);
4170
4171 // Rewrite Objective-c meta data*
4172 std::string ResultStr;
4173 RewriteImplementations(ResultStr);
4174
4175 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4176 // we are done.
4177 if (const RewriteBuffer *RewriteBuf =
4178 Rewrite.getRewriteBufferFor(MainFileID)) {
4179 //printf("Changed:\n");
4180 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4181 } else {
4182 fprintf(stderr, "No changes\n");
4183 }
4184 // Emit metadata.
4185 *OutFile << ResultStr;
4186 OutFile->flush();
4187}
4188