blob: ce1a741b50f3b4f6c1cef30178fc24d58a474bd6 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-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 Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-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 Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-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 Jahanian545b9ae2007-10-18 19:23:00 +0000109 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000110 public:
Ted Kremeneke3a61982008-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 Lattner9e13c2e2008-01-31 19:38:44 +0000117
Chris Lattner8a12c272007-10-11 18:38:32 +0000118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 // Top Level Driver code.
120 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000121 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000122 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000123 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000124
125 ~RewriteObjC() {}
126
127 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000128
129 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000130 // If replacement succeeded or warning disabled return with no warning.
131 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000132 return;
133
Chris Lattnerdcbc5b02008-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 Naroffba92b2e2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Chris Lattneraadaf782008-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 Lattnerf04da132007-10-24 17:06:59 +0000156
Chris Lattneraadaf782008-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 Lattnerf04da132007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
172 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000173 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-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 Lattner55d13b42008-03-16 21:23:50 +0000179 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000182 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000183 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000185 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000186 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000187 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000190 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000191 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000192 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000193 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000194 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000195 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000196 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000198 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
200 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
201 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000202 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
203 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000204 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
205 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000206 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000207 Stmt *RewriteBreakStmt(BreakStmt *S);
208 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000209 void SynthCountByEnumWithState(std::string &buf);
210
Steve Naroff09b266e2007-10-30 23:14:51 +0000211 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000212 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000213 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000214 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000215 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000216 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000217 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000218 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000219 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000220 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000224 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
230 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000231 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000232 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000233 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000234 const char *ClassName,
235 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236
Chris Lattner780f3292008-07-21 21:32:27 +0000237 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
238 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000239 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000240 const char *ClassName,
241 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000242 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000243 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
245 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000246 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000247 void RewriteImplementations(std::string &Result);
Steve Naroff54055232008-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);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000303 };
304}
305
Steve Naroff54055232008-10-27 17:20:55 +0000306void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
307 NamedDecl *D) {
308 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
309 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
310 E = fproto->arg_type_end(); I && (I != E); ++I)
311 if (isBlockPointerType(*I)) {
312 // All the args are checked/rewritten. Don't call twice!
313 RewriteBlockPointerDecl(D);
314 break;
315 }
316 }
317}
318
319void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
320 const PointerType *PT = funcType->getAsPointerType();
321 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
322 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
323}
324
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000325static bool IsHeaderFile(const std::string &Filename) {
326 std::string::size_type DotPos = Filename.rfind('.');
327
328 if (DotPos == std::string::npos) {
329 // no file extension
330 return false;
331 }
332
333 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
334 // C header: .h
335 // C++ header: .hh or .H;
336 return Ext == "h" || Ext == "hh" || Ext == "H";
337}
338
Steve Naroffb29b4272008-04-14 22:03:09 +0000339RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000340 Diagnostic &D, const LangOptions &LOpts)
341 : Diags(D), LangOpts(LOpts) {
342 IsHeader = IsHeaderFile(inFile);
343 InFileName = inFile;
344 OutFileName = outFile;
345 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
346 "rewriting sub-expression within a macro (may not be correct)");
347}
348
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000349ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000350 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000351 Diagnostic &Diags,
352 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000353 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000354}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000355
Steve Naroffb29b4272008-04-14 22:03:09 +0000356void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000357 Context = &context;
358 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000359 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 MsgSendFunctionDecl = 0;
361 MsgSendSuperFunctionDecl = 0;
362 MsgSendStretFunctionDecl = 0;
363 MsgSendSuperStretFunctionDecl = 0;
364 MsgSendFpretFunctionDecl = 0;
365 GetClassFunctionDecl = 0;
366 GetMetaClassFunctionDecl = 0;
367 SelGetUidFunctionDecl = 0;
368 CFStringFunctionDecl = 0;
369 GetProtocolFunctionDecl = 0;
370 ConstantStringClassReference = 0;
371 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000372 CurMethodDef = 0;
373 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000375 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000376 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000377 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000378 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379
380 // Get the ID and start/end of the main file.
381 MainFileID = SM->getMainFileID();
382 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
383 MainFileStart = MainBuf->getBufferStart();
384 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000385
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000386 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000387
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 // declaring objc_selector outside the parameter list removes a silly
389 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000390 if (IsHeader)
391 Preamble = "#pragma once\n";
392 Preamble += "struct objc_selector; struct objc_class;\n";
393 Preamble += "#ifndef OBJC_SUPER\n";
394 Preamble += "struct objc_super { struct objc_object *object; ";
395 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000396 if (LangOpts.Microsoft) {
397 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000398 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
399 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000400 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "};\n";
402 Preamble += "#define OBJC_SUPER\n";
403 Preamble += "#endif\n";
404 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
405 Preamble += "typedef struct objc_object Protocol;\n";
406 Preamble += "#define _REWRITER_typedef_Protocol\n";
407 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000408 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000409 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
410 else
411 Preamble += "#define __OBJC_RW_EXTERN extern\n";
412 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000413 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000420 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000422 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
427 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
428 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
429 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000431 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000432 // @synchronized hooks.
433 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
434 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000435 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000436 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
437 Preamble += "struct __objcFastEnumerationState {\n\t";
438 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000439 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000440 Preamble += "unsigned long *mutationsPtr;\n\t";
441 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000442 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "#define __FASTENUMERATIONSTATE\n";
444 Preamble += "#endif\n";
445 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
446 Preamble += "struct __NSConstantStringImpl {\n";
447 Preamble += " int *isa;\n";
448 Preamble += " int flags;\n";
449 Preamble += " char *str;\n";
450 Preamble += " long length;\n";
451 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000452 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
453 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
454 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000455 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000456 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
458 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000459 if (LangOpts.Microsoft) {
460 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000461 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000462 }
Steve Naroff54055232008-10-27 17:20:55 +0000463 // Blocks preamble.
464 Preamble += "#ifndef BLOCK_IMPL\n";
465 Preamble += "#define BLOCK_IMPL\n";
466 Preamble += "struct __block_impl {\n";
467 Preamble += " void *isa;\n";
468 Preamble += " int Flags;\n";
469 Preamble += " int Size;\n";
470 Preamble += " void *FuncPtr;\n";
471 Preamble += "};\n";
472 Preamble += "enum {\n";
473 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
474 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
475 Preamble += "};\n";
476 if (LangOpts.Microsoft)
477 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
478 else
479 Preamble += "#define __OBJC_RW_EXTERN extern\n";
480 Preamble += "// Runtime copy/destroy helper functions\n";
481 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
482 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
483 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
484 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
485 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
486 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
487 Preamble += "#endif\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000488}
489
490
Chris Lattnerf04da132007-10-24 17:06:59 +0000491//===----------------------------------------------------------------------===//
492// Top Level Driver Code
493//===----------------------------------------------------------------------===//
494
Steve Naroffb29b4272008-04-14 22:03:09 +0000495void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000496 // Two cases: either the decl could be in the main file, or it could be in a
497 // #included file. If the former, rewrite it now. If the later, check to see
498 // if we rewrote the #include/#import.
499 SourceLocation Loc = D->getLocation();
500 Loc = SM->getLogicalLoc(Loc);
501
502 // If this is for a builtin, ignore it.
503 if (Loc.isInvalid()) return;
504
Steve Naroffebf2b562007-10-23 23:50:29 +0000505 // Look for built-in declarations that we need to refer during the rewrite.
506 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000507 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000508 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000509 // declared in <Foundation/NSString.h>
510 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
511 ConstantStringClassReference = FVD;
512 return;
513 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000515 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000517 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000518 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000519 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000520 } else if (ObjCForwardProtocolDecl *FP =
521 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000522 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000523 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000524 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000525 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000527}
528
Chris Lattnerf04da132007-10-24 17:06:59 +0000529/// HandleDeclInMainFile - This is called for each top-level decl defined in the
530/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000531void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Steve Naroff54055232008-10-27 17:20:55 +0000532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
533 // Since function prototypes don't have ParmDecl's, we check the function
534 // prototype. This enables us to rewrite function declarations and
535 // definitions using the same code.
536 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
537
538 if (Stmt *Body = FD->getBody()) {
539 CurFunctionDef = FD;
Steve Narofff3473a72007-11-09 15:20:18 +0000540 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000541 // This synthesizes and inserts the block "impl" struct, invoke function,
542 // and any copy/dispose helper functions.
543 InsertBlockLiteralsWithinFunction(FD);
544 CurFunctionDef = 0;
545 }
546 return;
547 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000549 if (Stmt *Body = MD->getBody()) {
550 //Body->dump();
Steve Naroff54055232008-10-27 17:20:55 +0000551 CurMethodDef = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000552 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000553 InsertBlockLiteralsWithinMethod(MD);
554 CurMethodDef = 0;
Steve Naroff874e2322007-11-15 10:28:18 +0000555 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000556 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000557 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000558 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000559 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000561 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000562 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000563 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000564 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000565 if (VD->getInit())
566 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
567 }
Steve Naroff54055232008-10-27 17:20:55 +0000568 // Rewrite rules for blocks.
569 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
570 if (isBlockPointerType(VD->getType())) {
571 RewriteBlockPointerDecl(VD);
572 if (VD->getInit()) {
573 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
574 RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
575
576 // We've just rewritten the block body in place.
577 // Now we snarf the rewritten text and stash it away for later use.
578 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
579 RewrittenBlockExprs[CBE] = S;
580 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
581 // Do the rewrite, using S.size() which contains the rewritten size.
582 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
583 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
584 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
585 RewriteCastExpr(CE);
586 }
587 }
588 } else if (VD->getType()->isFunctionPointerType()) {
589 CheckFunctionPointerDecl(VD->getType(), VD);
590 if (VD->getInit()) {
591 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
592 RewriteCastExpr(CE);
593 }
594 }
595 }
596 return;
597 }
598 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
599 if (isBlockPointerType(TD->getUnderlyingType()))
600 RewriteBlockPointerDecl(TD);
601 else if (TD->getUnderlyingType()->isFunctionPointerType())
602 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
603 return;
604 }
605 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
606 if (RD->isDefinition()) {
607 for (RecordDecl::field_const_iterator i = RD->field_begin(),
608 e = RD->field_end(); i != e; ++i) {
609 FieldDecl *FD = *i;
610 if (isBlockPointerType(FD->getType()))
611 RewriteBlockPointerDecl(FD);
612 }
613 }
614 return;
615 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000616 // Nothing yet.
617}
618
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000619void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000620 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000621
622 // Rewrite tabs if we care.
623 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000624
Steve Naroffa7b402d2008-03-28 22:26:09 +0000625 if (Diags.hasErrorOccurred())
626 return;
627
628 // Create the output file.
629
Ted Kremeneka95d3752008-09-13 05:16:45 +0000630 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
631 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000632 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000633 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000634 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000635 std::string Err;
636 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
637 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000638 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000639 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000640 } else {
641 llvm::sys::Path Path(InFileName);
642 Path.eraseSuffix();
643 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000644 std::string Err;
645 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
646 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000647 }
648
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000649 RewriteInclude();
650
Steve Naroffba92b2e2008-03-27 22:29:16 +0000651 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
652 Preamble.c_str(), Preamble.size(), false);
653
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000654 // Rewrite Objective-c meta data*
655 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000656 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000657
Chris Lattnerf04da132007-10-24 17:06:59 +0000658 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
659 // we are done.
660 if (const RewriteBuffer *RewriteBuf =
661 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000662 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000663 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000664 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000665 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000666 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000667 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000668 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000669 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000670}
671
Chris Lattnerf04da132007-10-24 17:06:59 +0000672//===----------------------------------------------------------------------===//
673// Syntactic (non-AST) Rewriting Code
674//===----------------------------------------------------------------------===//
675
Steve Naroffb29b4272008-04-14 22:03:09 +0000676void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000677 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
678 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
679 const char *MainBufStart = MainBuf.first;
680 const char *MainBufEnd = MainBuf.second;
681 size_t ImportLen = strlen("import");
682 size_t IncludeLen = strlen("include");
683
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000684 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000685 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
686 if (*BufPtr == '#') {
687 if (++BufPtr == MainBufEnd)
688 return;
689 while (*BufPtr == ' ' || *BufPtr == '\t')
690 if (++BufPtr == MainBufEnd)
691 return;
692 if (!strncmp(BufPtr, "import", ImportLen)) {
693 // replace import with include
694 SourceLocation ImportLoc =
695 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000696 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000697 BufPtr += ImportLen;
698 }
699 }
700 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000701}
702
Steve Naroffb29b4272008-04-14 22:03:09 +0000703void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000704 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
705 const char *MainBufStart = MainBuf.first;
706 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000707
Chris Lattnerf04da132007-10-24 17:06:59 +0000708 // Loop over the whole file, looking for tabs.
709 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
710 if (*BufPtr != '\t')
711 continue;
712
713 // Okay, we found a tab. This tab will turn into at least one character,
714 // but it depends on which 'virtual column' it is in. Compute that now.
715 unsigned VCol = 0;
716 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
717 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
718 ++VCol;
719
720 // Okay, now that we know the virtual column, we know how many spaces to
721 // insert. We assume 8-character tab-stops.
722 unsigned Spaces = 8-(VCol & 7);
723
724 // Get the location of the tab.
725 SourceLocation TabLoc =
726 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
727
728 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000729 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000730 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000731}
732
733
Steve Naroffb29b4272008-04-14 22:03:09 +0000734void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000735 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000737
738 // Get the start location and compute the semi location.
739 SourceLocation startLoc = ClassDecl->getLocation();
740 const char *startBuf = SM->getCharacterData(startLoc);
741 const char *semiPtr = strchr(startBuf, ';');
742
743 // Translate to typedef's that forward reference structs with the same name
744 // as the class. As a convenience, we include the original declaration
745 // as a comment.
746 std::string typedefString;
747 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000748 typedefString.append(startBuf, semiPtr-startBuf+1);
749 typedefString += "\n";
750 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "#ifndef _REWRITER_typedef_";
753 typedefString += ForwardDecl->getName();
754 typedefString += "\n";
755 typedefString += "#define _REWRITER_typedef_";
756 typedefString += ForwardDecl->getName();
757 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000758 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000759 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000760 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000761 }
762
763 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(startLoc, semiPtr-startBuf+1,
765 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000766}
767
Steve Naroffb29b4272008-04-14 22:03:09 +0000768void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000769 SourceLocation LocStart = Method->getLocStart();
770 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000771
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000772 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000773 InsertText(LocStart, "#if 0\n", 6);
774 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000775 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000776 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000777 }
778}
779
Steve Naroffb29b4272008-04-14 22:03:09 +0000780void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000781{
Chris Lattner55d13b42008-03-16 21:23:50 +0000782 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000784 SourceLocation Loc = Property->getLocation();
785
Chris Lattneraadaf782008-01-31 19:51:04 +0000786 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000787
788 // FIXME: handle properties that are declared across multiple lines.
789 }
790}
791
Steve Naroffb29b4272008-04-14 22:03:09 +0000792void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000793 SourceLocation LocStart = CatDecl->getLocStart();
794
795 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000796 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000797
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000798 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000799 E = CatDecl->instmeth_end(); I != E; ++I)
800 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000802 E = CatDecl->classmeth_end(); I != E; ++I)
803 RewriteMethodDeclaration(*I);
804
Steve Naroff423cb562007-10-30 13:30:57 +0000805 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000806 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000807}
808
Steve Naroffb29b4272008-04-14 22:03:09 +0000809void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812 SourceLocation LocStart = PDecl->getLocStart();
813
814 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000816
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000817 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000818 E = PDecl->instmeth_end(); I != E; ++I)
819 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000821 E = PDecl->classmeth_end(); I != E; ++I)
822 RewriteMethodDeclaration(*I);
823
Steve Naroff752d6ef2007-10-30 16:42:30 +0000824 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000825 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000826 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000827
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000828 // Must comment out @optional/@required
829 const char *startBuf = SM->getCharacterData(LocStart);
830 const char *endBuf = SM->getCharacterData(LocEnd);
831 for (const char *p = startBuf; p < endBuf; p++) {
832 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
833 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000834 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000835 ReplaceText(OptionalLoc, strlen("@optional"),
836 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000837
838 }
839 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
840 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000841 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000842 ReplaceText(OptionalLoc, strlen("@required"),
843 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000844
845 }
846 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000847}
848
Steve Naroffb29b4272008-04-14 22:03:09 +0000849void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000851 if (LocStart.isInvalid())
852 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000853 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000854 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000855}
856
Steve Naroffb29b4272008-04-14 22:03:09 +0000857void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000860 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000861 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000862 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000863 else if (OMD->getResultType()->isFunctionPointerType()) {
864 // needs special handling, since pointer-to-functions have special
865 // syntax (where a decaration models use).
866 QualType retType = OMD->getResultType();
867 if (const PointerType* PT = retType->getAsPointerType()) {
868 QualType PointeeTy = PT->getPointeeType();
869 if ((FPRetType = PointeeTy->getAsFunctionType())) {
870 ResultStr += FPRetType->getResultType().getAsString();
871 ResultStr += "(*";
872 }
873 }
874 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000875 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000876 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000877
878 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000879 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000881 if (OMD->isInstance())
882 NameStr += "_I_";
883 else
884 NameStr += "_C_";
885
886 NameStr += OMD->getClassInterface()->getName();
887 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888
889 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000890 if (ObjCCategoryImplDecl *CID =
891 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000892 NameStr += CID->getName();
893 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 }
Steve Naroff563b8282008-04-04 22:23:44 +0000895 // Append selector names, replacing ':' with '_'
896 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000897 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 else {
899 std::string selString = OMD->getSelector().getName();
900 int len = selString.size();
901 for (int i = 0; i < len; i++)
902 if (selString[i] == ':')
903 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 // Remember this name for metadata emission
907 MethodInternalNames[OMD] = NameStr;
908 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000909
910 // Rewrite arguments
911 ResultStr += "(";
912
913 // invisible arguments
914 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000916 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000917 if (!LangOpts.Microsoft) {
918 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
919 ResultStr += "struct ";
920 }
921 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000922 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000923 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000924 }
925 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000926 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927
928 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000929 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ResultStr += " _cmd";
931
932 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000933 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ParmVarDecl *PDecl = OMD->getParamDecl(i);
935 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000936 if (PDecl->getType()->isObjCQualifiedIdType()) {
937 ResultStr += "id ";
938 ResultStr += PDecl->getName();
939 } else {
940 std::string Name = PDecl->getName();
941 PDecl->getType().getAsStringInternal(Name);
942 ResultStr += Name;
943 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000945 if (OMD->isVariadic())
946 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000947 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948
Steve Naroff76e429d2008-07-16 14:40:40 +0000949 if (FPRetType) {
950 ResultStr += ")"; // close the precedence "scope" for "*".
951
952 // Now, emit the argument types (if any).
953 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
954 ResultStr += "(";
955 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
956 if (i) ResultStr += ", ";
957 std::string ParamStr = FT->getArgType(i).getAsString();
958 ResultStr += ParamStr;
959 }
960 if (FT->isVariadic()) {
961 if (FT->getNumArgs()) ResultStr += ", ";
962 ResultStr += "...";
963 }
964 ResultStr += ")";
965 } else {
966 ResultStr += "()";
967 }
968 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969}
Steve Naroffb29b4272008-04-14 22:03:09 +0000970void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000971 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
972 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000973
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000974 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000975 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000976 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000977 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000980 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
981 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000983 ObjCMethodDecl *OMD = *I;
984 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 SourceLocation LocStart = OMD->getLocStart();
986 SourceLocation LocEnd = OMD->getBody()->getLocStart();
987
988 const char *startBuf = SM->getCharacterData(LocStart);
989 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000990 ReplaceText(LocStart, endBuf-startBuf,
991 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 }
993
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000995 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
996 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ObjCMethodDecl *OMD = *I;
999 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001000 SourceLocation LocStart = OMD->getLocStart();
1001 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1002
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001005 ReplaceText(LocStart, endBuf-startBuf,
1006 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001008 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001009 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001010 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001011 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001012}
1013
Steve Naroffb29b4272008-04-14 22:03:09 +00001014void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001015 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001016 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001017 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001018 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +00001019 ResultStr += ClassDecl->getName();
1020 ResultStr += "\n";
1021 ResultStr += "#define _REWRITER_typedef_";
1022 ResultStr += ClassDecl->getName();
1023 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001024 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001025 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +00001026 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001027 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001028 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001029 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001031
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001032 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1033 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001034 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001035 E = ClassDecl->instmeth_end(); I != E; ++I)
1036 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001037 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001038 E = ClassDecl->classmeth_end(); I != E; ++I)
1039 RewriteMethodDeclaration(*I);
1040
Steve Naroff2feac5e2007-10-30 03:43:13 +00001041 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001042 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001043}
1044
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001045Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1046 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001048 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001049 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001050 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1051 // lookup which class implements the instance variable.
1052 ObjCInterfaceDecl *clsDeclared = 0;
1053 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1054 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1055
1056 // Synthesize an explicit cast to gain access to the ivar.
1057 std::string RecName = clsDeclared->getIdentifier()->getName();
1058 RecName += "_IMPL";
1059 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001060 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001061 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001062 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1063 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001064 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
1065 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001066 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001067 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1068 IV->getBase()->getLocEnd(),
1069 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001070 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001071 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001072 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1073 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001074 ReplaceStmt(IV, ME);
1075 delete IV;
1076 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001077 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001078
1079 ReplaceStmt(IV->getBase(), PE);
1080 // Cannot delete IV->getBase(), since PE points to it.
1081 // Replace the old base with the cast. This is important when doing
1082 // embedded rewrites. For example, [newInv->_container addObject:0].
1083 IV->setBase(PE);
1084 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001085 }
Steve Naroff84472a82008-04-18 21:55:08 +00001086 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001087 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1088
1089 // Explicit ivar refs need to have a cast inserted.
1090 // FIXME: consider sharing some of this code with the code above.
1091 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001092 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001093 // lookup which class implements the instance variable.
1094 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001095 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001096 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1097
1098 // Synthesize an explicit cast to gain access to the ivar.
1099 std::string RecName = clsDeclared->getIdentifier()->getName();
1100 RecName += "_IMPL";
1101 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001102 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001103 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001104 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1105 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001106 CastExpr *castExpr = new ExplicitCastExpr(castT, IV->getBase(),
1107 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001108 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001109 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1110 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001111 ReplaceStmt(IV->getBase(), PE);
1112 // Cannot delete IV->getBase(), since PE points to it.
1113 // Replace the old base with the cast. This is important when doing
1114 // embedded rewrites. For example, [newInv->_container addObject:0].
1115 IV->setBase(PE);
1116 return IV;
1117 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001118 }
Steve Naroff84472a82008-04-18 21:55:08 +00001119 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001120}
1121
Chris Lattnerf04da132007-10-24 17:06:59 +00001122//===----------------------------------------------------------------------===//
1123// Function Body / Expression rewriting
1124//===----------------------------------------------------------------------===//
1125
Steve Naroffb29b4272008-04-14 22:03:09 +00001126Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001127 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1128 isa<DoStmt>(S) || isa<ForStmt>(S))
1129 Stmts.push_back(S);
1130 else if (isa<ObjCForCollectionStmt>(S)) {
1131 Stmts.push_back(S);
1132 ObjCBcLabelNo.push_back(++BcLabelCount);
1133 }
1134
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001135 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +00001136
1137 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +00001138 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1139 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +00001140 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +00001141 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +00001142 if (newStmt)
1143 *CI = newStmt;
1144 }
Steve Naroffebf2b562007-10-23 23:50:29 +00001145
1146 // Handle specific things.
1147 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
1148 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001149
1150 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001151 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +00001152
1153 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
1154 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +00001155
Steve Naroffbeaf2992007-11-03 11:27:19 +00001156 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
1157 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +00001158
Steve Naroff934f2762007-10-24 22:48:43 +00001159 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
1160 // Before we rewrite it, put the original message expression in a comment.
1161 SourceLocation startLoc = MessExpr->getLocStart();
1162 SourceLocation endLoc = MessExpr->getLocEnd();
1163
1164 const char *startBuf = SM->getCharacterData(startLoc);
1165 const char *endBuf = SM->getCharacterData(endLoc);
1166
1167 std::string messString;
1168 messString += "// ";
1169 messString.append(startBuf, endBuf-startBuf+1);
1170 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +00001171
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001172 // FIXME: Missing definition of
1173 // InsertText(clang::SourceLocation, char const*, unsigned int).
1174 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001175 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001176 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001177 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001178 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001179
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001180 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1181 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001182
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001183 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1184 return RewriteObjCSynchronizedStmt(StmtTry);
1185
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001186 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1187 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001188
1189 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1190 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001191
1192 if (ObjCForCollectionStmt *StmtForCollection =
1193 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001194 return RewriteObjCForCollectionStmt(StmtForCollection,
1195 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001196 if (BreakStmt *StmtBreakStmt =
1197 dyn_cast<BreakStmt>(S))
1198 return RewriteBreakStmt(StmtBreakStmt);
1199 if (ContinueStmt *StmtContinueStmt =
1200 dyn_cast<ContinueStmt>(S))
1201 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001202
Ted Kremenekab9bae72008-10-06 22:45:07 +00001203 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1204 // and cast exprs.
1205 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1206 // FIXME: What we're doing here is modifying the type-specifier that
1207 // precedes the first Decl. In the future the DeclGroup should have
1208 // a separate type-specifier that we can rewrite.
1209 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Steve Naroff54055232008-10-27 17:20:55 +00001210
1211 // Blocks rewrite rules.
1212 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1213 DI != DE; ++DI) {
1214
1215 ScopedDecl *SD = *DI;
1216 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1217 if (isBlockPointerType(ND->getType()))
1218 RewriteBlockPointerDecl(ND);
1219 else if (ND->getType()->isFunctionPointerType())
1220 CheckFunctionPointerDecl(ND->getType(), ND);
1221 }
1222 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1223 if (isBlockPointerType(TD->getUnderlyingType()))
1224 RewriteBlockPointerDecl(TD);
1225 else if (TD->getUnderlyingType()->isFunctionPointerType())
1226 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
1227 }
1228 }
Ted Kremenekab9bae72008-10-06 22:45:07 +00001229 }
1230
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001231 if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001232 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001233
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001234 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1235 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1236 assert(!Stmts.empty() && "Statement stack is empty");
1237 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1238 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1239 && "Statement stack mismatch");
1240 Stmts.pop_back();
1241 }
Steve Naroff54055232008-10-27 17:20:55 +00001242 // Handle blocks rewriting.
1243 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1244 if (BDRE->isByRef())
1245 RewriteBlockDeclRefExpr(BDRE);
1246 }
1247 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1248 if (CE->getCallee()->getType()->isBlockPointerType())
1249 RewriteBlockCall(CE);
1250 }
1251 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1252 RewriteCastExpr(CE);
1253 }
Steve Naroff874e2322007-11-15 10:28:18 +00001254#if 0
1255 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1256 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1257 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001258 std::string SStr;
1259 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001260 Replacement->printPretty(Buf);
1261 const std::string &Str = Buf.str();
1262
1263 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001264 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001265 delete S;
1266 return Replacement;
1267 }
1268#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001269 // Return this stmt unmodified.
1270 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001271}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001272
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273/// SynthCountByEnumWithState - To print:
1274/// ((unsigned int (*)
1275/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1276/// (void *)objc_msgSend)((id)l_collection,
1277/// sel_registerName(
1278/// "countByEnumeratingWithState:objects:count:"),
1279/// &enumState,
1280/// (id *)items, (unsigned int)16)
1281///
Steve Naroffb29b4272008-04-14 22:03:09 +00001282void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001283 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1284 "id *, unsigned int))(void *)objc_msgSend)";
1285 buf += "\n\t\t";
1286 buf += "((id)l_collection,\n\t\t";
1287 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1288 buf += "\n\t\t";
1289 buf += "&enumState, "
1290 "(id *)items, (unsigned int)16)";
1291}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001292
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001293/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1294/// statement to exit to its outer synthesized loop.
1295///
Steve Naroffb29b4272008-04-14 22:03:09 +00001296Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001297 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1298 return S;
1299 // replace break with goto __break_label
1300 std::string buf;
1301
1302 SourceLocation startLoc = S->getLocStart();
1303 buf = "goto __break_label_";
1304 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001305 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001306
1307 return 0;
1308}
1309
1310/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1311/// statement to continue with its inner synthesized loop.
1312///
Steve Naroffb29b4272008-04-14 22:03:09 +00001313Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1315 return S;
1316 // replace continue with goto __continue_label
1317 std::string buf;
1318
1319 SourceLocation startLoc = S->getLocStart();
1320 buf = "goto __continue_label_";
1321 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001322 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001323
1324 return 0;
1325}
1326
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001327/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001328/// It rewrites:
1329/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001330
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001331/// Into:
1332/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001333/// type elem;
1334/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001335/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336/// id l_collection = (id)collection;
1337/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1338/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001339/// if (limit) {
1340/// unsigned long startMutations = *enumState.mutationsPtr;
1341/// do {
1342/// unsigned long counter = 0;
1343/// do {
1344/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001345/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001346/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001347/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001348/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001350/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1351/// objects:items count:16]);
1352/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001353/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001354/// }
1355/// else
1356/// elem = nil;
1357/// }
1358///
Steve Naroffb29b4272008-04-14 22:03:09 +00001359Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001360 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001361 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1362 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1363 "ObjCForCollectionStmt Statement stack mismatch");
1364 assert(!ObjCBcLabelNo.empty() &&
1365 "ObjCForCollectionStmt - Label No stack empty");
1366
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001367 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001370 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001371 std::string buf;
1372 buf = "\n{\n\t";
1373 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1374 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001375 ScopedDecl* D = DS->getSolitaryDecl();
1376 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001377 elementTypeAsString = ElementType.getAsString();
1378 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001380 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 buf += elementName;
1382 buf += ";\n\t";
1383 }
Chris Lattner06767512008-04-08 05:52:18 +00001384 else {
1385 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001387 elementTypeAsString
1388 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001389 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001390
1391 // struct __objcFastEnumerationState enumState = { 0 };
1392 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1393 // id items[16];
1394 buf += "id items[16];\n\t";
1395 // id l_collection = (id)
1396 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001397 // Find start location of 'collection' the hard way!
1398 const char *startCollectionBuf = startBuf;
1399 startCollectionBuf += 3; // skip 'for'
1400 startCollectionBuf = strchr(startCollectionBuf, '(');
1401 startCollectionBuf++; // skip '('
1402 // find 'in' and skip it.
1403 while (*startCollectionBuf != ' ' ||
1404 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1405 (*(startCollectionBuf+3) != ' ' &&
1406 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1407 startCollectionBuf++;
1408 startCollectionBuf += 3;
1409
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001411 ReplaceText(startLoc, startCollectionBuf - startBuf,
1412 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001414 SourceLocation rightParenLoc = S->getRParenLoc();
1415 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1416 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 buf = ";\n\t";
1418
1419 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1420 // objects:items count:16];
1421 // which is synthesized into:
1422 // unsigned int limit =
1423 // ((unsigned int (*)
1424 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1425 // (void *)objc_msgSend)((id)l_collection,
1426 // sel_registerName(
1427 // "countByEnumeratingWithState:objects:count:"),
1428 // (struct __objcFastEnumerationState *)&state,
1429 // (id *)items, (unsigned int)16);
1430 buf += "unsigned long limit =\n\t\t";
1431 SynthCountByEnumWithState(buf);
1432 buf += ";\n\t";
1433 /// if (limit) {
1434 /// unsigned long startMutations = *enumState.mutationsPtr;
1435 /// do {
1436 /// unsigned long counter = 0;
1437 /// do {
1438 /// if (startMutations != *enumState.mutationsPtr)
1439 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001440 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001441 buf += "if (limit) {\n\t";
1442 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1443 buf += "do {\n\t\t";
1444 buf += "unsigned long counter = 0;\n\t\t";
1445 buf += "do {\n\t\t\t";
1446 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1447 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1448 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001449 buf += " = (";
1450 buf += elementTypeAsString;
1451 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001452 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001453 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001455 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001456 /// } while (counter < limit);
1457 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1458 /// objects:items count:16]);
1459 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001461 /// }
1462 /// else
1463 /// elem = nil;
1464 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 ///
1466 buf = ";\n\t";
1467 buf += "__continue_label_";
1468 buf += utostr(ObjCBcLabelNo.back());
1469 buf += ": ;";
1470 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 buf += "} while (counter < limit);\n\t";
1472 buf += "} while (limit = ";
1473 SynthCountByEnumWithState(buf);
1474 buf += ");\n\t";
1475 buf += elementName;
1476 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001477 buf += "__break_label_";
1478 buf += utostr(ObjCBcLabelNo.back());
1479 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001480 buf += "}\n\t";
1481 buf += "else\n\t\t";
1482 buf += elementName;
1483 buf += " = nil;\n";
1484 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001485
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001486 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001487 if (isa<CompoundStmt>(S->getBody())) {
1488 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1489 InsertText(endBodyLoc, buf.c_str(), buf.size());
1490 } else {
1491 /* Need to treat single statements specially. For example:
1492 *
1493 * for (A *a in b) if (stuff()) break;
1494 * for (A *a in b) xxxyy;
1495 *
1496 * The following code simply scans ahead to the semi to find the actual end.
1497 */
1498 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1499 const char *semiBuf = strchr(stmtBuf, ';');
1500 assert(semiBuf && "Can't find ';'");
1501 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1502 InsertText(endBodyLoc, buf.c_str(), buf.size());
1503 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001504 Stmts.pop_back();
1505 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001507}
1508
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001509/// RewriteObjCSynchronizedStmt -
1510/// This routine rewrites @synchronized(expr) stmt;
1511/// into:
1512/// objc_sync_enter(expr);
1513/// @try stmt @finally { objc_sync_exit(expr); }
1514///
Steve Naroffb29b4272008-04-14 22:03:09 +00001515Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001516 // Get the start location and compute the semi location.
1517 SourceLocation startLoc = S->getLocStart();
1518 const char *startBuf = SM->getCharacterData(startLoc);
1519
1520 assert((*startBuf == '@') && "bogus @synchronized location");
1521
1522 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001523 buf = "objc_sync_enter((id)";
1524 const char *lparenBuf = startBuf;
1525 while (*lparenBuf != '(') lparenBuf++;
1526 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001527 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1528 // the sync expression is typically a message expression that's already
1529 // been rewritten! (which implies the SourceLocation's are invalid).
1530 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001531 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001532 while (*endBuf != ')') endBuf--;
1533 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001534 buf = ");\n";
1535 // declare a new scope with two variables, _stack and _rethrow.
1536 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1537 buf += "int buf[18/*32-bit i386*/];\n";
1538 buf += "char *pointers[4];} _stack;\n";
1539 buf += "id volatile _rethrow = 0;\n";
1540 buf += "objc_exception_try_enter(&_stack);\n";
1541 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001542 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001543 startLoc = S->getSynchBody()->getLocEnd();
1544 startBuf = SM->getCharacterData(startLoc);
1545
Steve Naroffc7089f12008-08-19 13:04:19 +00001546 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001547 SourceLocation lastCurlyLoc = startLoc;
1548 buf = "}\nelse {\n";
1549 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1550 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001551 buf += " objc_sync_exit(";
Steve Naroff3498cc92008-08-21 13:03:03 +00001552 Expr *syncExpr = new ExplicitCastExpr(Context->getObjCIdType(),
1553 S->getSynchExpr(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001554 std::string syncExprBufS;
1555 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001556 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001557 buf += syncExprBuf.str();
1558 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001559 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1560 buf += "}\n";
1561 buf += "}";
1562
Chris Lattneraadaf782008-01-31 19:51:04 +00001563 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001564 return 0;
1565}
1566
Steve Naroffb29b4272008-04-14 22:03:09 +00001567Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001568 // Get the start location and compute the semi location.
1569 SourceLocation startLoc = S->getLocStart();
1570 const char *startBuf = SM->getCharacterData(startLoc);
1571
1572 assert((*startBuf == '@') && "bogus @try location");
1573
1574 std::string buf;
1575 // declare a new scope with two variables, _stack and _rethrow.
1576 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1577 buf += "int buf[18/*32-bit i386*/];\n";
1578 buf += "char *pointers[4];} _stack;\n";
1579 buf += "id volatile _rethrow = 0;\n";
1580 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001581 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001582
Chris Lattneraadaf782008-01-31 19:51:04 +00001583 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001584
1585 startLoc = S->getTryBody()->getLocEnd();
1586 startBuf = SM->getCharacterData(startLoc);
1587
1588 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001589
Steve Naroff75730982007-11-07 04:08:17 +00001590 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001591 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1592 if (catchList) {
1593 startLoc = startLoc.getFileLocWithOffset(1);
1594 buf = " /* @catch begin */ else {\n";
1595 buf += " id _caught = objc_exception_extract(&_stack);\n";
1596 buf += " objc_exception_try_enter (&_stack);\n";
1597 buf += " if (_setjmp(_stack.buf))\n";
1598 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1599 buf += " else { /* @catch continue */";
1600
1601 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001602 } else { /* no catch list */
1603 buf = "}\nelse {\n";
1604 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1605 buf += "}";
1606 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001607 }
Steve Naroff75730982007-11-07 04:08:17 +00001608 bool sawIdTypedCatch = false;
1609 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001610 while (catchList) {
1611 Stmt *catchStmt = catchList->getCatchParamStmt();
1612
1613 if (catchList == S->getCatchStmts())
1614 buf = "if ("; // we are generating code for the first catch clause
1615 else
1616 buf = "else if (";
1617 startLoc = catchList->getLocStart();
1618 startBuf = SM->getCharacterData(startLoc);
1619
1620 assert((*startBuf == '@') && "bogus @catch location");
1621
1622 const char *lParenLoc = strchr(startBuf, '(');
1623
Steve Naroffbe4b3332008-02-01 22:08:12 +00001624 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001625 // Now rewrite the body...
1626 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001627 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1628 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001629 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1630 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001631 assert((*bodyBuf == '{') && "bogus @catch body location");
1632
1633 buf += "1) { id _tmp = _caught;";
1634 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1635 buf.c_str(), buf.size());
1636 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001637 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001638 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001639 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001640 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001641 sawIdTypedCatch = true;
1642 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001643 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001644
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001645 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001646 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001647 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001648 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001649 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001650 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001651 }
1652 }
1653 // Now rewrite the body...
1654 lastCatchBody = catchList->getCatchBody();
1655 SourceLocation rParenLoc = catchList->getRParenLoc();
1656 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1657 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1658 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1659 assert((*rParenBuf == ')') && "bogus @catch paren location");
1660 assert((*bodyBuf == '{') && "bogus @catch body location");
1661
1662 buf = " = _caught;";
1663 // Here we replace ") {" with "= _caught;" (which initializes and
1664 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001665 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001666 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001667 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001668 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001669 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001670 catchList = catchList->getNextCatchStmt();
1671 }
1672 // Complete the catch list...
1673 if (lastCatchBody) {
1674 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001675 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1676 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001677
Steve Naroff378f47a2008-09-11 15:29:03 +00001678 // Insert the last (implicit) else clause *before* the right curly brace.
1679 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1680 buf = "} /* last catch end */\n";
1681 buf += "else {\n";
1682 buf += " _rethrow = _caught;\n";
1683 buf += " objc_exception_try_exit(&_stack);\n";
1684 buf += "} } /* @catch end */\n";
1685 if (!S->getFinallyStmt())
1686 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001687 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001688
1689 // Set lastCurlyLoc
1690 lastCurlyLoc = lastCatchBody->getLocEnd();
1691 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001692 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001693 startLoc = finalStmt->getLocStart();
1694 startBuf = SM->getCharacterData(startLoc);
1695 assert((*startBuf == '@') && "bogus @finally start");
1696
1697 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001698 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001699
1700 Stmt *body = finalStmt->getFinallyBody();
1701 SourceLocation startLoc = body->getLocStart();
1702 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001703 assert(*SM->getCharacterData(startLoc) == '{' &&
1704 "bogus @finally body location");
1705 assert(*SM->getCharacterData(endLoc) == '}' &&
1706 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001707
1708 startLoc = startLoc.getFileLocWithOffset(1);
1709 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001710 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001711 endLoc = endLoc.getFileLocWithOffset(-1);
1712 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001713 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001714
1715 // Set lastCurlyLoc
1716 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001717 } else { /* no finally clause - make sure we synthesize an implicit one */
1718 buf = "{ /* implicit finally clause */\n";
1719 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1720 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1721 buf += "}";
1722 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001723 }
1724 // Now emit the final closing curly brace...
1725 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1726 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001727 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001728 return 0;
1729}
1730
Steve Naroffb29b4272008-04-14 22:03:09 +00001731Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001732 return 0;
1733}
1734
Steve Naroffb29b4272008-04-14 22:03:09 +00001735Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001736 return 0;
1737}
1738
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001739// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001740// the throw expression is typically a message expression that's already
1741// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001742Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001743 // Get the start location and compute the semi location.
1744 SourceLocation startLoc = S->getLocStart();
1745 const char *startBuf = SM->getCharacterData(startLoc);
1746
1747 assert((*startBuf == '@') && "bogus @throw location");
1748
1749 std::string buf;
1750 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001751 if (S->getThrowExpr())
1752 buf = "objc_exception_throw(";
1753 else // add an implicit argument
1754 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001755
1756 // handle "@ throw" correctly.
1757 const char *wBuf = strchr(startBuf, 'w');
1758 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1759 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1760
Steve Naroff2bd03922007-11-07 15:32:26 +00001761 const char *semiBuf = strchr(startBuf, ';');
1762 assert((*semiBuf == ';') && "@throw: can't find ';'");
1763 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1764 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001765 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001766 return 0;
1767}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001768
Steve Naroffb29b4272008-04-14 22:03:09 +00001769Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001770 // Create a new string expression.
1771 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001772 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001773 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001774 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1775 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001776 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001777 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001778
Chris Lattner07506182007-11-30 22:53:43 +00001779 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001780 delete Exp;
1781 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001782}
1783
Steve Naroffb29b4272008-04-14 22:03:09 +00001784Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001785 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1786 // Create a call to sel_registerName("selName").
1787 llvm::SmallVector<Expr*, 8> SelExprs;
1788 QualType argType = Context->getPointerType(Context->CharTy);
1789 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1790 Exp->getSelector().getName().size(),
1791 false, argType, SourceLocation(),
1792 SourceLocation()));
1793 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1794 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001795 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001796 delete Exp;
1797 return SelExp;
1798}
1799
Steve Naroffb29b4272008-04-14 22:03:09 +00001800CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001801 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001802 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001803 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001804
1805 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001806 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001807
1808 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001809 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001810 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1811
1812 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001813
Steve Naroff934f2762007-10-24 22:48:43 +00001814 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1815}
1816
Steve Naroffd5255f52007-11-01 13:24:47 +00001817static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1818 const char *&startRef, const char *&endRef) {
1819 while (startBuf < endBuf) {
1820 if (*startBuf == '<')
1821 startRef = startBuf; // mark the start.
1822 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001823 if (startRef && *startRef == '<') {
1824 endRef = startBuf; // mark the end.
1825 return true;
1826 }
1827 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001828 }
1829 startBuf++;
1830 }
1831 return false;
1832}
1833
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001834static void scanToNextArgument(const char *&argRef) {
1835 int angle = 0;
1836 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1837 if (*argRef == '<')
1838 angle++;
1839 else if (*argRef == '>')
1840 angle--;
1841 argRef++;
1842 }
1843 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1844}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001845
Steve Naroffb29b4272008-04-14 22:03:09 +00001846bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001847
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001849 return true;
1850
Steve Naroffd5255f52007-11-01 13:24:47 +00001851 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001852 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001853 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001854 return true; // we have "Class <Protocol> *".
1855 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001856 return false;
1857}
1858
Steve Naroff4f95b752008-07-29 18:15:38 +00001859void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1860 QualType Type = E->getType();
1861 if (needToScanForQualifiers(Type)) {
1862 SourceLocation Loc = E->getLocStart();
1863 const char *startBuf = SM->getCharacterData(Loc);
1864 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1865 const char *startRef = 0, *endRef = 0;
1866 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1867 // Get the locations of the startRef, endRef.
1868 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1869 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1870 // Comment out the protocol references.
1871 InsertText(LessLoc, "/*", 2);
1872 InsertText(GreaterLoc, "*/", 2);
1873 }
1874 }
1875}
1876
Steve Naroffb29b4272008-04-14 22:03:09 +00001877void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001878 SourceLocation Loc;
1879 QualType Type;
1880 const FunctionTypeProto *proto = 0;
1881 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1882 Loc = VD->getLocation();
1883 Type = VD->getType();
1884 }
1885 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1886 Loc = FD->getLocation();
1887 // Check for ObjC 'id' and class types that have been adorned with protocol
1888 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1889 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1890 assert(funcType && "missing function type");
1891 proto = dyn_cast<FunctionTypeProto>(funcType);
1892 if (!proto)
1893 return;
1894 Type = proto->getResultType();
1895 }
1896 else
1897 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001898
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001899 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001900 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001901
1902 const char *endBuf = SM->getCharacterData(Loc);
1903 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001904 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001905 startBuf--; // scan backward (from the decl location) for return type.
1906 const char *startRef = 0, *endRef = 0;
1907 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1908 // Get the locations of the startRef, endRef.
1909 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1910 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1911 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001912 InsertText(LessLoc, "/*", 2);
1913 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001914 }
1915 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001916 if (!proto)
1917 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001918 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001919 const char *startBuf = SM->getCharacterData(Loc);
1920 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001921 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1922 if (needToScanForQualifiers(proto->getArgType(i))) {
1923 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001924
Steve Naroffd5255f52007-11-01 13:24:47 +00001925 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001926 // scan forward (from the decl location) for argument types.
1927 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001928 const char *startRef = 0, *endRef = 0;
1929 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1930 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001931 SourceLocation LessLoc =
1932 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1933 SourceLocation GreaterLoc =
1934 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001935 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001936 InsertText(LessLoc, "/*", 2);
1937 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001938 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001939 startBuf = ++endBuf;
1940 }
1941 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001942 // If the function name is derived from a macro expansion, then the
1943 // argument buffer will not follow the name. Need to speak with Chris.
1944 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001945 startBuf++; // scan forward (from the decl location) for argument types.
1946 startBuf++;
1947 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001948 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001949}
1950
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001951// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001952void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001953 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1954 llvm::SmallVector<QualType, 16> ArgTys;
1955 ArgTys.push_back(Context->getPointerType(
1956 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001957 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001958 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001959 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001960 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001961 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001962 SelGetUidIdent, getFuncType,
1963 FunctionDecl::Extern, false, 0);
1964}
1965
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001966// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001967void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001968 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1969 llvm::SmallVector<QualType, 16> ArgTys;
1970 ArgTys.push_back(Context->getPointerType(
1971 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001972 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001973 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001974 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001975 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001976 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001977 SelGetProtoIdent, getFuncType,
1978 FunctionDecl::Extern, false, 0);
1979}
1980
Steve Naroffb29b4272008-04-14 22:03:09 +00001981void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001982 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001983 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001984 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001985 return;
1986 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001988}
1989
Steve Naroffc0a123c2008-03-11 17:37:02 +00001990// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001991void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001992 if (SuperContructorFunctionDecl)
1993 return;
1994 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1995 llvm::SmallVector<QualType, 16> ArgTys;
1996 QualType argT = Context->getObjCIdType();
1997 assert(!argT.isNull() && "Can't find 'id' type");
1998 ArgTys.push_back(argT);
1999 ArgTys.push_back(argT);
2000 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2001 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002002 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002003 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002004 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002005 msgSendIdent, msgSendType,
2006 FunctionDecl::Extern, false, 0);
2007}
2008
Steve Naroff09b266e2007-10-30 23:14:51 +00002009// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002010void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002011 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2012 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002014 assert(!argT.isNull() && "Can't find 'id' type");
2015 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002016 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002017 assert(!argT.isNull() && "Can't find 'SEL' type");
2018 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002020 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002021 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002022 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002023 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002024 msgSendIdent, msgSendType,
2025 FunctionDecl::Extern, false, 0);
2026}
2027
Steve Naroff874e2322007-11-15 10:28:18 +00002028// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002029void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002030 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2031 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002032 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002033 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002034 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002035 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2036 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2037 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002039 assert(!argT.isNull() && "Can't find 'SEL' type");
2040 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002042 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002043 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002044 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002045 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002046 msgSendIdent, msgSendType,
2047 FunctionDecl::Extern, false, 0);
2048}
2049
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002051void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002052 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2053 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002054 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002055 assert(!argT.isNull() && "Can't find 'id' type");
2056 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002057 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002058 assert(!argT.isNull() && "Can't find 'SEL' type");
2059 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002062 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002063 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002064 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065 msgSendIdent, msgSendType,
2066 FunctionDecl::Extern, false, 0);
2067}
2068
2069// SynthMsgSendSuperStretFunctionDecl -
2070// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002071void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002072 IdentifierInfo *msgSendIdent =
2073 &Context->Idents.get("objc_msgSendSuper_stret");
2074 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002075 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002076 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002077 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002078 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2079 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2080 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002082 assert(!argT.isNull() && "Can't find 'SEL' type");
2083 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002084 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002085 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002086 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002087 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002088 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002089 msgSendIdent, msgSendType,
2090 FunctionDecl::Extern, false, 0);
2091}
2092
Steve Naroff1284db82008-05-08 22:02:18 +00002093// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002094void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002095 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2096 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002098 assert(!argT.isNull() && "Can't find 'id' type");
2099 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002101 assert(!argT.isNull() && "Can't find 'SEL' type");
2102 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002103 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002104 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002105 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002106 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002107 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002108 msgSendIdent, msgSendType,
2109 FunctionDecl::Extern, false, 0);
2110}
2111
Steve Naroff09b266e2007-10-30 23:14:51 +00002112// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002113void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002114 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2115 llvm::SmallVector<QualType, 16> ArgTys;
2116 ArgTys.push_back(Context->getPointerType(
2117 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002118 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002119 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002120 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002121 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002122 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002123 getClassIdent, getClassType,
2124 FunctionDecl::Extern, false, 0);
2125}
2126
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002127// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002128void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002129 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2130 llvm::SmallVector<QualType, 16> ArgTys;
2131 ArgTys.push_back(Context->getPointerType(
2132 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002133 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002134 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002135 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002136 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002137 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002138 getClassIdent, getClassType,
2139 FunctionDecl::Extern, false, 0);
2140}
2141
Steve Naroffb29b4272008-04-14 22:03:09 +00002142Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002143 QualType strType = getConstantStringStructType();
2144
2145 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002146
2147 std::string tmpName = InFileName;
2148 unsigned i;
2149 for (i=0; i < tmpName.length(); i++) {
2150 char c = tmpName.at(i);
2151 // replace any non alphanumeric characters with '_'.
2152 if (!isalpha(c) && (c < '0' || c > '9'))
2153 tmpName[i] = '_';
2154 }
2155 S += tmpName;
2156 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002157 S += utostr(NumObjCStringLiterals++);
2158
Steve Naroffba92b2e2008-03-27 22:29:16 +00002159 Preamble += "static __NSConstantStringImpl " + S;
2160 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2161 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002162 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002163 std::string prettyBufS;
2164 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002165 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002166 Preamble += prettyBuf.str();
2167 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002168 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002169 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002170
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002171 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002172 &Context->Idents.get(S.c_str()), strType,
2173 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002174 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2175 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2176 Context->getPointerType(DRE->getType()),
2177 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002178 // cast to NSConstantString *
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002179 CastExpr *cast = new ExplicitCastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002180 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002181 delete Exp;
2182 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002183}
2184
Steve Naroffb29b4272008-04-14 22:03:09 +00002185ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002186 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002187 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002188
Chris Lattnerd9f69102008-08-10 01:53:14 +00002189 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
2190 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002191 const PointerType *PT = PDE->getType()->getAsPointerType();
2192 assert(PT);
2193 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2194 return IT->getDecl();
2195 }
2196 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002197}
2198
2199// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002200QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002201 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002202 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002203 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002204 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002205 QualType FieldTypes[2];
2206
2207 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002208 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002209 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002211 // Create fields
2212 FieldDecl *FieldDecls[2];
2213
2214 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002215 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002216 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002217
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002218 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002219 }
2220 return Context->getTagDeclType(SuperStructDecl);
2221}
2222
Steve Naroffb29b4272008-04-14 22:03:09 +00002223QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002224 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002225 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002226 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002227 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002228 QualType FieldTypes[4];
2229
2230 // struct objc_object *receiver;
2231 FieldTypes[0] = Context->getObjCIdType();
2232 // int flags;
2233 FieldTypes[1] = Context->IntTy;
2234 // char *str;
2235 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2236 // long length;
2237 FieldTypes[3] = Context->LongTy;
2238 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002239 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002240
2241 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002242 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002243 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002244
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002245 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002246 }
2247 return Context->getTagDeclType(ConstantStringDecl);
2248}
2249
Steve Naroffb29b4272008-04-14 22:03:09 +00002250Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002251 if (!SelGetUidFunctionDecl)
2252 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002253 if (!MsgSendFunctionDecl)
2254 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002255 if (!MsgSendSuperFunctionDecl)
2256 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257 if (!MsgSendStretFunctionDecl)
2258 SynthMsgSendStretFunctionDecl();
2259 if (!MsgSendSuperStretFunctionDecl)
2260 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002261 if (!MsgSendFpretFunctionDecl)
2262 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002263 if (!GetClassFunctionDecl)
2264 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002265 if (!GetMetaClassFunctionDecl)
2266 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267
Steve Naroff874e2322007-11-15 10:28:18 +00002268 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002269 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2270 // May need to use objc_msgSend_stret() as well.
2271 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002272 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002273 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002274 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002275 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002276 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002277 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002278 }
Steve Naroff874e2322007-11-15 10:28:18 +00002279
Steve Naroff934f2762007-10-24 22:48:43 +00002280 // Synthesize a call to objc_msgSend().
2281 llvm::SmallVector<Expr*, 8> MsgExprs;
2282 IdentifierInfo *clsName = Exp->getClassName();
2283
2284 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2285 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002286 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2287 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 if (!strcmp(clsName->getName(), "super")) {
2289 MsgSendFlavor = MsgSendSuperFunctionDecl;
2290 if (MsgSendStretFlavor)
2291 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2292 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2293
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002294 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002295 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002296
2297 llvm::SmallVector<Expr*, 4> InitExprs;
2298
2299 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002300 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002301 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002302 Context->getObjCIdType(),
2303 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 llvm::SmallVector<Expr*, 8> ClsExprs;
2305 QualType argType = Context->getPointerType(Context->CharTy);
2306 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2307 SuperDecl->getIdentifier()->getLength(),
2308 false, argType, SourceLocation(),
2309 SourceLocation()));
2310 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2311 &ClsExprs[0],
2312 ClsExprs.size());
2313 // To turn off a warning, type-cast to 'id'
2314 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002315 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002316 Cls, SourceLocation())); // set 'super class', using objc_getClass().
2317 // struct objc_super
2318 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002319 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002320
Steve Naroff23f41272008-03-11 18:14:26 +00002321 if (LangOpts.Microsoft) {
2322 SynthSuperContructorFunctionDecl();
2323 // Simulate a contructor call...
2324 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2325 superType, SourceLocation());
2326 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2327 superType, SourceLocation());
2328 } else {
2329 // (struct objc_super) { <exprs from above> }
2330 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2331 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002332 SourceLocation(), false);
2333 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2334 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002335 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002336 // struct objc_super *
2337 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2338 Context->getPointerType(SuperRep->getType()),
2339 SourceLocation());
2340 MsgExprs.push_back(Unop);
2341 } else {
2342 llvm::SmallVector<Expr*, 8> ClsExprs;
2343 QualType argType = Context->getPointerType(Context->CharTy);
2344 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2345 clsName->getLength(),
2346 false, argType, SourceLocation(),
2347 SourceLocation()));
2348 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2349 &ClsExprs[0],
2350 ClsExprs.size());
2351 MsgExprs.push_back(Cls);
2352 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002353 } else { // instance message.
2354 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002355
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002356 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002357 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002358 if (MsgSendStretFlavor)
2359 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002360 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2361
2362 llvm::SmallVector<Expr*, 4> InitExprs;
2363
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002364 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002365 new ExplicitCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002366 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002367 Context->getObjCIdType(),
2368 SourceLocation()),
2369 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002370
2371 llvm::SmallVector<Expr*, 8> ClsExprs;
2372 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002373 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2374 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002375 false, argType, SourceLocation(),
2376 SourceLocation()));
2377 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002378 &ClsExprs[0],
2379 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002380 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002381 InitExprs.push_back(
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002382 new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002383 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002384 // struct objc_super
2385 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002386 Expr *SuperRep;
2387
2388 if (LangOpts.Microsoft) {
2389 SynthSuperContructorFunctionDecl();
2390 // Simulate a contructor call...
2391 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2392 superType, SourceLocation());
2393 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2394 superType, SourceLocation());
2395 } else {
2396 // (struct objc_super) { <exprs from above> }
2397 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2398 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002399 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002400 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2401 }
Steve Naroff874e2322007-11-15 10:28:18 +00002402 // struct objc_super *
2403 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2404 Context->getPointerType(SuperRep->getType()),
2405 SourceLocation());
2406 MsgExprs.push_back(Unop);
2407 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002408 // Remove all type-casts because it may contain objc-style types; e.g.
2409 // Foo<Proto> *.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002410 while (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002411 recExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002412 recExpr = new ExplicitCastExpr(Context->getObjCIdType(), recExpr,
2413 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002414 MsgExprs.push_back(recExpr);
2415 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002416 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002417 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002418 llvm::SmallVector<Expr*, 8> SelExprs;
2419 QualType argType = Context->getPointerType(Context->CharTy);
2420 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2421 Exp->getSelector().getName().size(),
2422 false, argType, SourceLocation(),
2423 SourceLocation()));
2424 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2425 &SelExprs[0], SelExprs.size());
2426 MsgExprs.push_back(SelExp);
2427
2428 // Now push any user supplied arguments.
2429 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002430 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002431 // Make all implicit casts explicit...ICE comes in handy:-)
2432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2433 // Reuse the ICE type, it is exactly what the doctor ordered.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002434 userExpr = new ExplicitCastExpr(ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002436 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002437 }
2438 // Make id<P...> cast into an 'id' cast.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002439 else if (ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002440 if (CE->getType()->isObjCQualifiedIdType()) {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002441 while ((CE = dyn_cast<ExplicitCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002442 userExpr = CE->getSubExpr();
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002443 userExpr = new ExplicitCastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002444 userExpr, SourceLocation());
2445 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002446 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002447 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002448 // We've transferred the ownership to MsgExprs. Null out the argument in
2449 // the original expression, since we will delete it below.
2450 Exp->setArg(i, 0);
2451 }
Steve Naroffab972d32007-11-04 22:37:50 +00002452 // Generate the funky cast.
2453 CastExpr *cast;
2454 llvm::SmallVector<QualType, 8> ArgTypes;
2455 QualType returnType;
2456
2457 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002458 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2459 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2460 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 ArgTypes.push_back(Context->getObjCIdType());
2462 ArgTypes.push_back(Context->getObjCSelType());
2463 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002464 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002465 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2467 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002468 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002469 ArgTypes.push_back(t);
2470 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2472 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002473 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002475 }
2476 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002477 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002478
2479 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002480 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2481 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002482
2483 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2484 // If we don't do this cast, we get the following bizarre warning/note:
2485 // xx.m:13: warning: function called through a non-compatible type
2486 // xx.m:13: note: if this code is reached, the program will abort
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002487 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Steve Naroffab972d32007-11-04 22:37:50 +00002488 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002489
Steve Naroffab972d32007-11-04 22:37:50 +00002490 // Now do the "normal" pointer to function cast.
2491 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002492 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002493 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002494 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002495 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002496 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002497
2498 // Don't forget the parens to enforce the proper binding.
2499 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2500
2501 const FunctionType *FT = msgSendType->getAsFunctionType();
2502 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2503 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002504 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002505 if (MsgSendStretFlavor) {
2506 // We have the method which returns a struct/union. Must also generate
2507 // call to objc_msgSend_stret and hang both varieties on a conditional
2508 // expression which dictate which one to envoke depending on size of
2509 // method's return type.
2510
2511 // Create a reference to the objc_msgSend_stret() declaration.
2512 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2513 SourceLocation());
2514 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002515 cast = new ExplicitCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 SourceLocation());
2517 // Now do the "normal" pointer to function cast.
2518 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002519 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002520 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002521 castType = Context->getPointerType(castType);
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002522 cast = new ExplicitCastExpr(castType, cast, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002523
2524 // Don't forget the parens to enforce the proper binding.
2525 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2526
2527 FT = msgSendType->getAsFunctionType();
2528 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2529 FT->getResultType(), SourceLocation());
2530
2531 // Build sizeof(returnType)
2532 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2533 returnType, Context->getSizeType(),
2534 SourceLocation(), SourceLocation());
2535 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2536 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2537 // For X86 it is more complicated and some kind of target specific routine
2538 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002539 unsigned IntSize =
2540 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002541 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2542 Context->IntTy,
2543 SourceLocation());
2544 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2545 BinaryOperator::LE,
2546 Context->IntTy,
2547 SourceLocation());
2548 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2549 ConditionalOperator *CondExpr =
2550 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002551 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002552 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002553 return ReplacingStmt;
2554}
2555
Steve Naroffb29b4272008-04-14 22:03:09 +00002556Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002557 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002558 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002559 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002560
Chris Lattnere64b7772007-10-24 16:57:36 +00002561 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002562 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002563}
2564
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002565/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2566/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002567Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002568 if (!GetProtocolFunctionDecl)
2569 SynthGetProtocolFunctionDecl();
2570 // Create a call to objc_getProtocol("ProtocolName").
2571 llvm::SmallVector<Expr*, 8> ProtoExprs;
2572 QualType argType = Context->getPointerType(Context->CharTy);
2573 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2574 strlen(Exp->getProtocol()->getName()),
2575 false, argType, SourceLocation(),
2576 SourceLocation()));
2577 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2578 &ProtoExprs[0],
2579 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002580 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002581 delete Exp;
2582 return ProtoExp;
2583
2584}
2585
Steve Naroffbaf58c32008-05-31 14:15:04 +00002586bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2587 const char *endBuf) {
2588 while (startBuf < endBuf) {
2589 if (*startBuf == '#') {
2590 // Skip whitespace.
2591 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2592 ;
2593 if (!strncmp(startBuf, "if", strlen("if")) ||
2594 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2595 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2596 !strncmp(startBuf, "define", strlen("define")) ||
2597 !strncmp(startBuf, "undef", strlen("undef")) ||
2598 !strncmp(startBuf, "else", strlen("else")) ||
2599 !strncmp(startBuf, "elif", strlen("elif")) ||
2600 !strncmp(startBuf, "endif", strlen("endif")) ||
2601 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2602 !strncmp(startBuf, "include", strlen("include")) ||
2603 !strncmp(startBuf, "import", strlen("import")) ||
2604 !strncmp(startBuf, "include_next", strlen("include_next")))
2605 return true;
2606 }
2607 startBuf++;
2608 }
2609 return false;
2610}
2611
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002612/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002613/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002614void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002615 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2617 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002618 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002619 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002620 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002622 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002623 SourceLocation LocStart = CDecl->getLocStart();
2624 SourceLocation LocEnd = CDecl->getLocEnd();
2625
2626 const char *startBuf = SM->getCharacterData(LocStart);
2627 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002628
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002629 // If no ivars and no root or if its root, directly or indirectly,
2630 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002631 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2632 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002633 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002634 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002635 return;
2636 }
2637
2638 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002639 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002640 Result += "\nstruct ";
2641 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002642 if (LangOpts.Microsoft)
2643 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002644
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002645 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002646 const char *cursor = strchr(startBuf, '{');
2647 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002648 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002649 // If the buffer contains preprocessor directives, we do more fine-grained
2650 // rewrites. This is intended to fix code that looks like (which occurs in
2651 // NSURL.h, for example):
2652 //
2653 // #ifdef XYZ
2654 // @interface Foo : NSObject
2655 // #else
2656 // @interface FooBar : NSObject
2657 // #endif
2658 // {
2659 // int i;
2660 // }
2661 // @end
2662 //
2663 // This clause is segregated to avoid breaking the common case.
2664 if (BufferContainsPPDirectives(startBuf, cursor)) {
2665 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2666 CDecl->getClassLoc();
2667 const char *endHeader = SM->getCharacterData(L);
2668 endHeader += Lexer::MeasureTokenLength(L, *SM);
2669
Chris Lattner3db6cae2008-07-21 18:19:38 +00002670 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002671 // advance to the end of the referenced protocols.
2672 while (endHeader < cursor && *endHeader != '>') endHeader++;
2673 endHeader++;
2674 }
2675 // rewrite the original header
2676 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2677 } else {
2678 // rewrite the original header *without* disturbing the '{'
2679 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2680 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002681 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002682 Result = "\n struct ";
2683 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002684 Result += "_IMPL ";
2685 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002686 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002687
2688 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002689 SourceLocation OnePastCurly =
2690 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2691 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002692 }
2693 cursor++; // past '{'
2694
2695 // Now comment out any visibility specifiers.
2696 while (cursor < endBuf) {
2697 if (*cursor == '@') {
2698 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002699 // Skip whitespace.
2700 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2701 /*scan*/;
2702
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002703 // FIXME: presence of @public, etc. inside comment results in
2704 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002705 if (!strncmp(cursor, "public", strlen("public")) ||
2706 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002707 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002708 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002709 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002710 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002711 // FIXME: If there are cases where '<' is used in ivar declaration part
2712 // of user code, then scan the ivar list and use needToScanForQualifiers
2713 // for type checking.
2714 else if (*cursor == '<') {
2715 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002716 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002717 cursor = strchr(cursor, '>');
2718 cursor++;
2719 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002720 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002721 }
Steve Narofffea763e82007-11-14 19:25:57 +00002722 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002723 }
Steve Narofffea763e82007-11-14 19:25:57 +00002724 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002725 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002726 } else { // we don't have any instance variables - insert super struct.
2727 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2728 Result += " {\n struct ";
2729 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002730 Result += "_IMPL ";
2731 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002732 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002733 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002734 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002735 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002736 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002737 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002738}
2739
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002740// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002741/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002742void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002743 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002744 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002745 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002746 const char *ClassName,
2747 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002748 if (MethodBegin == MethodEnd) return;
2749
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002750 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002751 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002752 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002753 SEL _cmd;
2754 char *method_types;
2755 void *_imp;
2756 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002758 Result += "\nstruct _objc_method {\n";
2759 Result += "\tSEL _cmd;\n";
2760 Result += "\tchar *method_types;\n";
2761 Result += "\tvoid *_imp;\n";
2762 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002764 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002765 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002766
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002767 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002768
2769 /* struct {
2770 struct _objc_method_list *next_method;
2771 int method_count;
2772 struct _objc_method method_list[];
2773 }
2774 */
2775 Result += "\nstatic struct {\n";
2776 Result += "\tstruct _objc_method_list *next_method;\n";
2777 Result += "\tint method_count;\n";
2778 Result += "\tstruct _objc_method method_list[";
2779 Result += utostr(MethodEnd-MethodBegin);
2780 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002781 Result += prefix;
2782 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2783 Result += "_METHODS_";
2784 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002785 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002786 Result += IsInstanceMethod ? "inst" : "cls";
2787 Result += "_meth\")))= ";
2788 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002789
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002790 Result += "\t,{{(SEL)\"";
2791 Result += (*MethodBegin)->getSelector().getName().c_str();
2792 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002793 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002794 Result += "\", \"";
2795 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002796 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002797 Result += MethodInternalNames[*MethodBegin];
2798 Result += "}\n";
2799 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2800 Result += "\t ,{(SEL)\"";
2801 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002802 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002803 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002804 Result += "\", \"";
2805 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002806 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002807 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002808 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002809 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002810 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811}
2812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002813/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002814void RewriteObjC::
2815RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2816 const char *prefix,
2817 const char *ClassName,
2818 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002819 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002820 if (Protocols.empty()) return;
2821
2822 for (unsigned i = 0; i != Protocols.size(); i++) {
2823 ObjCProtocolDecl *PDecl = Protocols[i];
2824 // Output struct protocol_methods holder of method selector and type.
2825 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2826 /* struct protocol_methods {
2827 SEL _cmd;
2828 char *method_types;
2829 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002830 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002831 Result += "\nstruct protocol_methods {\n";
2832 Result += "\tSEL _cmd;\n";
2833 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002834 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002835
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002836 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002837 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002838 // Do not synthesize the protocol more than once.
2839 if (ObjCSynthesizedProtocols.count(PDecl))
2840 continue;
2841
2842 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2843 unsigned NumMethods = PDecl->getNumInstanceMethods();
2844 /* struct _objc_protocol_method_list {
2845 int protocol_method_count;
2846 struct protocol_methods protocols[];
2847 }
2848 */
2849 Result += "\nstatic struct {\n";
2850 Result += "\tint protocol_method_count;\n";
2851 Result += "\tstruct protocol_methods protocols[";
2852 Result += utostr(NumMethods);
2853 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2854 Result += PDecl->getName();
2855 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2856 "{\n\t" + utostr(NumMethods) + "\n";
2857
2858 // Output instance methods declared in this protocol.
2859 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2860 E = PDecl->instmeth_end(); I != E; ++I) {
2861 if (I == PDecl->instmeth_begin())
2862 Result += "\t ,{{(SEL)\"";
2863 else
2864 Result += "\t ,{(SEL)\"";
2865 Result += (*I)->getSelector().getName().c_str();
2866 std::string MethodTypeString;
2867 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2868 Result += "\", \"";
2869 Result += MethodTypeString;
2870 Result += "\"}\n";
2871 }
2872 Result += "\t }\n};\n";
2873 }
2874
2875 // Output class methods declared in this protocol.
2876 int NumMethods = PDecl->getNumClassMethods();
2877 if (NumMethods > 0) {
2878 /* struct _objc_protocol_method_list {
2879 int protocol_method_count;
2880 struct protocol_methods protocols[];
2881 }
2882 */
2883 Result += "\nstatic struct {\n";
2884 Result += "\tint protocol_method_count;\n";
2885 Result += "\tstruct protocol_methods protocols[";
2886 Result += utostr(NumMethods);
2887 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2888 Result += PDecl->getName();
2889 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2890 "{\n\t";
2891 Result += utostr(NumMethods);
2892 Result += "\n";
2893
2894 // Output instance methods declared in this protocol.
2895 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2896 E = PDecl->classmeth_end(); I != E; ++I) {
2897 if (I == PDecl->classmeth_begin())
2898 Result += "\t ,{{(SEL)\"";
2899 else
2900 Result += "\t ,{(SEL)\"";
2901 Result += (*I)->getSelector().getName().c_str();
2902 std::string MethodTypeString;
2903 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2904 Result += "\", \"";
2905 Result += MethodTypeString;
2906 Result += "\"}\n";
2907 }
2908 Result += "\t }\n};\n";
2909 }
2910
2911 // Output:
2912 /* struct _objc_protocol {
2913 // Objective-C 1.0 extensions
2914 struct _objc_protocol_extension *isa;
2915 char *protocol_name;
2916 struct _objc_protocol **protocol_list;
2917 struct _objc_protocol_method_list *instance_methods;
2918 struct _objc_protocol_method_list *class_methods;
2919 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002920 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002921 static bool objc_protocol = false;
2922 if (!objc_protocol) {
2923 Result += "\nstruct _objc_protocol {\n";
2924 Result += "\tstruct _objc_protocol_extension *isa;\n";
2925 Result += "\tchar *protocol_name;\n";
2926 Result += "\tstruct _objc_protocol **protocol_list;\n";
2927 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2928 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2929 Result += "};\n";
2930
2931 objc_protocol = true;
2932 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002933
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002934 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2935 Result += PDecl->getName();
2936 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2937 "{\n\t0, \"";
2938 Result += PDecl->getName();
2939 Result += "\", 0, ";
2940 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2941 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2942 Result += PDecl->getName();
2943 Result += ", ";
2944 }
2945 else
2946 Result += "0, ";
2947 if (PDecl->getNumClassMethods() > 0) {
2948 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2949 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002950 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002951 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002952 else
2953 Result += "0\n";
2954 Result += "};\n";
2955
2956 // Mark this protocol as having been generated.
2957 if (!ObjCSynthesizedProtocols.insert(PDecl))
2958 assert(false && "protocol already synthesized");
2959 }
2960 // Output the top lovel protocol meta-data for the class.
2961 /* struct _objc_protocol_list {
2962 struct _objc_protocol_list *next;
2963 int protocol_count;
2964 struct _objc_protocol *class_protocols[];
2965 }
2966 */
2967 Result += "\nstatic struct {\n";
2968 Result += "\tstruct _objc_protocol_list *next;\n";
2969 Result += "\tint protocol_count;\n";
2970 Result += "\tstruct _objc_protocol *class_protocols[";
2971 Result += utostr(Protocols.size());
2972 Result += "];\n} _OBJC_";
2973 Result += prefix;
2974 Result += "_PROTOCOLS_";
2975 Result += ClassName;
2976 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2977 "{\n\t0, ";
2978 Result += utostr(Protocols.size());
2979 Result += "\n";
2980
2981 Result += "\t,{&_OBJC_PROTOCOL_";
2982 Result += Protocols[0]->getName();
2983 Result += " \n";
2984
2985 for (unsigned i = 1; i != Protocols.size(); i++) {
2986 Result += "\t ,&_OBJC_PROTOCOL_";
2987 Result += Protocols[i]->getName();
2988 Result += "\n";
2989 }
2990 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002991}
2992
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002993/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002994/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002995void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002996 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002997 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002998 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003000 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3001 CDecl = CDecl->getNextClassCategory())
3002 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3003 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003004
Chris Lattnereb44eee2007-12-23 01:40:15 +00003005 std::string FullCategoryName = ClassDecl->getName();
3006 FullCategoryName += '_';
3007 FullCategoryName += IDecl->getName();
3008
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003009 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003010 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003011 true, "CATEGORY_", FullCategoryName.c_str(),
3012 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003013
3014 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003015 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003016 false, "CATEGORY_", FullCategoryName.c_str(),
3017 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003018
3019 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003020 // Null CDecl is case of a category implementation with no category interface
3021 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003022 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003023 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024
3025 /* struct _objc_category {
3026 char *category_name;
3027 char *class_name;
3028 struct _objc_method_list *instance_methods;
3029 struct _objc_method_list *class_methods;
3030 struct _objc_protocol_list *protocols;
3031 // Objective-C 1.0 extensions
3032 uint32_t size; // sizeof (struct _objc_category)
3033 struct _objc_property_list *instance_properties; // category's own
3034 // @property decl.
3035 };
3036 */
3037
3038 static bool objc_category = false;
3039 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003040 Result += "\nstruct _objc_category {\n";
3041 Result += "\tchar *category_name;\n";
3042 Result += "\tchar *class_name;\n";
3043 Result += "\tstruct _objc_method_list *instance_methods;\n";
3044 Result += "\tstruct _objc_method_list *class_methods;\n";
3045 Result += "\tstruct _objc_protocol_list *protocols;\n";
3046 Result += "\tunsigned int size;\n";
3047 Result += "\tstruct _objc_property_list *instance_properties;\n";
3048 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003049 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003050 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003051 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3052 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003053 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003054 Result += IDecl->getName();
3055 Result += "\"\n\t, \"";
3056 Result += ClassDecl->getName();
3057 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003058
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003059 if (IDecl->getNumInstanceMethods() > 0) {
3060 Result += "\t, (struct _objc_method_list *)"
3061 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3062 Result += FullCategoryName;
3063 Result += "\n";
3064 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003065 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += "\t, 0\n";
3067 if (IDecl->getNumClassMethods() > 0) {
3068 Result += "\t, (struct _objc_method_list *)"
3069 "&_OBJC_CATEGORY_CLASS_METHODS_";
3070 Result += FullCategoryName;
3071 Result += "\n";
3072 }
3073 else
3074 Result += "\t, 0\n";
3075
Chris Lattner780f3292008-07-21 21:32:27 +00003076 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003077 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3078 Result += FullCategoryName;
3079 Result += "\n";
3080 }
3081 else
3082 Result += "\t, 0\n";
3083 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003084}
3085
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003086/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3087/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003088void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003089 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003090 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003091 if (ivar->isBitField()) {
3092 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3093 // place all bitfields at offset 0.
3094 Result += "0";
3095 } else {
3096 Result += "__OFFSETOFIVAR__(struct ";
3097 Result += IDecl->getName();
3098 if (LangOpts.Microsoft)
3099 Result += "_IMPL";
3100 Result += ", ";
3101 Result += ivar->getName();
3102 Result += ")";
3103 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003104}
3105
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003106//===----------------------------------------------------------------------===//
3107// Meta Data Emission
3108//===----------------------------------------------------------------------===//
3109
Steve Naroffb29b4272008-04-14 22:03:09 +00003110void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003111 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003113
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003114 // Explictly declared @interface's are already synthesized.
3115 if (CDecl->ImplicitInterfaceDecl()) {
3116 // FIXME: Implementation of a class with no @interface (legacy) doese not
3117 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003119 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003120
Chris Lattnerbe6df082007-12-12 07:56:42 +00003121 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003122 unsigned NumIvars = !IDecl->ivar_empty()
3123 ? IDecl->ivar_size()
3124 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003125 if (NumIvars > 0) {
3126 static bool objc_ivar = false;
3127 if (!objc_ivar) {
3128 /* struct _objc_ivar {
3129 char *ivar_name;
3130 char *ivar_type;
3131 int ivar_offset;
3132 };
3133 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003134 Result += "\nstruct _objc_ivar {\n";
3135 Result += "\tchar *ivar_name;\n";
3136 Result += "\tchar *ivar_type;\n";
3137 Result += "\tint ivar_offset;\n";
3138 Result += "};\n";
3139
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003140 objc_ivar = true;
3141 }
3142
Steve Naroff946a6932008-03-11 00:12:29 +00003143 /* struct {
3144 int ivar_count;
3145 struct _objc_ivar ivar_list[nIvars];
3146 };
3147 */
3148 Result += "\nstatic struct {\n";
3149 Result += "\tint ivar_count;\n";
3150 Result += "\tstruct _objc_ivar ivar_list[";
3151 Result += utostr(NumIvars);
3152 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003153 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003154 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 "{\n\t";
3156 Result += utostr(NumIvars);
3157 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003158
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003159 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003160 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003161 IVI = IDecl->ivar_begin();
3162 IVE = IDecl->ivar_end();
3163 } else {
3164 IVI = CDecl->ivar_begin();
3165 IVE = CDecl->ivar_end();
3166 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003167 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003168 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003169 Result += "\", \"";
3170 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003171 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003172 Result += StrEncoding;
3173 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003174 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003175 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003176 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003177 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003178 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003179 Result += "\", \"";
3180 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003181 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003182 Result += StrEncoding;
3183 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003184 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003185 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003186 }
3187
3188 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003189 }
3190
3191 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003193 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003194
3195 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003196 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003197 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003199 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003200 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003201 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003202
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003203
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003204 // Declaration of class/meta-class metadata
3205 /* struct _objc_class {
3206 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003207 const char *super_class_name;
3208 char *name;
3209 long version;
3210 long info;
3211 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003212 struct _objc_ivar_list *ivars;
3213 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003214 struct objc_cache *cache;
3215 struct objc_protocol_list *protocols;
3216 const char *ivar_layout;
3217 struct _objc_class_ext *ext;
3218 };
3219 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003220 static bool objc_class = false;
3221 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003222 Result += "\nstruct _objc_class {\n";
3223 Result += "\tstruct _objc_class *isa;\n";
3224 Result += "\tconst char *super_class_name;\n";
3225 Result += "\tchar *name;\n";
3226 Result += "\tlong version;\n";
3227 Result += "\tlong info;\n";
3228 Result += "\tlong instance_size;\n";
3229 Result += "\tstruct _objc_ivar_list *ivars;\n";
3230 Result += "\tstruct _objc_method_list *methods;\n";
3231 Result += "\tstruct objc_cache *cache;\n";
3232 Result += "\tstruct _objc_protocol_list *protocols;\n";
3233 Result += "\tconst char *ivar_layout;\n";
3234 Result += "\tstruct _objc_class_ext *ext;\n";
3235 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003236 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003237 }
3238
3239 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003240 ObjCInterfaceDecl *RootClass = 0;
3241 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003242 while (SuperClass) {
3243 RootClass = SuperClass;
3244 SuperClass = SuperClass->getSuperClass();
3245 }
3246 SuperClass = CDecl->getSuperClass();
3247
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003248 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3249 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003250 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003251 "{\n\t(struct _objc_class *)\"";
3252 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3253 Result += "\"";
3254
3255 if (SuperClass) {
3256 Result += ", \"";
3257 Result += SuperClass->getName();
3258 Result += "\", \"";
3259 Result += CDecl->getName();
3260 Result += "\"";
3261 }
3262 else {
3263 Result += ", 0, \"";
3264 Result += CDecl->getName();
3265 Result += "\"";
3266 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003267 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003268 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003269 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003270 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003271 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003272 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 Result += "\n";
3274 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003275 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003277 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003278 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += CDecl->getName();
3280 Result += ",0,0\n";
3281 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003282 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += "\t,0,0,0,0\n";
3284 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003285
3286 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3288 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003289 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003290 "{\n\t&_OBJC_METACLASS_";
3291 Result += CDecl->getName();
3292 if (SuperClass) {
3293 Result += ", \"";
3294 Result += SuperClass->getName();
3295 Result += "\", \"";
3296 Result += CDecl->getName();
3297 Result += "\"";
3298 }
3299 else {
3300 Result += ", 0, \"";
3301 Result += CDecl->getName();
3302 Result += "\"";
3303 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003304 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003305 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003306 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003307 Result += ",0";
3308 else {
3309 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003310 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003311 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003312 if (LangOpts.Microsoft)
3313 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003314 Result += ")";
3315 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003317 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003318 Result += CDecl->getName();
3319 Result += "\n\t";
3320 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003321 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003322 Result += ",0";
3323 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003324 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003325 Result += CDecl->getName();
3326 Result += ", 0\n\t";
3327 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003328 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003329 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003330 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003331 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003332 Result += CDecl->getName();
3333 Result += ", 0,0\n";
3334 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003335 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003336 Result += ",0,0,0\n";
3337 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003338}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003339
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003340/// RewriteImplementations - This routine rewrites all method implementations
3341/// and emits meta-data.
3342
Steve Naroffb29b4272008-04-14 22:03:09 +00003343void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003344 int ClsDefCount = ClassImplementation.size();
3345 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003346
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003347 if (ClsDefCount == 0 && CatDefCount == 0)
3348 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003349 // Rewrite implemented methods
3350 for (int i = 0; i < ClsDefCount; i++)
3351 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003352
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003353 for (int i = 0; i < CatDefCount; i++)
3354 RewriteImplementationDecl(CategoryImplementation[i]);
3355
Steve Naroff5df5b762008-05-07 21:23:49 +00003356 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003357 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003358 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003359 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003360 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003361
3362 // For each implemented category, write out all its meta data.
3363 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003364 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003365
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003366 // Write objc_symtab metadata
3367 /*
3368 struct _objc_symtab
3369 {
3370 long sel_ref_cnt;
3371 SEL *refs;
3372 short cls_def_cnt;
3373 short cat_def_cnt;
3374 void *defs[cls_def_cnt + cat_def_cnt];
3375 };
3376 */
3377
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003378 Result += "\nstruct _objc_symtab {\n";
3379 Result += "\tlong sel_ref_cnt;\n";
3380 Result += "\tSEL *refs;\n";
3381 Result += "\tshort cls_def_cnt;\n";
3382 Result += "\tshort cat_def_cnt;\n";
3383 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3384 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003385
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003386 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003387 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += "\t0, 0, " + utostr(ClsDefCount)
3389 + ", " + utostr(CatDefCount) + "\n";
3390 for (int i = 0; i < ClsDefCount; i++) {
3391 Result += "\t,&_OBJC_CLASS_";
3392 Result += ClassImplementation[i]->getName();
3393 Result += "\n";
3394 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003395
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 for (int i = 0; i < CatDefCount; i++) {
3397 Result += "\t,&_OBJC_CATEGORY_";
3398 Result += CategoryImplementation[i]->getClassInterface()->getName();
3399 Result += "_";
3400 Result += CategoryImplementation[i]->getName();
3401 Result += "\n";
3402 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003403
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003404 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003405
3406 // Write objc_module metadata
3407
3408 /*
3409 struct _objc_module {
3410 long version;
3411 long size;
3412 const char *name;
3413 struct _objc_symtab *symtab;
3414 }
3415 */
3416
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003417 Result += "\nstruct _objc_module {\n";
3418 Result += "\tlong version;\n";
3419 Result += "\tlong size;\n";
3420 Result += "\tconst char *name;\n";
3421 Result += "\tstruct _objc_symtab *symtab;\n";
3422 Result += "};\n\n";
3423 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003424 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003425 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3426 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003428
3429 if (LangOpts.Microsoft) {
3430 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003431 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003432 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3433 Result += "&_OBJC_MODULES;\n";
3434 Result += "#pragma data_seg(pop)\n\n";
3435 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003436}
Chris Lattner311ff022007-10-16 22:36:42 +00003437
Steve Naroff54055232008-10-27 17:20:55 +00003438std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3439 const char *funcName,
3440 std::string Tag) {
3441 const FunctionType *AFT = CE->getFunctionType();
3442 QualType RT = AFT->getResultType();
3443 std::string StructRef = "struct " + Tag;
3444 std::string S = "static " + RT.getAsString() + " __" +
3445 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003446
Steve Naroff54055232008-10-27 17:20:55 +00003447 BlockDecl *BD = CE->getBlockDecl();
3448
3449 if (isa<FunctionTypeNoProto>(AFT)) {
3450 S += "()";
3451 } else if (BD->param_empty()) {
3452 S += "(" + StructRef + " *__cself)";
3453 } else {
3454 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3455 assert(FT && "SynthesizeBlockFunc: No function proto");
3456 S += '(';
3457 // first add the implicit argument.
3458 S += StructRef + " *__cself, ";
3459 std::string ParamStr;
3460 for (BlockDecl::param_iterator AI = BD->param_begin(),
3461 E = BD->param_end(); AI != E; ++AI) {
3462 if (AI != BD->param_begin()) S += ", ";
3463 ParamStr = (*AI)->getName();
3464 (*AI)->getType().getAsStringInternal(ParamStr);
3465 S += ParamStr;
3466 }
3467 if (FT->isVariadic()) {
3468 if (!BD->param_empty()) S += ", ";
3469 S += "...";
3470 }
3471 S += ')';
3472 }
3473 S += " {\n";
3474
3475 // Create local declarations to avoid rewriting all closure decl ref exprs.
3476 // First, emit a declaration for all "by ref" decls.
3477 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3478 E = BlockByRefDecls.end(); I != E; ++I) {
3479 S += " ";
3480 std::string Name = (*I)->getName();
3481 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3482 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3483 }
3484 // Next, emit a declaration for all "by copy" declarations.
3485 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3486 E = BlockByCopyDecls.end(); I != E; ++I) {
3487 S += " ";
3488 std::string Name = (*I)->getName();
3489 // Handle nested closure invocation. For example:
3490 //
3491 // void (^myImportedClosure)(void);
3492 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3493 //
3494 // void (^anotherClosure)(void);
3495 // anotherClosure = ^(void) {
3496 // myImportedClosure(); // import and invoke the closure
3497 // };
3498 //
3499 if (isBlockPointerType((*I)->getType()))
3500 S += "struct __block_impl *";
3501 else
3502 (*I)->getType().getAsStringInternal(Name);
3503 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3504 }
3505 std::string RewrittenStr = RewrittenBlockExprs[CE];
3506 const char *cstr = RewrittenStr.c_str();
3507 while (*cstr++ != '{') ;
3508 S += cstr;
3509 S += "\n";
3510 return S;
3511}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003512
Steve Naroff54055232008-10-27 17:20:55 +00003513std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3514 const char *funcName,
3515 std::string Tag) {
3516 std::string StructRef = "struct " + Tag;
3517 std::string S = "static void __";
3518
3519 S += funcName;
3520 S += "_block_copy_" + utostr(i);
3521 S += "(" + StructRef;
3522 S += "*dst, " + StructRef;
3523 S += "*src) {";
3524 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3525 E = ImportedBlockDecls.end(); I != E; ++I) {
3526 S += "_Block_copy_assign(&dst->";
3527 S += (*I)->getName();
3528 S += ", src->";
3529 S += (*I)->getName();
3530 S += ");}";
3531 }
3532 S += "\nstatic void __";
3533 S += funcName;
3534 S += "_block_dispose_" + utostr(i);
3535 S += "(" + StructRef;
3536 S += "*src) {";
3537 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3538 E = ImportedBlockDecls.end(); I != E; ++I) {
3539 S += "_Block_destroy(src->";
3540 S += (*I)->getName();
3541 S += ");";
3542 }
3543 S += "}\n";
3544 return S;
3545}
3546
3547std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3548 bool hasCopyDisposeHelpers) {
3549 std::string S = "struct " + Tag;
3550 std::string Constructor = " " + Tag;
3551
3552 S += " {\n struct __block_impl impl;\n";
3553
3554 if (hasCopyDisposeHelpers)
3555 S += " void *copy;\n void *dispose;\n";
3556
3557 Constructor += "(void *fp";
3558
3559 if (hasCopyDisposeHelpers)
3560 Constructor += ", void *copyHelp, void *disposeHelp";
3561
3562 if (BlockDeclRefs.size()) {
3563 // Output all "by copy" declarations.
3564 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3565 E = BlockByCopyDecls.end(); I != E; ++I) {
3566 S += " ";
3567 std::string FieldName = (*I)->getName();
3568 std::string ArgName = "_" + FieldName;
3569 // Handle nested closure invocation. For example:
3570 //
3571 // void (^myImportedBlock)(void);
3572 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3573 //
3574 // void (^anotherBlock)(void);
3575 // anotherBlock = ^(void) {
3576 // myImportedBlock(); // import and invoke the closure
3577 // };
3578 //
3579 if (isBlockPointerType((*I)->getType())) {
3580 S += "struct __block_impl *";
3581 Constructor += ", void *" + ArgName;
3582 } else {
3583 (*I)->getType().getAsStringInternal(FieldName);
3584 (*I)->getType().getAsStringInternal(ArgName);
3585 Constructor += ", " + ArgName;
3586 }
3587 S += FieldName + ";\n";
3588 }
3589 // Output all "by ref" declarations.
3590 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3591 E = BlockByRefDecls.end(); I != E; ++I) {
3592 S += " ";
3593 std::string FieldName = (*I)->getName();
3594 std::string ArgName = "_" + FieldName;
3595 // Handle nested closure invocation. For example:
3596 //
3597 // void (^myImportedBlock)(void);
3598 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3599 //
3600 // void (^anotherBlock)(void);
3601 // anotherBlock = ^(void) {
3602 // myImportedBlock(); // import and invoke the closure
3603 // };
3604 //
3605 if (isBlockPointerType((*I)->getType())) {
3606 S += "struct __block_impl *";
3607 Constructor += ", void *" + ArgName;
3608 } else {
3609 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3610 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3611 Constructor += ", " + ArgName;
3612 }
3613 S += FieldName + "; // by ref\n";
3614 }
3615 // Finish writing the constructor.
3616 // FIXME: handle NSConcreteGlobalBlock.
3617 Constructor += ", int flags=0) {\n";
3618 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3619 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3620
3621 if (hasCopyDisposeHelpers)
3622 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3623
3624 // Initialize all "by copy" arguments.
3625 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3626 E = BlockByCopyDecls.end(); I != E; ++I) {
3627 std::string Name = (*I)->getName();
3628 Constructor += " ";
3629 if (isBlockPointerType((*I)->getType()))
3630 Constructor += Name + " = (struct __block_impl *)_";
3631 else
3632 Constructor += Name + " = _";
3633 Constructor += Name + ";\n";
3634 }
3635 // Initialize all "by ref" arguments.
3636 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3637 E = BlockByRefDecls.end(); I != E; ++I) {
3638 std::string Name = (*I)->getName();
3639 Constructor += " ";
3640 if (isBlockPointerType((*I)->getType()))
3641 Constructor += Name + " = (struct __block_impl *)_";
3642 else
3643 Constructor += Name + " = _";
3644 Constructor += Name + ";\n";
3645 }
3646 } else {
3647 // Finish writing the constructor.
3648 // FIXME: handle NSConcreteGlobalBlock.
3649 Constructor += ", int flags=0) {\n";
3650 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3651 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3652 if (hasCopyDisposeHelpers)
3653 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3654 }
3655 Constructor += " ";
3656 Constructor += "}\n";
3657 S += Constructor;
3658 S += "};\n";
3659 return S;
3660}
3661
3662void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3663 const char *FunName) {
3664 // Insert closures that were part of the function.
3665 for (unsigned i = 0; i < Blocks.size(); i++) {
3666
3667 CollectBlockDeclRefInfo(Blocks[i]);
3668
3669 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3670
3671 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3672 ImportedBlockDecls.size() > 0);
3673
3674 InsertText(FunLocStart, CI.c_str(), CI.size());
3675
3676 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3677
3678 InsertText(FunLocStart, CF.c_str(), CF.size());
3679
3680 if (ImportedBlockDecls.size()) {
3681 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3682 InsertText(FunLocStart, HF.c_str(), HF.size());
3683 }
3684
3685 BlockDeclRefs.clear();
3686 BlockByRefDecls.clear();
3687 BlockByCopyDecls.clear();
3688 BlockCallExprs.clear();
3689 ImportedBlockDecls.clear();
3690 }
3691 Blocks.clear();
3692 RewrittenBlockExprs.clear();
3693}
3694
3695void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3696 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3697 const char *FuncName = FD->getName();
3698
3699 SynthesizeBlockLiterals(FunLocStart, FuncName);
3700}
3701
3702void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3703 SourceLocation FunLocStart = MD->getLocStart();
3704 std::string FuncName = std::string(MD->getSelector().getName());
3705 // Convert colons to underscores.
3706 std::string::size_type loc = 0;
3707 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3708 FuncName.replace(loc, 1, "_");
3709
3710 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3711}
3712
3713void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3714 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3715 CI != E; ++CI)
3716 if (*CI) {
3717 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3718 GetBlockDeclRefExprs(CBE->getBody());
3719 else
3720 GetBlockDeclRefExprs(*CI);
3721 }
3722 // Handle specific things.
3723 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3724 // FIXME: Handle enums.
3725 if (!isa<FunctionDecl>(CDRE->getDecl()))
3726 BlockDeclRefs.push_back(CDRE);
3727 return;
3728}
3729
3730void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3731 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3732 CI != E; ++CI)
3733 if (*CI) {
3734 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3735 GetBlockCallExprs(CBE->getBody());
3736 else
3737 GetBlockCallExprs(*CI);
3738 }
3739
3740 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3741 if (CE->getCallee()->getType()->isBlockPointerType()) {
3742 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3743 }
3744 }
3745 return;
3746}
3747
3748std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3749 // Navigate to relevant type information.
3750 const char *closureName = 0;
3751 const BlockPointerType *CPT = 0;
3752
3753 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3754 closureName = DRE->getDecl()->getName();
3755 CPT = DRE->getType()->getAsBlockPointerType();
3756 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3757 closureName = CDRE->getDecl()->getName();
3758 CPT = CDRE->getType()->getAsBlockPointerType();
3759 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3760 closureName = MExpr->getMemberDecl()->getName();
3761 CPT = MExpr->getType()->getAsBlockPointerType();
3762 } else {
3763 assert(1 && "RewriteBlockClass: Bad type");
3764 }
3765 assert(CPT && "RewriteBlockClass: Bad type");
3766 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3767 assert(FT && "RewriteBlockClass: Bad type");
3768 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3769 // FTP will be null for closures that don't take arguments.
3770
3771 // Build a closure call - start with a paren expr to enforce precedence.
3772 std::string BlockCall = "(";
3773
3774 // Synthesize the cast.
3775 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3776 BlockCall += "(struct __block_impl *";
3777 if (FTP) {
3778 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3779 E = FTP->arg_type_end(); I && (I != E); ++I)
3780 BlockCall += ", " + (*I).getAsString();
3781 }
3782 BlockCall += "))"; // close the argument list and paren expression.
3783
3784 // Invoke the closure. We need to cast it since the declaration type is
3785 // bogus (it's a function pointer type)
3786 BlockCall += "((struct __block_impl *)";
3787 std::string closureExprBufStr;
3788 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3789 Exp->getCallee()->printPretty(closureExprBuf);
3790 BlockCall += closureExprBuf.str();
3791 BlockCall += ")->FuncPtr)";
3792
3793 // Add the arguments.
3794 BlockCall += "((struct __block_impl *)";
3795 BlockCall += closureExprBuf.str();
3796 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3797 E = Exp->arg_end(); I != E; ++I) {
3798 std::string syncExprBufS;
3799 llvm::raw_string_ostream Buf(syncExprBufS);
3800 (*I)->printPretty(Buf);
3801 BlockCall += ", " + Buf.str();
3802 }
3803 return BlockCall;
3804}
3805
3806void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3807 std::string BlockCall = SynthesizeBlockCall(Exp);
3808
3809 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3810 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3811
3812 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3813 BlockCall.c_str(), BlockCall.size());
3814}
3815
3816void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3817 // FIXME: Add more elaborate code generation required by the ABI.
3818 InsertText(BDRE->getLocStart(), "*", 1);
3819}
3820
3821void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3822 SourceLocation LocStart = CE->getLocStart();
3823 SourceLocation LocEnd = CE->getLocEnd();
3824
3825 const char *startBuf = SM->getCharacterData(LocStart);
3826 const char *endBuf = SM->getCharacterData(LocEnd);
3827
3828 // advance the location to startArgList.
3829 const char *argPtr = startBuf;
3830
3831 while (*argPtr++ && (argPtr < endBuf)) {
3832 switch (*argPtr) {
3833 case '^':
3834 // Replace the '^' with '*'.
3835 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3836 ReplaceText(LocStart, 1, "*", 1);
3837 break;
3838 }
3839 }
3840 return;
3841}
3842
3843void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3844 SourceLocation DeclLoc = FD->getLocation();
3845 unsigned parenCount = 0;
3846
3847 // We have 1 or more arguments that have closure pointers.
3848 const char *startBuf = SM->getCharacterData(DeclLoc);
3849 const char *startArgList = strchr(startBuf, '(');
3850
3851 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3852
3853 parenCount++;
3854 // advance the location to startArgList.
3855 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3856 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3857
3858 const char *argPtr = startArgList;
3859
3860 while (*argPtr++ && parenCount) {
3861 switch (*argPtr) {
3862 case '^':
3863 // Replace the '^' with '*'.
3864 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3865 ReplaceText(DeclLoc, 1, "*", 1);
3866 break;
3867 case '(':
3868 parenCount++;
3869 break;
3870 case ')':
3871 parenCount--;
3872 break;
3873 }
3874 }
3875 return;
3876}
3877
3878bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3879 const FunctionTypeProto *FTP;
3880 const PointerType *PT = QT->getAsPointerType();
3881 if (PT) {
3882 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3883 } else {
3884 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3885 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3886 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3887 }
3888 if (FTP) {
3889 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3890 E = FTP->arg_type_end(); I != E; ++I)
3891 if (isBlockPointerType(*I))
3892 return true;
3893 }
3894 return false;
3895}
3896
3897void RewriteObjC::GetExtentOfArgList(const char *Name,
3898 const char *&LParen, const char *&RParen) {
3899 const char *argPtr = strchr(Name, '(');
3900 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3901
3902 LParen = argPtr; // output the start.
3903 argPtr++; // skip past the left paren.
3904 unsigned parenCount = 1;
3905
3906 while (*argPtr && parenCount) {
3907 switch (*argPtr) {
3908 case '(': parenCount++; break;
3909 case ')': parenCount--; break;
3910 default: break;
3911 }
3912 if (parenCount) argPtr++;
3913 }
3914 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3915 RParen = argPtr; // output the end
3916}
3917
3918void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3919 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3920 RewriteBlockPointerFunctionArgs(FD);
3921 return;
3922 }
3923 // Handle Variables and Typedefs.
3924 SourceLocation DeclLoc = ND->getLocation();
3925 QualType DeclT;
3926 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3927 DeclT = VD->getType();
3928 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3929 DeclT = TDD->getUnderlyingType();
3930 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3931 DeclT = FD->getType();
3932 else
3933 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3934
3935 const char *startBuf = SM->getCharacterData(DeclLoc);
3936 const char *endBuf = startBuf;
3937 // scan backward (from the decl location) for the end of the previous decl.
3938 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3939 startBuf--;
3940
3941 // *startBuf != '^' if we are dealing with a pointer to function that
3942 // may take block argument types (which will be handled below).
3943 if (*startBuf == '^') {
3944 // Replace the '^' with '*', computing a negative offset.
3945 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3946 ReplaceText(DeclLoc, 1, "*", 1);
3947 }
3948 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3949 // Replace the '^' with '*' for arguments.
3950 DeclLoc = ND->getLocation();
3951 startBuf = SM->getCharacterData(DeclLoc);
3952 const char *argListBegin, *argListEnd;
3953 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3954 while (argListBegin < argListEnd) {
3955 if (*argListBegin == '^') {
3956 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3957 ReplaceText(CaretLoc, 1, "*", 1);
3958 }
3959 argListBegin++;
3960 }
3961 }
3962 return;
3963}
3964
3965void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3966 // Add initializers for any closure decl refs.
3967 GetBlockDeclRefExprs(Exp->getBody());
3968 if (BlockDeclRefs.size()) {
3969 // Unique all "by copy" declarations.
3970 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3971 if (!BlockDeclRefs[i]->isByRef())
3972 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3973 // Unique all "by ref" declarations.
3974 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3975 if (BlockDeclRefs[i]->isByRef()) {
3976 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3977 }
3978 // Find any imported blocks...they will need special attention.
3979 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3980 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
3981 GetBlockCallExprs(Blocks[i]);
3982 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3983 }
3984 }
3985}
3986
3987std::string RewriteObjC::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
3988 Blocks.push_back(Exp);
3989
3990 CollectBlockDeclRefInfo(Exp);
3991 std::string FuncName;
3992
3993 if (CurFunctionDef)
3994 FuncName = std::string(CurFunctionDef->getName());
3995 else if (CurMethodDef) {
3996 FuncName = std::string(CurMethodDef->getSelector().getName());
3997 // Convert colons to underscores.
3998 std::string::size_type loc = 0;
3999 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4000 FuncName.replace(loc, 1, "_");
4001 } else if (VD)
4002 FuncName = std::string(VD->getName());
4003
4004 std::string BlockNumber = utostr(Blocks.size()-1);
4005
4006 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4007 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4008
4009 std::string FunkTypeStr;
4010
4011 // Get a pointer to the function type so we can cast appropriately.
4012 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
4013
4014 // Rewrite the closure block with a compound literal. The first cast is
4015 // to prevent warnings from the C compiler.
4016 std::string Init = "(" + FunkTypeStr;
4017
4018 Init += ")&" + Tag;
4019
4020 // Initialize the block function.
4021 Init += "((void*)" + Func;
4022
4023 if (ImportedBlockDecls.size()) {
4024 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
4025 Init += ",(void*)" + Buf;
4026 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
4027 Init += ",(void*)" + Buf;
4028 }
4029 // Add initializers for any closure decl refs.
4030 if (BlockDeclRefs.size()) {
4031 // Output all "by copy" declarations.
4032 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4033 E = BlockByCopyDecls.end(); I != E; ++I) {
4034 Init += ",";
4035 if (isObjCType((*I)->getType())) {
4036 Init += "[[";
4037 Init += (*I)->getName();
4038 Init += " retain] autorelease]";
4039 } else if (isBlockPointerType((*I)->getType())) {
4040 Init += "(void *)";
4041 Init += (*I)->getName();
4042 } else {
4043 Init += (*I)->getName();
4044 }
4045 }
4046 // Output all "by ref" declarations.
4047 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4048 E = BlockByRefDecls.end(); I != E; ++I) {
4049 Init += ",&";
4050 Init += (*I)->getName();
4051 }
4052 }
4053 Init += ")";
4054 BlockDeclRefs.clear();
4055 BlockByRefDecls.clear();
4056 BlockByCopyDecls.clear();
4057 ImportedBlockDecls.clear();
4058
4059 return Init;
4060}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004061