blob: 00604726fa3cb6f19145e671ff330c8450b86557 [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 Naroff54055232008-10-27 17:20:55 +0000459 // Blocks preamble.
460 Preamble += "#ifndef BLOCK_IMPL\n";
461 Preamble += "#define BLOCK_IMPL\n";
462 Preamble += "struct __block_impl {\n";
463 Preamble += " void *isa;\n";
464 Preamble += " int Flags;\n";
465 Preamble += " int Size;\n";
466 Preamble += " void *FuncPtr;\n";
467 Preamble += "};\n";
468 Preamble += "enum {\n";
469 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
470 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
471 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000472 Preamble += "// Runtime copy/destroy helper functions\n";
473 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
474 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
478 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
479 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000480 if (LangOpts.Microsoft) {
481 Preamble += "#undef __OBJC_RW_EXTERN\n";
482 Preamble += "#define __attribute__(X)\n";
483 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000484}
485
486
Chris Lattnerf04da132007-10-24 17:06:59 +0000487//===----------------------------------------------------------------------===//
488// Top Level Driver Code
489//===----------------------------------------------------------------------===//
490
Steve Naroffb29b4272008-04-14 22:03:09 +0000491void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000492 // Two cases: either the decl could be in the main file, or it could be in a
493 // #included file. If the former, rewrite it now. If the later, check to see
494 // if we rewrote the #include/#import.
495 SourceLocation Loc = D->getLocation();
496 Loc = SM->getLogicalLoc(Loc);
497
498 // If this is for a builtin, ignore it.
499 if (Loc.isInvalid()) return;
500
Steve Naroffebf2b562007-10-23 23:50:29 +0000501 // Look for built-in declarations that we need to refer during the rewrite.
502 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000503 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000504 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000505 // declared in <Foundation/NSString.h>
506 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
507 ConstantStringClassReference = FVD;
508 return;
509 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000510 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000511 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000512 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000513 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000515 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCForwardProtocolDecl *FP =
517 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000518 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000519 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000520 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000521 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000522 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000523}
524
Chris Lattnerf04da132007-10-24 17:06:59 +0000525/// HandleDeclInMainFile - This is called for each top-level decl defined in the
526/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000527void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Steve Naroff54055232008-10-27 17:20:55 +0000528 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
529 // Since function prototypes don't have ParmDecl's, we check the function
530 // prototype. This enables us to rewrite function declarations and
531 // definitions using the same code.
532 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
533
534 if (Stmt *Body = FD->getBody()) {
535 CurFunctionDef = FD;
Steve Narofff3473a72007-11-09 15:20:18 +0000536 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000537 // This synthesizes and inserts the block "impl" struct, invoke function,
538 // and any copy/dispose helper functions.
539 InsertBlockLiteralsWithinFunction(FD);
540 CurFunctionDef = 0;
541 }
542 return;
543 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000544 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000545 if (Stmt *Body = MD->getBody()) {
546 //Body->dump();
Steve Naroff54055232008-10-27 17:20:55 +0000547 CurMethodDef = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000548 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000549 InsertBlockLiteralsWithinMethod(MD);
550 CurMethodDef = 0;
Steve Naroff874e2322007-11-15 10:28:18 +0000551 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000552 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000554 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000555 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000556 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000557 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000558 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000559 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000560 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000561 if (VD->getInit())
562 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
563 }
Steve Naroff54055232008-10-27 17:20:55 +0000564 // Rewrite rules for blocks.
565 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
566 if (isBlockPointerType(VD->getType())) {
567 RewriteBlockPointerDecl(VD);
568 if (VD->getInit()) {
569 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
570 RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
571
572 // We've just rewritten the block body in place.
573 // Now we snarf the rewritten text and stash it away for later use.
574 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
575 RewrittenBlockExprs[CBE] = S;
576 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
577 // Do the rewrite, using S.size() which contains the rewritten size.
578 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
579 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
580 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
581 RewriteCastExpr(CE);
582 }
583 }
584 } else if (VD->getType()->isFunctionPointerType()) {
585 CheckFunctionPointerDecl(VD->getType(), VD);
586 if (VD->getInit()) {
587 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
588 RewriteCastExpr(CE);
589 }
590 }
591 }
592 return;
593 }
594 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
595 if (isBlockPointerType(TD->getUnderlyingType()))
596 RewriteBlockPointerDecl(TD);
597 else if (TD->getUnderlyingType()->isFunctionPointerType())
598 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
599 return;
600 }
601 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
602 if (RD->isDefinition()) {
603 for (RecordDecl::field_const_iterator i = RD->field_begin(),
604 e = RD->field_end(); i != e; ++i) {
605 FieldDecl *FD = *i;
606 if (isBlockPointerType(FD->getType()))
607 RewriteBlockPointerDecl(FD);
608 }
609 }
610 return;
611 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000612 // Nothing yet.
613}
614
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000615void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000616 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000617
618 // Rewrite tabs if we care.
619 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000620
Steve Naroffa7b402d2008-03-28 22:26:09 +0000621 if (Diags.hasErrorOccurred())
622 return;
623
624 // Create the output file.
625
Ted Kremeneka95d3752008-09-13 05:16:45 +0000626 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
627 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000628 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000629 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000630 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000631 std::string Err;
632 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
633 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000634 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000635 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000636 } else {
637 llvm::sys::Path Path(InFileName);
638 Path.eraseSuffix();
639 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000640 std::string Err;
641 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
642 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000643 }
644
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000645 RewriteInclude();
646
Steve Naroffba92b2e2008-03-27 22:29:16 +0000647 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
648 Preamble.c_str(), Preamble.size(), false);
649
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000650 // Rewrite Objective-c meta data*
651 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000652 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000653
Chris Lattnerf04da132007-10-24 17:06:59 +0000654 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
655 // we are done.
656 if (const RewriteBuffer *RewriteBuf =
657 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000658 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000659 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000660 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000661 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000662 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000663 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000664 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000665 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000666}
667
Chris Lattnerf04da132007-10-24 17:06:59 +0000668//===----------------------------------------------------------------------===//
669// Syntactic (non-AST) Rewriting Code
670//===----------------------------------------------------------------------===//
671
Steve Naroffb29b4272008-04-14 22:03:09 +0000672void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000673 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
674 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
675 const char *MainBufStart = MainBuf.first;
676 const char *MainBufEnd = MainBuf.second;
677 size_t ImportLen = strlen("import");
678 size_t IncludeLen = strlen("include");
679
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000680 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000681 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
682 if (*BufPtr == '#') {
683 if (++BufPtr == MainBufEnd)
684 return;
685 while (*BufPtr == ' ' || *BufPtr == '\t')
686 if (++BufPtr == MainBufEnd)
687 return;
688 if (!strncmp(BufPtr, "import", ImportLen)) {
689 // replace import with include
690 SourceLocation ImportLoc =
691 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000692 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000693 BufPtr += ImportLen;
694 }
695 }
696 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000697}
698
Steve Naroffb29b4272008-04-14 22:03:09 +0000699void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
701 const char *MainBufStart = MainBuf.first;
702 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000703
Chris Lattnerf04da132007-10-24 17:06:59 +0000704 // Loop over the whole file, looking for tabs.
705 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
706 if (*BufPtr != '\t')
707 continue;
708
709 // Okay, we found a tab. This tab will turn into at least one character,
710 // but it depends on which 'virtual column' it is in. Compute that now.
711 unsigned VCol = 0;
712 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
713 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
714 ++VCol;
715
716 // Okay, now that we know the virtual column, we know how many spaces to
717 // insert. We assume 8-character tab-stops.
718 unsigned Spaces = 8-(VCol & 7);
719
720 // Get the location of the tab.
721 SourceLocation TabLoc =
722 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
723
724 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000725 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000727}
728
729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000733
734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
746 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
749 typedefString += ForwardDecl->getName();
750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
752 typedefString += ForwardDecl->getName();
753 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000755 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000757 }
758
759 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
761 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000767
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000768 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Chris Lattner55d13b42008-03-16 21:23:50 +0000778 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000780 SourceLocation Loc = Property->getLocation();
781
Chris Lattneraadaf782008-01-31 19:51:04 +0000782 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783
784 // FIXME: handle properties that are declared across multiple lines.
785 }
786}
787
Steve Naroffb29b4272008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000793
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000795 E = CatDecl->instmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->classmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
800
Steve Naroff423cb562007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000803}
804
Steve Naroffb29b4272008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807
Steve Naroff752d6ef2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000814 E = PDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Naroff752d6ef2007-10-30 16:42:30 +0000820 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000821 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000822 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000823
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 // Must comment out @optional/@required
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
827 for (const char *p = startBuf; p < endBuf; p++) {
828 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
829 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@optional"),
832 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000833
834 }
835 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
836 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@required"),
839 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000840
841 }
842 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000843}
844
Steve Naroffb29b4272008-04-14 22:03:09 +0000845void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000846 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000847 if (LocStart.isInvalid())
848 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851}
852
Steve Naroffb29b4272008-04-14 22:03:09 +0000853void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000855 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000858 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 else if (OMD->getResultType()->isFunctionPointerType()) {
860 // needs special handling, since pointer-to-functions have special
861 // syntax (where a decaration models use).
862 QualType retType = OMD->getResultType();
863 if (const PointerType* PT = retType->getAsPointerType()) {
864 QualType PointeeTy = PT->getPointeeType();
865 if ((FPRetType = PointeeTy->getAsFunctionType())) {
866 ResultStr += FPRetType->getResultType().getAsString();
867 ResultStr += "(*";
868 }
869 }
870 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000871 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000872 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000873
874 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000875 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000876
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000877 if (OMD->isInstance())
878 NameStr += "_I_";
879 else
880 NameStr += "_C_";
881
882 NameStr += OMD->getClassInterface()->getName();
883 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
885 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000886 if (ObjCCategoryImplDecl *CID =
887 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += CID->getName();
889 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000890 }
Steve Naroff563b8282008-04-04 22:23:44 +0000891 // Append selector names, replacing ':' with '_'
892 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 else {
895 std::string selString = OMD->getSelector().getName();
896 int len = selString.size();
897 for (int i = 0; i < len; i++)
898 if (selString[i] == ':')
899 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000900 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 // Remember this name for metadata emission
903 MethodInternalNames[OMD] = NameStr;
904 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905
906 // Rewrite arguments
907 ResultStr += "(";
908
909 // invisible arguments
910 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000911 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000912 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000913 if (!LangOpts.Microsoft) {
914 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
915 ResultStr += "struct ";
916 }
917 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000918 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000919 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000920 }
921 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000922 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923
924 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000925 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ResultStr += " _cmd";
927
928 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000929 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ParmVarDecl *PDecl = OMD->getParamDecl(i);
931 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000932 if (PDecl->getType()->isObjCQualifiedIdType()) {
933 ResultStr += "id ";
934 ResultStr += PDecl->getName();
935 } else {
936 std::string Name = PDecl->getName();
937 PDecl->getType().getAsStringInternal(Name);
938 ResultStr += Name;
939 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000941 if (OMD->isVariadic())
942 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000943 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944
Steve Naroff76e429d2008-07-16 14:40:40 +0000945 if (FPRetType) {
946 ResultStr += ")"; // close the precedence "scope" for "*".
947
948 // Now, emit the argument types (if any).
949 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
950 ResultStr += "(";
951 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
952 if (i) ResultStr += ", ";
953 std::string ParamStr = FT->getArgType(i).getAsString();
954 ResultStr += ParamStr;
955 }
956 if (FT->isVariadic()) {
957 if (FT->getNumArgs()) ResultStr += ", ";
958 ResultStr += "...";
959 }
960 ResultStr += ")";
961 } else {
962 ResultStr += "()";
963 }
964 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000965}
Steve Naroffb29b4272008-04-14 22:03:09 +0000966void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
968 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000970 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000971 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000972 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000973 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000976 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
977 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 ObjCMethodDecl *OMD = *I;
980 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000981 SourceLocation LocStart = OMD->getLocStart();
982 SourceLocation LocEnd = OMD->getBody()->getLocStart();
983
984 const char *startBuf = SM->getCharacterData(LocStart);
985 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000986 ReplaceText(LocStart, endBuf-startBuf,
987 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 }
989
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000991 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
992 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 ObjCMethodDecl *OMD = *I;
995 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 SourceLocation LocStart = OMD->getLocStart();
997 SourceLocation LocEnd = OMD->getBody()->getLocStart();
998
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(LocStart, endBuf-startBuf,
1002 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001004 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001005 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001006 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001007 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008}
1009
Steve Naroffb29b4272008-04-14 22:03:09 +00001010void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001011 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001013 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001014 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +00001015 ResultStr += ClassDecl->getName();
1016 ResultStr += "\n";
1017 ResultStr += "#define _REWRITER_typedef_";
1018 ResultStr += ClassDecl->getName();
1019 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001020 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001021 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +00001022 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001023 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001024 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001025 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001027
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001028 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1029 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001031 E = ClassDecl->instmeth_end(); I != E; ++I)
1032 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001034 E = ClassDecl->classmeth_end(); I != E; ++I)
1035 RewriteMethodDeclaration(*I);
1036
Steve Naroff2feac5e2007-10-30 03:43:13 +00001037 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001038 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001039}
1040
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001041Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1042 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001044 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001045 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001046 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1047 // lookup which class implements the instance variable.
1048 ObjCInterfaceDecl *clsDeclared = 0;
1049 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1050 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1051
1052 // Synthesize an explicit cast to gain access to the ivar.
1053 std::string RecName = clsDeclared->getIdentifier()->getName();
1054 RecName += "_IMPL";
1055 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001057 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001058 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1059 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor49badde2008-10-27 19:41:14 +00001060 CastExpr *castExpr = new ExplicitCCastExpr(castT, IV->getBase(), castT,
1061 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001062 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001063 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1064 IV->getBase()->getLocEnd(),
1065 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001066 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001067 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001068 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1069 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001070 ReplaceStmt(IV, ME);
1071 delete IV;
1072 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001073 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001074
1075 ReplaceStmt(IV->getBase(), PE);
1076 // Cannot delete IV->getBase(), since PE points to it.
1077 // Replace the old base with the cast. This is important when doing
1078 // embedded rewrites. For example, [newInv->_container addObject:0].
1079 IV->setBase(PE);
1080 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001081 }
Steve Naroff84472a82008-04-18 21:55:08 +00001082 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001083 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1084
1085 // Explicit ivar refs need to have a cast inserted.
1086 // FIXME: consider sharing some of this code with the code above.
1087 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001088 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001089 // lookup which class implements the instance variable.
1090 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001091 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001092 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1093
1094 // Synthesize an explicit cast to gain access to the ivar.
1095 std::string RecName = clsDeclared->getIdentifier()->getName();
1096 RecName += "_IMPL";
1097 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001098 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001099 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001100 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1101 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor49badde2008-10-27 19:41:14 +00001102 CastExpr *castExpr = new ExplicitCCastExpr(castT, IV->getBase(), castT,
1103 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001104 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001105 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1106 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001107 ReplaceStmt(IV->getBase(), PE);
1108 // Cannot delete IV->getBase(), since PE points to it.
1109 // Replace the old base with the cast. This is important when doing
1110 // embedded rewrites. For example, [newInv->_container addObject:0].
1111 IV->setBase(PE);
1112 return IV;
1113 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001114 }
Steve Naroff84472a82008-04-18 21:55:08 +00001115 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001116}
1117
Chris Lattnerf04da132007-10-24 17:06:59 +00001118//===----------------------------------------------------------------------===//
1119// Function Body / Expression rewriting
1120//===----------------------------------------------------------------------===//
1121
Steve Naroffb29b4272008-04-14 22:03:09 +00001122Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001123 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1124 isa<DoStmt>(S) || isa<ForStmt>(S))
1125 Stmts.push_back(S);
1126 else if (isa<ObjCForCollectionStmt>(S)) {
1127 Stmts.push_back(S);
1128 ObjCBcLabelNo.push_back(++BcLabelCount);
1129 }
1130
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001131 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +00001132
1133 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +00001134 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1135 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +00001136 if (*CI) {
Steve Naroffa48396e2008-10-27 18:50:14 +00001137 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
1138 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
1139 if (newStmt)
1140 *CI = newStmt;
1141
1142 // We've just rewritten the block body in place.
1143 // Now we snarf the rewritten text and stash it away for later use.
1144 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1145 RewrittenBlockExprs[CBE] = S;
1146 std::string Init = SynthesizeBlockInitExpr(CBE);
1147 // Do the rewrite, using S.size() which contains the rewritten size.
1148 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1149 } else {
1150 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
1151 if (newStmt)
1152 *CI = newStmt;
1153 }
Steve Naroff75730982007-11-07 04:08:17 +00001154 }
Steve Naroffebf2b562007-10-23 23:50:29 +00001155
1156 // Handle specific things.
1157 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
1158 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001159
1160 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001161 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +00001162
1163 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
1164 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +00001165
Steve Naroffbeaf2992007-11-03 11:27:19 +00001166 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
1167 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +00001168
Steve Naroff934f2762007-10-24 22:48:43 +00001169 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
1170 // Before we rewrite it, put the original message expression in a comment.
1171 SourceLocation startLoc = MessExpr->getLocStart();
1172 SourceLocation endLoc = MessExpr->getLocEnd();
1173
1174 const char *startBuf = SM->getCharacterData(startLoc);
1175 const char *endBuf = SM->getCharacterData(endLoc);
1176
1177 std::string messString;
1178 messString += "// ";
1179 messString.append(startBuf, endBuf-startBuf+1);
1180 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +00001181
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001182 // FIXME: Missing definition of
1183 // InsertText(clang::SourceLocation, char const*, unsigned int).
1184 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001185 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001186 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001187 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001188 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001189
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1191 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001192
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001193 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1194 return RewriteObjCSynchronizedStmt(StmtTry);
1195
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1197 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001198
1199 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1200 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001201
1202 if (ObjCForCollectionStmt *StmtForCollection =
1203 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001204 return RewriteObjCForCollectionStmt(StmtForCollection,
1205 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001206 if (BreakStmt *StmtBreakStmt =
1207 dyn_cast<BreakStmt>(S))
1208 return RewriteBreakStmt(StmtBreakStmt);
1209 if (ContinueStmt *StmtContinueStmt =
1210 dyn_cast<ContinueStmt>(S))
1211 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001212
Ted Kremenekab9bae72008-10-06 22:45:07 +00001213 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1214 // and cast exprs.
1215 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1216 // FIXME: What we're doing here is modifying the type-specifier that
1217 // precedes the first Decl. In the future the DeclGroup should have
1218 // a separate type-specifier that we can rewrite.
1219 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Steve Naroff54055232008-10-27 17:20:55 +00001220
1221 // Blocks rewrite rules.
1222 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1223 DI != DE; ++DI) {
1224
1225 ScopedDecl *SD = *DI;
1226 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1227 if (isBlockPointerType(ND->getType()))
1228 RewriteBlockPointerDecl(ND);
1229 else if (ND->getType()->isFunctionPointerType())
1230 CheckFunctionPointerDecl(ND->getType(), ND);
1231 }
1232 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1233 if (isBlockPointerType(TD->getUnderlyingType()))
1234 RewriteBlockPointerDecl(TD);
1235 else if (TD->getUnderlyingType()->isFunctionPointerType())
1236 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
1237 }
1238 }
Ted Kremenekab9bae72008-10-06 22:45:07 +00001239 }
1240
Douglas Gregor49badde2008-10-27 19:41:14 +00001241 if (ExplicitCCastExpr *CE = dyn_cast<ExplicitCCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001242 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001243
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1245 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1246 assert(!Stmts.empty() && "Statement stack is empty");
1247 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1248 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1249 && "Statement stack mismatch");
1250 Stmts.pop_back();
1251 }
Steve Naroff54055232008-10-27 17:20:55 +00001252 // Handle blocks rewriting.
1253 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1254 if (BDRE->isByRef())
1255 RewriteBlockDeclRefExpr(BDRE);
1256 }
1257 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1258 if (CE->getCallee()->getType()->isBlockPointerType())
1259 RewriteBlockCall(CE);
1260 }
1261 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1262 RewriteCastExpr(CE);
1263 }
Steve Naroff874e2322007-11-15 10:28:18 +00001264#if 0
1265 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1266 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1267 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001268 std::string SStr;
1269 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001270 Replacement->printPretty(Buf);
1271 const std::string &Str = Buf.str();
1272
1273 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001274 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001275 delete S;
1276 return Replacement;
1277 }
1278#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001279 // Return this stmt unmodified.
1280 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001281}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001283/// SynthCountByEnumWithState - To print:
1284/// ((unsigned int (*)
1285/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1286/// (void *)objc_msgSend)((id)l_collection,
1287/// sel_registerName(
1288/// "countByEnumeratingWithState:objects:count:"),
1289/// &enumState,
1290/// (id *)items, (unsigned int)16)
1291///
Steve Naroffb29b4272008-04-14 22:03:09 +00001292void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001293 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1294 "id *, unsigned int))(void *)objc_msgSend)";
1295 buf += "\n\t\t";
1296 buf += "((id)l_collection,\n\t\t";
1297 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1298 buf += "\n\t\t";
1299 buf += "&enumState, "
1300 "(id *)items, (unsigned int)16)";
1301}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001302
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001303/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1304/// statement to exit to its outer synthesized loop.
1305///
Steve Naroffb29b4272008-04-14 22:03:09 +00001306Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001307 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1308 return S;
1309 // replace break with goto __break_label
1310 std::string buf;
1311
1312 SourceLocation startLoc = S->getLocStart();
1313 buf = "goto __break_label_";
1314 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001315 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001316
1317 return 0;
1318}
1319
1320/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1321/// statement to continue with its inner synthesized loop.
1322///
Steve Naroffb29b4272008-04-14 22:03:09 +00001323Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001324 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1325 return S;
1326 // replace continue with goto __continue_label
1327 std::string buf;
1328
1329 SourceLocation startLoc = S->getLocStart();
1330 buf = "goto __continue_label_";
1331 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001332 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001333
1334 return 0;
1335}
1336
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001337/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001338/// It rewrites:
1339/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001340
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001341/// Into:
1342/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001343/// type elem;
1344/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001345/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346/// id l_collection = (id)collection;
1347/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1348/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// if (limit) {
1350/// unsigned long startMutations = *enumState.mutationsPtr;
1351/// do {
1352/// unsigned long counter = 0;
1353/// do {
1354/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001355/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001356/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001357/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001358/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001359/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1361/// objects:items count:16]);
1362/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001363/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001364/// }
1365/// else
1366/// elem = nil;
1367/// }
1368///
Steve Naroffb29b4272008-04-14 22:03:09 +00001369Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001370 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001371 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1372 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1373 "ObjCForCollectionStmt Statement stack mismatch");
1374 assert(!ObjCBcLabelNo.empty() &&
1375 "ObjCForCollectionStmt - Label No stack empty");
1376
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001380 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 std::string buf;
1382 buf = "\n{\n\t";
1383 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1384 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001385 ScopedDecl* D = DS->getSolitaryDecl();
1386 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001387 elementTypeAsString = ElementType.getAsString();
1388 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001390 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001391 buf += elementName;
1392 buf += ";\n\t";
1393 }
Chris Lattner06767512008-04-08 05:52:18 +00001394 else {
1395 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001397 elementTypeAsString
1398 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001399 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001400
1401 // struct __objcFastEnumerationState enumState = { 0 };
1402 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1403 // id items[16];
1404 buf += "id items[16];\n\t";
1405 // id l_collection = (id)
1406 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001407 // Find start location of 'collection' the hard way!
1408 const char *startCollectionBuf = startBuf;
1409 startCollectionBuf += 3; // skip 'for'
1410 startCollectionBuf = strchr(startCollectionBuf, '(');
1411 startCollectionBuf++; // skip '('
1412 // find 'in' and skip it.
1413 while (*startCollectionBuf != ' ' ||
1414 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1415 (*(startCollectionBuf+3) != ' ' &&
1416 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1417 startCollectionBuf++;
1418 startCollectionBuf += 3;
1419
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001421 ReplaceText(startLoc, startCollectionBuf - startBuf,
1422 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001424 SourceLocation rightParenLoc = S->getRParenLoc();
1425 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1426 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 buf = ";\n\t";
1428
1429 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1430 // objects:items count:16];
1431 // which is synthesized into:
1432 // unsigned int limit =
1433 // ((unsigned int (*)
1434 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1435 // (void *)objc_msgSend)((id)l_collection,
1436 // sel_registerName(
1437 // "countByEnumeratingWithState:objects:count:"),
1438 // (struct __objcFastEnumerationState *)&state,
1439 // (id *)items, (unsigned int)16);
1440 buf += "unsigned long limit =\n\t\t";
1441 SynthCountByEnumWithState(buf);
1442 buf += ";\n\t";
1443 /// if (limit) {
1444 /// unsigned long startMutations = *enumState.mutationsPtr;
1445 /// do {
1446 /// unsigned long counter = 0;
1447 /// do {
1448 /// if (startMutations != *enumState.mutationsPtr)
1449 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001450 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001451 buf += "if (limit) {\n\t";
1452 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1453 buf += "do {\n\t\t";
1454 buf += "unsigned long counter = 0;\n\t\t";
1455 buf += "do {\n\t\t\t";
1456 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1457 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1458 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001459 buf += " = (";
1460 buf += elementTypeAsString;
1461 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001463 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 /// } while (counter < limit);
1467 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1468 /// objects:items count:16]);
1469 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001470 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 /// }
1472 /// else
1473 /// elem = nil;
1474 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001475 ///
1476 buf = ";\n\t";
1477 buf += "__continue_label_";
1478 buf += utostr(ObjCBcLabelNo.back());
1479 buf += ": ;";
1480 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 buf += "} while (counter < limit);\n\t";
1482 buf += "} while (limit = ";
1483 SynthCountByEnumWithState(buf);
1484 buf += ");\n\t";
1485 buf += elementName;
1486 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487 buf += "__break_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
1489 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490 buf += "}\n\t";
1491 buf += "else\n\t\t";
1492 buf += elementName;
1493 buf += " = nil;\n";
1494 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001495
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001497 if (isa<CompoundStmt>(S->getBody())) {
1498 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1499 InsertText(endBodyLoc, buf.c_str(), buf.size());
1500 } else {
1501 /* Need to treat single statements specially. For example:
1502 *
1503 * for (A *a in b) if (stuff()) break;
1504 * for (A *a in b) xxxyy;
1505 *
1506 * The following code simply scans ahead to the semi to find the actual end.
1507 */
1508 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1509 const char *semiBuf = strchr(stmtBuf, ';');
1510 assert(semiBuf && "Can't find ';'");
1511 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1512 InsertText(endBodyLoc, buf.c_str(), buf.size());
1513 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001514 Stmts.pop_back();
1515 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001517}
1518
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001519/// RewriteObjCSynchronizedStmt -
1520/// This routine rewrites @synchronized(expr) stmt;
1521/// into:
1522/// objc_sync_enter(expr);
1523/// @try stmt @finally { objc_sync_exit(expr); }
1524///
Steve Naroffb29b4272008-04-14 22:03:09 +00001525Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001526 // Get the start location and compute the semi location.
1527 SourceLocation startLoc = S->getLocStart();
1528 const char *startBuf = SM->getCharacterData(startLoc);
1529
1530 assert((*startBuf == '@') && "bogus @synchronized location");
1531
1532 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001533 buf = "objc_sync_enter((id)";
1534 const char *lparenBuf = startBuf;
1535 while (*lparenBuf != '(') lparenBuf++;
1536 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001537 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1538 // the sync expression is typically a message expression that's already
1539 // been rewritten! (which implies the SourceLocation's are invalid).
1540 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001541 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001542 while (*endBuf != ')') endBuf--;
1543 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001544 buf = ");\n";
1545 // declare a new scope with two variables, _stack and _rethrow.
1546 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1547 buf += "int buf[18/*32-bit i386*/];\n";
1548 buf += "char *pointers[4];} _stack;\n";
1549 buf += "id volatile _rethrow = 0;\n";
1550 buf += "objc_exception_try_enter(&_stack);\n";
1551 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001552 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001553 startLoc = S->getSynchBody()->getLocEnd();
1554 startBuf = SM->getCharacterData(startLoc);
1555
Steve Naroffc7089f12008-08-19 13:04:19 +00001556 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001557 SourceLocation lastCurlyLoc = startLoc;
1558 buf = "}\nelse {\n";
1559 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1560 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001561 buf += " objc_sync_exit(";
Douglas Gregor49badde2008-10-27 19:41:14 +00001562 Expr *syncExpr = new ExplicitCCastExpr(Context->getObjCIdType(),
1563 S->getSynchExpr(),
1564 Context->getObjCIdType(),
1565 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001566 std::string syncExprBufS;
1567 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001568 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001569 buf += syncExprBuf.str();
1570 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001571 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1572 buf += "}\n";
1573 buf += "}";
1574
Chris Lattneraadaf782008-01-31 19:51:04 +00001575 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001576 return 0;
1577}
1578
Steve Naroffb29b4272008-04-14 22:03:09 +00001579Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001580 // Get the start location and compute the semi location.
1581 SourceLocation startLoc = S->getLocStart();
1582 const char *startBuf = SM->getCharacterData(startLoc);
1583
1584 assert((*startBuf == '@') && "bogus @try location");
1585
1586 std::string buf;
1587 // declare a new scope with two variables, _stack and _rethrow.
1588 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1589 buf += "int buf[18/*32-bit i386*/];\n";
1590 buf += "char *pointers[4];} _stack;\n";
1591 buf += "id volatile _rethrow = 0;\n";
1592 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001593 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001594
Chris Lattneraadaf782008-01-31 19:51:04 +00001595 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001596
1597 startLoc = S->getTryBody()->getLocEnd();
1598 startBuf = SM->getCharacterData(startLoc);
1599
1600 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001601
Steve Naroff75730982007-11-07 04:08:17 +00001602 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001603 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1604 if (catchList) {
1605 startLoc = startLoc.getFileLocWithOffset(1);
1606 buf = " /* @catch begin */ else {\n";
1607 buf += " id _caught = objc_exception_extract(&_stack);\n";
1608 buf += " objc_exception_try_enter (&_stack);\n";
1609 buf += " if (_setjmp(_stack.buf))\n";
1610 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1611 buf += " else { /* @catch continue */";
1612
1613 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001614 } else { /* no catch list */
1615 buf = "}\nelse {\n";
1616 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1617 buf += "}";
1618 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001619 }
Steve Naroff75730982007-11-07 04:08:17 +00001620 bool sawIdTypedCatch = false;
1621 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001622 while (catchList) {
1623 Stmt *catchStmt = catchList->getCatchParamStmt();
1624
1625 if (catchList == S->getCatchStmts())
1626 buf = "if ("; // we are generating code for the first catch clause
1627 else
1628 buf = "else if (";
1629 startLoc = catchList->getLocStart();
1630 startBuf = SM->getCharacterData(startLoc);
1631
1632 assert((*startBuf == '@') && "bogus @catch location");
1633
1634 const char *lParenLoc = strchr(startBuf, '(');
1635
Steve Naroffbe4b3332008-02-01 22:08:12 +00001636 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001637 // Now rewrite the body...
1638 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001639 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1640 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001641 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1642 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001643 assert((*bodyBuf == '{') && "bogus @catch body location");
1644
1645 buf += "1) { id _tmp = _caught;";
1646 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1647 buf.c_str(), buf.size());
1648 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001649 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001650 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001651 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001652 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001653 sawIdTypedCatch = true;
1654 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001655 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001656
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001657 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001658 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001659 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001660 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001661 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001662 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001663 }
1664 }
1665 // Now rewrite the body...
1666 lastCatchBody = catchList->getCatchBody();
1667 SourceLocation rParenLoc = catchList->getRParenLoc();
1668 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1669 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1670 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1671 assert((*rParenBuf == ')') && "bogus @catch paren location");
1672 assert((*bodyBuf == '{') && "bogus @catch body location");
1673
1674 buf = " = _caught;";
1675 // Here we replace ") {" with "= _caught;" (which initializes and
1676 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001677 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001678 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001679 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001680 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001681 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001682 catchList = catchList->getNextCatchStmt();
1683 }
1684 // Complete the catch list...
1685 if (lastCatchBody) {
1686 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001687 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1688 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001689
Steve Naroff378f47a2008-09-11 15:29:03 +00001690 // Insert the last (implicit) else clause *before* the right curly brace.
1691 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1692 buf = "} /* last catch end */\n";
1693 buf += "else {\n";
1694 buf += " _rethrow = _caught;\n";
1695 buf += " objc_exception_try_exit(&_stack);\n";
1696 buf += "} } /* @catch end */\n";
1697 if (!S->getFinallyStmt())
1698 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001699 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001700
1701 // Set lastCurlyLoc
1702 lastCurlyLoc = lastCatchBody->getLocEnd();
1703 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001704 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001705 startLoc = finalStmt->getLocStart();
1706 startBuf = SM->getCharacterData(startLoc);
1707 assert((*startBuf == '@') && "bogus @finally start");
1708
1709 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001710 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001711
1712 Stmt *body = finalStmt->getFinallyBody();
1713 SourceLocation startLoc = body->getLocStart();
1714 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001715 assert(*SM->getCharacterData(startLoc) == '{' &&
1716 "bogus @finally body location");
1717 assert(*SM->getCharacterData(endLoc) == '}' &&
1718 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001719
1720 startLoc = startLoc.getFileLocWithOffset(1);
1721 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001722 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001723 endLoc = endLoc.getFileLocWithOffset(-1);
1724 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001725 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001726
1727 // Set lastCurlyLoc
1728 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001729 } else { /* no finally clause - make sure we synthesize an implicit one */
1730 buf = "{ /* implicit finally clause */\n";
1731 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1732 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1733 buf += "}";
1734 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001735 }
1736 // Now emit the final closing curly brace...
1737 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1738 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001739 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001740 return 0;
1741}
1742
Steve Naroffb29b4272008-04-14 22:03:09 +00001743Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001744 return 0;
1745}
1746
Steve Naroffb29b4272008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001748 return 0;
1749}
1750
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001751// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001752// the throw expression is typically a message expression that's already
1753// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001754Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001755 // Get the start location and compute the semi location.
1756 SourceLocation startLoc = S->getLocStart();
1757 const char *startBuf = SM->getCharacterData(startLoc);
1758
1759 assert((*startBuf == '@') && "bogus @throw location");
1760
1761 std::string buf;
1762 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001763 if (S->getThrowExpr())
1764 buf = "objc_exception_throw(";
1765 else // add an implicit argument
1766 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001767
1768 // handle "@ throw" correctly.
1769 const char *wBuf = strchr(startBuf, 'w');
1770 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1771 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1772
Steve Naroff2bd03922007-11-07 15:32:26 +00001773 const char *semiBuf = strchr(startBuf, ';');
1774 assert((*semiBuf == ';') && "@throw: can't find ';'");
1775 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1776 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001777 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001778 return 0;
1779}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001780
Steve Naroffb29b4272008-04-14 22:03:09 +00001781Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001782 // Create a new string expression.
1783 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001784 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001785 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001786 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1787 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001788 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001789 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001790
Chris Lattner07506182007-11-30 22:53:43 +00001791 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001792 delete Exp;
1793 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001794}
1795
Steve Naroffb29b4272008-04-14 22:03:09 +00001796Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001797 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1798 // Create a call to sel_registerName("selName").
1799 llvm::SmallVector<Expr*, 8> SelExprs;
1800 QualType argType = Context->getPointerType(Context->CharTy);
1801 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1802 Exp->getSelector().getName().size(),
1803 false, argType, SourceLocation(),
1804 SourceLocation()));
1805 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1806 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001807 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001808 delete Exp;
1809 return SelExp;
1810}
1811
Steve Naroffb29b4272008-04-14 22:03:09 +00001812CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001813 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001814 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001815 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001816
1817 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001818 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001819
1820 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001821 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001822 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1823
1824 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001825
Steve Naroff934f2762007-10-24 22:48:43 +00001826 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1827}
1828
Steve Naroffd5255f52007-11-01 13:24:47 +00001829static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1830 const char *&startRef, const char *&endRef) {
1831 while (startBuf < endBuf) {
1832 if (*startBuf == '<')
1833 startRef = startBuf; // mark the start.
1834 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001835 if (startRef && *startRef == '<') {
1836 endRef = startBuf; // mark the end.
1837 return true;
1838 }
1839 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001840 }
1841 startBuf++;
1842 }
1843 return false;
1844}
1845
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001846static void scanToNextArgument(const char *&argRef) {
1847 int angle = 0;
1848 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1849 if (*argRef == '<')
1850 angle++;
1851 else if (*argRef == '>')
1852 angle--;
1853 argRef++;
1854 }
1855 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1856}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001857
Steve Naroffb29b4272008-04-14 22:03:09 +00001858bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001859
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001860 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001861 return true;
1862
Steve Naroffd5255f52007-11-01 13:24:47 +00001863 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001864 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001865 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001866 return true; // we have "Class <Protocol> *".
1867 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001868 return false;
1869}
1870
Steve Naroff4f95b752008-07-29 18:15:38 +00001871void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1872 QualType Type = E->getType();
1873 if (needToScanForQualifiers(Type)) {
1874 SourceLocation Loc = E->getLocStart();
1875 const char *startBuf = SM->getCharacterData(Loc);
1876 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1877 const char *startRef = 0, *endRef = 0;
1878 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1879 // Get the locations of the startRef, endRef.
1880 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1881 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1882 // Comment out the protocol references.
1883 InsertText(LessLoc, "/*", 2);
1884 InsertText(GreaterLoc, "*/", 2);
1885 }
1886 }
1887}
1888
Steve Naroffb29b4272008-04-14 22:03:09 +00001889void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001890 SourceLocation Loc;
1891 QualType Type;
1892 const FunctionTypeProto *proto = 0;
1893 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1894 Loc = VD->getLocation();
1895 Type = VD->getType();
1896 }
1897 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1898 Loc = FD->getLocation();
1899 // Check for ObjC 'id' and class types that have been adorned with protocol
1900 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1901 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1902 assert(funcType && "missing function type");
1903 proto = dyn_cast<FunctionTypeProto>(funcType);
1904 if (!proto)
1905 return;
1906 Type = proto->getResultType();
1907 }
1908 else
1909 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001910
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001911 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001912 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001913
1914 const char *endBuf = SM->getCharacterData(Loc);
1915 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001916 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001917 startBuf--; // scan backward (from the decl location) for return type.
1918 const char *startRef = 0, *endRef = 0;
1919 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1920 // Get the locations of the startRef, endRef.
1921 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1922 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1923 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001924 InsertText(LessLoc, "/*", 2);
1925 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001926 }
1927 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001928 if (!proto)
1929 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001930 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001931 const char *startBuf = SM->getCharacterData(Loc);
1932 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001933 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1934 if (needToScanForQualifiers(proto->getArgType(i))) {
1935 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001936
Steve Naroffd5255f52007-11-01 13:24:47 +00001937 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001938 // scan forward (from the decl location) for argument types.
1939 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001940 const char *startRef = 0, *endRef = 0;
1941 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1942 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001943 SourceLocation LessLoc =
1944 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1945 SourceLocation GreaterLoc =
1946 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001947 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001948 InsertText(LessLoc, "/*", 2);
1949 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001950 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001951 startBuf = ++endBuf;
1952 }
1953 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001954 // If the function name is derived from a macro expansion, then the
1955 // argument buffer will not follow the name. Need to speak with Chris.
1956 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001957 startBuf++; // scan forward (from the decl location) for argument types.
1958 startBuf++;
1959 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001960 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001961}
1962
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001963// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001964void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001965 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1966 llvm::SmallVector<QualType, 16> ArgTys;
1967 ArgTys.push_back(Context->getPointerType(
1968 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001970 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001971 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001972 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001973 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001974 SelGetUidIdent, getFuncType,
1975 FunctionDecl::Extern, false, 0);
1976}
1977
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001978// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001979void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001980 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1981 llvm::SmallVector<QualType, 16> ArgTys;
1982 ArgTys.push_back(Context->getPointerType(
1983 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001985 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001986 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001987 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001988 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001989 SelGetProtoIdent, getFuncType,
1990 FunctionDecl::Extern, false, 0);
1991}
1992
Steve Naroffb29b4272008-04-14 22:03:09 +00001993void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001994 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001995 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001996 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001997 return;
1998 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001999 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002000}
2001
Steve Naroffc0a123c2008-03-11 17:37:02 +00002002// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002003void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002004 if (SuperContructorFunctionDecl)
2005 return;
2006 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
2007 llvm::SmallVector<QualType, 16> ArgTys;
2008 QualType argT = Context->getObjCIdType();
2009 assert(!argT.isNull() && "Can't find 'id' type");
2010 ArgTys.push_back(argT);
2011 ArgTys.push_back(argT);
2012 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2013 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002014 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002015 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002016 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002017 msgSendIdent, msgSendType,
2018 FunctionDecl::Extern, false, 0);
2019}
2020
Steve Naroff09b266e2007-10-30 23:14:51 +00002021// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002022void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002023 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2024 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002025 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002026 assert(!argT.isNull() && "Can't find 'id' type");
2027 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002028 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002029 assert(!argT.isNull() && "Can't find 'SEL' type");
2030 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002032 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002033 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002034 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002035 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002036 msgSendIdent, msgSendType,
2037 FunctionDecl::Extern, false, 0);
2038}
2039
Steve Naroff874e2322007-11-15 10:28:18 +00002040// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002041void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002042 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2043 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002044 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002045 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002046 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002047 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2048 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2049 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002050 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002051 assert(!argT.isNull() && "Can't find 'SEL' type");
2052 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002053 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002054 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002055 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002056 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002057 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002058 msgSendIdent, msgSendType,
2059 FunctionDecl::Extern, false, 0);
2060}
2061
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002063void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2065 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002066 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067 assert(!argT.isNull() && "Can't find 'id' type");
2068 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002069 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002070 assert(!argT.isNull() && "Can't find 'SEL' type");
2071 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002072 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002073 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002074 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002075 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002076 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002077 msgSendIdent, msgSendType,
2078 FunctionDecl::Extern, false, 0);
2079}
2080
2081// SynthMsgSendSuperStretFunctionDecl -
2082// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002083void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002084 IdentifierInfo *msgSendIdent =
2085 &Context->Idents.get("objc_msgSendSuper_stret");
2086 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002087 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002088 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002089 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002090 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2091 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2092 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002094 assert(!argT.isNull() && "Can't find 'SEL' type");
2095 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002096 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002097 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002098 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002099 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002100 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002101 msgSendIdent, msgSendType,
2102 FunctionDecl::Extern, false, 0);
2103}
2104
Steve Naroff1284db82008-05-08 22:02:18 +00002105// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002106void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002107 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2108 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002109 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002110 assert(!argT.isNull() && "Can't find 'id' type");
2111 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002112 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002113 assert(!argT.isNull() && "Can't find 'SEL' type");
2114 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002115 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002116 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002117 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002118 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002119 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002120 msgSendIdent, msgSendType,
2121 FunctionDecl::Extern, false, 0);
2122}
2123
Steve Naroff09b266e2007-10-30 23:14:51 +00002124// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002125void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002126 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2127 llvm::SmallVector<QualType, 16> ArgTys;
2128 ArgTys.push_back(Context->getPointerType(
2129 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002130 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002131 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002132 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002133 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002134 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002135 getClassIdent, getClassType,
2136 FunctionDecl::Extern, false, 0);
2137}
2138
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002139// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002140void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002141 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2142 llvm::SmallVector<QualType, 16> ArgTys;
2143 ArgTys.push_back(Context->getPointerType(
2144 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002145 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002146 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002147 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002148 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002149 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002150 getClassIdent, getClassType,
2151 FunctionDecl::Extern, false, 0);
2152}
2153
Steve Naroffb29b4272008-04-14 22:03:09 +00002154Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002155 QualType strType = getConstantStringStructType();
2156
2157 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002158
2159 std::string tmpName = InFileName;
2160 unsigned i;
2161 for (i=0; i < tmpName.length(); i++) {
2162 char c = tmpName.at(i);
2163 // replace any non alphanumeric characters with '_'.
2164 if (!isalpha(c) && (c < '0' || c > '9'))
2165 tmpName[i] = '_';
2166 }
2167 S += tmpName;
2168 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002169 S += utostr(NumObjCStringLiterals++);
2170
Steve Naroffba92b2e2008-03-27 22:29:16 +00002171 Preamble += "static __NSConstantStringImpl " + S;
2172 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2173 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002174 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002175 std::string prettyBufS;
2176 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002177 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002178 Preamble += prettyBuf.str();
2179 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002180 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002181 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002182
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002183 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002184 &Context->Idents.get(S.c_str()), strType,
2185 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002186 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2187 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2188 Context->getPointerType(DRE->getType()),
2189 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002190 // cast to NSConstantString *
Douglas Gregor49badde2008-10-27 19:41:14 +00002191 CastExpr *cast = new ExplicitCCastExpr(Exp->getType(), Unop,
2192 Exp->getType(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002193 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002194 delete Exp;
2195 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002196}
2197
Steve Naroffb29b4272008-04-14 22:03:09 +00002198ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002199 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002200 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002201
Chris Lattnerd9f69102008-08-10 01:53:14 +00002202 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
2203 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002204 const PointerType *PT = PDE->getType()->getAsPointerType();
2205 assert(PT);
2206 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2207 return IT->getDecl();
2208 }
2209 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002210}
2211
2212// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002213QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002214 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002215 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002216 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002217 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002218 QualType FieldTypes[2];
2219
2220 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002221 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002222 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002224 // Create fields
2225 FieldDecl *FieldDecls[2];
2226
2227 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002228 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002229 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002230
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002231 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002232 }
2233 return Context->getTagDeclType(SuperStructDecl);
2234}
2235
Steve Naroffb29b4272008-04-14 22:03:09 +00002236QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002237 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002238 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002239 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002240 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002241 QualType FieldTypes[4];
2242
2243 // struct objc_object *receiver;
2244 FieldTypes[0] = Context->getObjCIdType();
2245 // int flags;
2246 FieldTypes[1] = Context->IntTy;
2247 // char *str;
2248 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2249 // long length;
2250 FieldTypes[3] = Context->LongTy;
2251 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002252 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002253
2254 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002255 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002256 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002257
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002258 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002259 }
2260 return Context->getTagDeclType(ConstantStringDecl);
2261}
2262
Steve Naroffb29b4272008-04-14 22:03:09 +00002263Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002264 if (!SelGetUidFunctionDecl)
2265 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002266 if (!MsgSendFunctionDecl)
2267 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002268 if (!MsgSendSuperFunctionDecl)
2269 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002270 if (!MsgSendStretFunctionDecl)
2271 SynthMsgSendStretFunctionDecl();
2272 if (!MsgSendSuperStretFunctionDecl)
2273 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002274 if (!MsgSendFpretFunctionDecl)
2275 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 if (!GetClassFunctionDecl)
2277 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002278 if (!GetMetaClassFunctionDecl)
2279 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002280
Steve Naroff874e2322007-11-15 10:28:18 +00002281 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002282 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2283 // May need to use objc_msgSend_stret() as well.
2284 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002285 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002286 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002287 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002288 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002289 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002290 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002291 }
Steve Naroff874e2322007-11-15 10:28:18 +00002292
Steve Naroff934f2762007-10-24 22:48:43 +00002293 // Synthesize a call to objc_msgSend().
2294 llvm::SmallVector<Expr*, 8> MsgExprs;
2295 IdentifierInfo *clsName = Exp->getClassName();
2296
2297 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2298 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002299 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2300 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002301 if (!strcmp(clsName->getName(), "super")) {
2302 MsgSendFlavor = MsgSendSuperFunctionDecl;
2303 if (MsgSendStretFlavor)
2304 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2305 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2306
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002307 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002308 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002309
2310 llvm::SmallVector<Expr*, 4> InitExprs;
2311
2312 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002313 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002314 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002315 Context->getObjCIdType(),
2316 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002317 llvm::SmallVector<Expr*, 8> ClsExprs;
2318 QualType argType = Context->getPointerType(Context->CharTy);
2319 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2320 SuperDecl->getIdentifier()->getLength(),
2321 false, argType, SourceLocation(),
2322 SourceLocation()));
2323 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2324 &ClsExprs[0],
2325 ClsExprs.size());
2326 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002327 InitExprs.push_back( // set 'super class', using objc_getClass().
2328 new ExplicitCCastExpr(Context->getObjCIdType(),
2329 Cls, Context->getObjCIdType(),
2330 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002331 // struct objc_super
2332 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002333 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002334
Steve Naroff23f41272008-03-11 18:14:26 +00002335 if (LangOpts.Microsoft) {
2336 SynthSuperContructorFunctionDecl();
2337 // Simulate a contructor call...
2338 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2339 superType, SourceLocation());
2340 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2341 superType, SourceLocation());
2342 } else {
2343 // (struct objc_super) { <exprs from above> }
2344 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2345 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002346 SourceLocation(), false);
2347 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2348 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002349 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002350 // struct objc_super *
2351 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2352 Context->getPointerType(SuperRep->getType()),
2353 SourceLocation());
2354 MsgExprs.push_back(Unop);
2355 } else {
2356 llvm::SmallVector<Expr*, 8> ClsExprs;
2357 QualType argType = Context->getPointerType(Context->CharTy);
2358 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2359 clsName->getLength(),
2360 false, argType, SourceLocation(),
2361 SourceLocation()));
2362 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2363 &ClsExprs[0],
2364 ClsExprs.size());
2365 MsgExprs.push_back(Cls);
2366 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002367 } else { // instance message.
2368 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002369
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002371 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002372 if (MsgSendStretFlavor)
2373 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002374 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2375
2376 llvm::SmallVector<Expr*, 4> InitExprs;
2377
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002378 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002379 new ExplicitCCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002380 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002381 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002382 SourceLocation()),
2383 Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002384 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002385
2386 llvm::SmallVector<Expr*, 8> ClsExprs;
2387 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002388 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2389 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002390 false, argType, SourceLocation(),
2391 SourceLocation()));
2392 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002393 &ClsExprs[0],
2394 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002395 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002396 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002397 // set 'super class', using objc_getClass().
2398 new ExplicitCCastExpr(Context->getObjCIdType(),
2399 Cls, Context->getObjCIdType(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002400 // struct objc_super
2401 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002402 Expr *SuperRep;
2403
2404 if (LangOpts.Microsoft) {
2405 SynthSuperContructorFunctionDecl();
2406 // Simulate a contructor call...
2407 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2408 superType, SourceLocation());
2409 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2410 superType, SourceLocation());
2411 } else {
2412 // (struct objc_super) { <exprs from above> }
2413 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2414 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002415 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002416 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2417 }
Steve Naroff874e2322007-11-15 10:28:18 +00002418 // struct objc_super *
2419 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2420 Context->getPointerType(SuperRep->getType()),
2421 SourceLocation());
2422 MsgExprs.push_back(Unop);
2423 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002424 // Remove all type-casts because it may contain objc-style types; e.g.
2425 // Foo<Proto> *.
Douglas Gregor49badde2008-10-27 19:41:14 +00002426 while (ExplicitCCastExpr *CE = dyn_cast<ExplicitCCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002427 recExpr = CE->getSubExpr();
Douglas Gregor49badde2008-10-27 19:41:14 +00002428 recExpr = new ExplicitCCastExpr(Context->getObjCIdType(), recExpr,
2429 Context->getObjCIdType(),
2430 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002431 MsgExprs.push_back(recExpr);
2432 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002433 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002434 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002435 llvm::SmallVector<Expr*, 8> SelExprs;
2436 QualType argType = Context->getPointerType(Context->CharTy);
2437 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2438 Exp->getSelector().getName().size(),
2439 false, argType, SourceLocation(),
2440 SourceLocation()));
2441 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2442 &SelExprs[0], SelExprs.size());
2443 MsgExprs.push_back(SelExp);
2444
2445 // Now push any user supplied arguments.
2446 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002447 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002448 // Make all implicit casts explicit...ICE comes in handy:-)
2449 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2450 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002451 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002453 : ICE->getType();
2454 userExpr = new ExplicitCCastExpr(type, userExpr, type, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002455 }
2456 // Make id<P...> cast into an 'id' cast.
Douglas Gregor49badde2008-10-27 19:41:14 +00002457 else if (ExplicitCCastExpr *CE = dyn_cast<ExplicitCCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +00002459 while ((CE = dyn_cast<ExplicitCCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002460 userExpr = CE->getSubExpr();
Douglas Gregor49badde2008-10-27 19:41:14 +00002461 userExpr = new ExplicitCCastExpr(Context->getObjCIdType(),
2462 userExpr, Context->getObjCIdType(),
2463 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002464 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002465 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002466 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002467 // We've transferred the ownership to MsgExprs. Null out the argument in
2468 // the original expression, since we will delete it below.
2469 Exp->setArg(i, 0);
2470 }
Steve Naroffab972d32007-11-04 22:37:50 +00002471 // Generate the funky cast.
2472 CastExpr *cast;
2473 llvm::SmallVector<QualType, 8> ArgTypes;
2474 QualType returnType;
2475
2476 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002477 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2478 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2479 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002480 ArgTypes.push_back(Context->getObjCIdType());
2481 ArgTypes.push_back(Context->getObjCSelType());
2482 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002483 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002484 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002485 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2486 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002487 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002488 ArgTypes.push_back(t);
2489 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002490 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2491 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002492 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002494 }
2495 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002496 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002497
2498 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002499 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2500 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002501
2502 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2503 // If we don't do this cast, we get the following bizarre warning/note:
2504 // xx.m:13: warning: function called through a non-compatible type
2505 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor49badde2008-10-27 19:41:14 +00002506 cast = new ExplicitCCastExpr(Context->getPointerType(Context->VoidTy), DRE,
2507 Context->getPointerType(Context->VoidTy),
2508 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002509
Steve Naroffab972d32007-11-04 22:37:50 +00002510 // Now do the "normal" pointer to function cast.
2511 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002512 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002513 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002514 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002515 castType = Context->getPointerType(castType);
Douglas Gregor49badde2008-10-27 19:41:14 +00002516 cast = new ExplicitCCastExpr(castType, cast, castType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002517
2518 // Don't forget the parens to enforce the proper binding.
2519 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2520
2521 const FunctionType *FT = msgSendType->getAsFunctionType();
2522 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2523 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002524 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002525 if (MsgSendStretFlavor) {
2526 // We have the method which returns a struct/union. Must also generate
2527 // call to objc_msgSend_stret and hang both varieties on a conditional
2528 // expression which dictate which one to envoke depending on size of
2529 // method's return type.
2530
2531 // Create a reference to the objc_msgSend_stret() declaration.
2532 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2533 SourceLocation());
2534 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor49badde2008-10-27 19:41:14 +00002535 cast = new ExplicitCCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2536 Context->getPointerType(Context->VoidTy),
2537 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002538 // Now do the "normal" pointer to function cast.
2539 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002540 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002541 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 castType = Context->getPointerType(castType);
Douglas Gregor49badde2008-10-27 19:41:14 +00002543 cast = new ExplicitCCastExpr(castType, cast, castType, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544
2545 // Don't forget the parens to enforce the proper binding.
2546 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2547
2548 FT = msgSendType->getAsFunctionType();
2549 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2550 FT->getResultType(), SourceLocation());
2551
2552 // Build sizeof(returnType)
2553 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2554 returnType, Context->getSizeType(),
2555 SourceLocation(), SourceLocation());
2556 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2557 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2558 // For X86 it is more complicated and some kind of target specific routine
2559 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002560 unsigned IntSize =
2561 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2563 Context->IntTy,
2564 SourceLocation());
2565 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2566 BinaryOperator::LE,
2567 Context->IntTy,
2568 SourceLocation());
2569 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2570 ConditionalOperator *CondExpr =
2571 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002572 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002573 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002574 return ReplacingStmt;
2575}
2576
Steve Naroffb29b4272008-04-14 22:03:09 +00002577Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002578 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002579 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002580 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002581
Chris Lattnere64b7772007-10-24 16:57:36 +00002582 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002583 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002584}
2585
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002586/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2587/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002588Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002589 if (!GetProtocolFunctionDecl)
2590 SynthGetProtocolFunctionDecl();
2591 // Create a call to objc_getProtocol("ProtocolName").
2592 llvm::SmallVector<Expr*, 8> ProtoExprs;
2593 QualType argType = Context->getPointerType(Context->CharTy);
2594 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2595 strlen(Exp->getProtocol()->getName()),
2596 false, argType, SourceLocation(),
2597 SourceLocation()));
2598 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2599 &ProtoExprs[0],
2600 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002601 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002602 delete Exp;
2603 return ProtoExp;
2604
2605}
2606
Steve Naroffbaf58c32008-05-31 14:15:04 +00002607bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2608 const char *endBuf) {
2609 while (startBuf < endBuf) {
2610 if (*startBuf == '#') {
2611 // Skip whitespace.
2612 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2613 ;
2614 if (!strncmp(startBuf, "if", strlen("if")) ||
2615 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2616 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2617 !strncmp(startBuf, "define", strlen("define")) ||
2618 !strncmp(startBuf, "undef", strlen("undef")) ||
2619 !strncmp(startBuf, "else", strlen("else")) ||
2620 !strncmp(startBuf, "elif", strlen("elif")) ||
2621 !strncmp(startBuf, "endif", strlen("endif")) ||
2622 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2623 !strncmp(startBuf, "include", strlen("include")) ||
2624 !strncmp(startBuf, "import", strlen("import")) ||
2625 !strncmp(startBuf, "include_next", strlen("include_next")))
2626 return true;
2627 }
2628 startBuf++;
2629 }
2630 return false;
2631}
2632
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002633/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002634/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002635void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002636 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002637 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2638 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002639 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002640 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002641 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002642 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002643 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002644 SourceLocation LocStart = CDecl->getLocStart();
2645 SourceLocation LocEnd = CDecl->getLocEnd();
2646
2647 const char *startBuf = SM->getCharacterData(LocStart);
2648 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002649
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002650 // If no ivars and no root or if its root, directly or indirectly,
2651 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002652 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2653 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002654 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002655 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002656 return;
2657 }
2658
2659 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002660 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002661 Result += "\nstruct ";
2662 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002663 if (LangOpts.Microsoft)
2664 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002665
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002666 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002667 const char *cursor = strchr(startBuf, '{');
2668 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002669 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002670 // If the buffer contains preprocessor directives, we do more fine-grained
2671 // rewrites. This is intended to fix code that looks like (which occurs in
2672 // NSURL.h, for example):
2673 //
2674 // #ifdef XYZ
2675 // @interface Foo : NSObject
2676 // #else
2677 // @interface FooBar : NSObject
2678 // #endif
2679 // {
2680 // int i;
2681 // }
2682 // @end
2683 //
2684 // This clause is segregated to avoid breaking the common case.
2685 if (BufferContainsPPDirectives(startBuf, cursor)) {
2686 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2687 CDecl->getClassLoc();
2688 const char *endHeader = SM->getCharacterData(L);
2689 endHeader += Lexer::MeasureTokenLength(L, *SM);
2690
Chris Lattner3db6cae2008-07-21 18:19:38 +00002691 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002692 // advance to the end of the referenced protocols.
2693 while (endHeader < cursor && *endHeader != '>') endHeader++;
2694 endHeader++;
2695 }
2696 // rewrite the original header
2697 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2698 } else {
2699 // rewrite the original header *without* disturbing the '{'
2700 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2701 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002702 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002703 Result = "\n struct ";
2704 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002705 Result += "_IMPL ";
2706 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002707 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002708
2709 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002710 SourceLocation OnePastCurly =
2711 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2712 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002713 }
2714 cursor++; // past '{'
2715
2716 // Now comment out any visibility specifiers.
2717 while (cursor < endBuf) {
2718 if (*cursor == '@') {
2719 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002720 // Skip whitespace.
2721 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2722 /*scan*/;
2723
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002724 // FIXME: presence of @public, etc. inside comment results in
2725 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002726 if (!strncmp(cursor, "public", strlen("public")) ||
2727 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002728 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002729 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002730 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002731 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002732 // FIXME: If there are cases where '<' is used in ivar declaration part
2733 // of user code, then scan the ivar list and use needToScanForQualifiers
2734 // for type checking.
2735 else if (*cursor == '<') {
2736 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002737 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002738 cursor = strchr(cursor, '>');
2739 cursor++;
2740 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002741 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002742 }
Steve Narofffea763e82007-11-14 19:25:57 +00002743 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002744 }
Steve Narofffea763e82007-11-14 19:25:57 +00002745 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002746 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002747 } else { // we don't have any instance variables - insert super struct.
2748 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2749 Result += " {\n struct ";
2750 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002751 Result += "_IMPL ";
2752 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002753 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002754 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002755 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002756 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002757 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002758 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002759}
2760
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002761// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002762/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002763void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002764 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002765 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002766 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002767 const char *ClassName,
2768 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002769 if (MethodBegin == MethodEnd) return;
2770
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002771 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002772 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002773 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002774 SEL _cmd;
2775 char *method_types;
2776 void *_imp;
2777 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002778 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002779 Result += "\nstruct _objc_method {\n";
2780 Result += "\tSEL _cmd;\n";
2781 Result += "\tchar *method_types;\n";
2782 Result += "\tvoid *_imp;\n";
2783 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002784
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002785 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002786 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002787
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002788 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002789
2790 /* struct {
2791 struct _objc_method_list *next_method;
2792 int method_count;
2793 struct _objc_method method_list[];
2794 }
2795 */
2796 Result += "\nstatic struct {\n";
2797 Result += "\tstruct _objc_method_list *next_method;\n";
2798 Result += "\tint method_count;\n";
2799 Result += "\tstruct _objc_method method_list[";
2800 Result += utostr(MethodEnd-MethodBegin);
2801 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002802 Result += prefix;
2803 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2804 Result += "_METHODS_";
2805 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002806 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002807 Result += IsInstanceMethod ? "inst" : "cls";
2808 Result += "_meth\")))= ";
2809 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002811 Result += "\t,{{(SEL)\"";
2812 Result += (*MethodBegin)->getSelector().getName().c_str();
2813 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002814 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002815 Result += "\", \"";
2816 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002817 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002818 Result += MethodInternalNames[*MethodBegin];
2819 Result += "}\n";
2820 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2821 Result += "\t ,{(SEL)\"";
2822 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002823 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002825 Result += "\", \"";
2826 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002827 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002828 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002829 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002830 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002831 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002832}
2833
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002835void RewriteObjC::
2836RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2837 const char *prefix,
2838 const char *ClassName,
2839 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002840 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002841 if (Protocols.empty()) return;
2842
2843 for (unsigned i = 0; i != Protocols.size(); i++) {
2844 ObjCProtocolDecl *PDecl = Protocols[i];
2845 // Output struct protocol_methods holder of method selector and type.
2846 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2847 /* struct protocol_methods {
2848 SEL _cmd;
2849 char *method_types;
2850 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002851 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002852 Result += "\nstruct protocol_methods {\n";
2853 Result += "\tSEL _cmd;\n";
2854 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002856
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002857 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002858 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002859 // Do not synthesize the protocol more than once.
2860 if (ObjCSynthesizedProtocols.count(PDecl))
2861 continue;
2862
2863 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2864 unsigned NumMethods = PDecl->getNumInstanceMethods();
2865 /* struct _objc_protocol_method_list {
2866 int protocol_method_count;
2867 struct protocol_methods protocols[];
2868 }
2869 */
2870 Result += "\nstatic struct {\n";
2871 Result += "\tint protocol_method_count;\n";
2872 Result += "\tstruct protocol_methods protocols[";
2873 Result += utostr(NumMethods);
2874 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2875 Result += PDecl->getName();
2876 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2877 "{\n\t" + utostr(NumMethods) + "\n";
2878
2879 // Output instance methods declared in this protocol.
2880 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2881 E = PDecl->instmeth_end(); I != E; ++I) {
2882 if (I == PDecl->instmeth_begin())
2883 Result += "\t ,{{(SEL)\"";
2884 else
2885 Result += "\t ,{(SEL)\"";
2886 Result += (*I)->getSelector().getName().c_str();
2887 std::string MethodTypeString;
2888 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2889 Result += "\", \"";
2890 Result += MethodTypeString;
2891 Result += "\"}\n";
2892 }
2893 Result += "\t }\n};\n";
2894 }
2895
2896 // Output class methods declared in this protocol.
2897 int NumMethods = PDecl->getNumClassMethods();
2898 if (NumMethods > 0) {
2899 /* struct _objc_protocol_method_list {
2900 int protocol_method_count;
2901 struct protocol_methods protocols[];
2902 }
2903 */
2904 Result += "\nstatic struct {\n";
2905 Result += "\tint protocol_method_count;\n";
2906 Result += "\tstruct protocol_methods protocols[";
2907 Result += utostr(NumMethods);
2908 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2909 Result += PDecl->getName();
2910 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2911 "{\n\t";
2912 Result += utostr(NumMethods);
2913 Result += "\n";
2914
2915 // Output instance methods declared in this protocol.
2916 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2917 E = PDecl->classmeth_end(); I != E; ++I) {
2918 if (I == PDecl->classmeth_begin())
2919 Result += "\t ,{{(SEL)\"";
2920 else
2921 Result += "\t ,{(SEL)\"";
2922 Result += (*I)->getSelector().getName().c_str();
2923 std::string MethodTypeString;
2924 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2925 Result += "\", \"";
2926 Result += MethodTypeString;
2927 Result += "\"}\n";
2928 }
2929 Result += "\t }\n};\n";
2930 }
2931
2932 // Output:
2933 /* struct _objc_protocol {
2934 // Objective-C 1.0 extensions
2935 struct _objc_protocol_extension *isa;
2936 char *protocol_name;
2937 struct _objc_protocol **protocol_list;
2938 struct _objc_protocol_method_list *instance_methods;
2939 struct _objc_protocol_method_list *class_methods;
2940 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002941 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002942 static bool objc_protocol = false;
2943 if (!objc_protocol) {
2944 Result += "\nstruct _objc_protocol {\n";
2945 Result += "\tstruct _objc_protocol_extension *isa;\n";
2946 Result += "\tchar *protocol_name;\n";
2947 Result += "\tstruct _objc_protocol **protocol_list;\n";
2948 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2949 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2950 Result += "};\n";
2951
2952 objc_protocol = true;
2953 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002954
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002955 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2956 Result += PDecl->getName();
2957 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2958 "{\n\t0, \"";
2959 Result += PDecl->getName();
2960 Result += "\", 0, ";
2961 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2962 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2963 Result += PDecl->getName();
2964 Result += ", ";
2965 }
2966 else
2967 Result += "0, ";
2968 if (PDecl->getNumClassMethods() > 0) {
2969 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2970 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002971 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002972 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002973 else
2974 Result += "0\n";
2975 Result += "};\n";
2976
2977 // Mark this protocol as having been generated.
2978 if (!ObjCSynthesizedProtocols.insert(PDecl))
2979 assert(false && "protocol already synthesized");
2980 }
2981 // Output the top lovel protocol meta-data for the class.
2982 /* struct _objc_protocol_list {
2983 struct _objc_protocol_list *next;
2984 int protocol_count;
2985 struct _objc_protocol *class_protocols[];
2986 }
2987 */
2988 Result += "\nstatic struct {\n";
2989 Result += "\tstruct _objc_protocol_list *next;\n";
2990 Result += "\tint protocol_count;\n";
2991 Result += "\tstruct _objc_protocol *class_protocols[";
2992 Result += utostr(Protocols.size());
2993 Result += "];\n} _OBJC_";
2994 Result += prefix;
2995 Result += "_PROTOCOLS_";
2996 Result += ClassName;
2997 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2998 "{\n\t0, ";
2999 Result += utostr(Protocols.size());
3000 Result += "\n";
3001
3002 Result += "\t,{&_OBJC_PROTOCOL_";
3003 Result += Protocols[0]->getName();
3004 Result += " \n";
3005
3006 for (unsigned i = 1; i != Protocols.size(); i++) {
3007 Result += "\t ,&_OBJC_PROTOCOL_";
3008 Result += Protocols[i]->getName();
3009 Result += "\n";
3010 }
3011 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003012}
3013
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003014/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003015/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003016void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003017 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003018 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003021 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3022 CDecl = CDecl->getNextClassCategory())
3023 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3024 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003025
Chris Lattnereb44eee2007-12-23 01:40:15 +00003026 std::string FullCategoryName = ClassDecl->getName();
3027 FullCategoryName += '_';
3028 FullCategoryName += IDecl->getName();
3029
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003030 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003031 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003032 true, "CATEGORY_", FullCategoryName.c_str(),
3033 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003034
3035 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003036 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003037 false, "CATEGORY_", FullCategoryName.c_str(),
3038 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003039
3040 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003041 // Null CDecl is case of a category implementation with no category interface
3042 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003043 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003044 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003045
3046 /* struct _objc_category {
3047 char *category_name;
3048 char *class_name;
3049 struct _objc_method_list *instance_methods;
3050 struct _objc_method_list *class_methods;
3051 struct _objc_protocol_list *protocols;
3052 // Objective-C 1.0 extensions
3053 uint32_t size; // sizeof (struct _objc_category)
3054 struct _objc_property_list *instance_properties; // category's own
3055 // @property decl.
3056 };
3057 */
3058
3059 static bool objc_category = false;
3060 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += "\nstruct _objc_category {\n";
3062 Result += "\tchar *category_name;\n";
3063 Result += "\tchar *class_name;\n";
3064 Result += "\tstruct _objc_method_list *instance_methods;\n";
3065 Result += "\tstruct _objc_method_list *class_methods;\n";
3066 Result += "\tstruct _objc_protocol_list *protocols;\n";
3067 Result += "\tunsigned int size;\n";
3068 Result += "\tstruct _objc_property_list *instance_properties;\n";
3069 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003070 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003071 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3073 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003074 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003075 Result += IDecl->getName();
3076 Result += "\"\n\t, \"";
3077 Result += ClassDecl->getName();
3078 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003079
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 if (IDecl->getNumInstanceMethods() > 0) {
3081 Result += "\t, (struct _objc_method_list *)"
3082 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3083 Result += FullCategoryName;
3084 Result += "\n";
3085 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003086 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003087 Result += "\t, 0\n";
3088 if (IDecl->getNumClassMethods() > 0) {
3089 Result += "\t, (struct _objc_method_list *)"
3090 "&_OBJC_CATEGORY_CLASS_METHODS_";
3091 Result += FullCategoryName;
3092 Result += "\n";
3093 }
3094 else
3095 Result += "\t, 0\n";
3096
Chris Lattner780f3292008-07-21 21:32:27 +00003097 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003098 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3099 Result += FullCategoryName;
3100 Result += "\n";
3101 }
3102 else
3103 Result += "\t, 0\n";
3104 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003105}
3106
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003107/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3108/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003109void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003110 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003111 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003112 if (ivar->isBitField()) {
3113 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3114 // place all bitfields at offset 0.
3115 Result += "0";
3116 } else {
3117 Result += "__OFFSETOFIVAR__(struct ";
3118 Result += IDecl->getName();
3119 if (LangOpts.Microsoft)
3120 Result += "_IMPL";
3121 Result += ", ";
3122 Result += ivar->getName();
3123 Result += ")";
3124 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003125}
3126
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003127//===----------------------------------------------------------------------===//
3128// Meta Data Emission
3129//===----------------------------------------------------------------------===//
3130
Steve Naroffb29b4272008-04-14 22:03:09 +00003131void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003132 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003133 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003134
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003135 // Explictly declared @interface's are already synthesized.
3136 if (CDecl->ImplicitInterfaceDecl()) {
3137 // FIXME: Implementation of a class with no @interface (legacy) doese not
3138 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003139 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003140 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003141
Chris Lattnerbe6df082007-12-12 07:56:42 +00003142 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003143 unsigned NumIvars = !IDecl->ivar_empty()
3144 ? IDecl->ivar_size()
3145 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003146 if (NumIvars > 0) {
3147 static bool objc_ivar = false;
3148 if (!objc_ivar) {
3149 /* struct _objc_ivar {
3150 char *ivar_name;
3151 char *ivar_type;
3152 int ivar_offset;
3153 };
3154 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 Result += "\nstruct _objc_ivar {\n";
3156 Result += "\tchar *ivar_name;\n";
3157 Result += "\tchar *ivar_type;\n";
3158 Result += "\tint ivar_offset;\n";
3159 Result += "};\n";
3160
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003161 objc_ivar = true;
3162 }
3163
Steve Naroff946a6932008-03-11 00:12:29 +00003164 /* struct {
3165 int ivar_count;
3166 struct _objc_ivar ivar_list[nIvars];
3167 };
3168 */
3169 Result += "\nstatic struct {\n";
3170 Result += "\tint ivar_count;\n";
3171 Result += "\tstruct _objc_ivar ivar_list[";
3172 Result += utostr(NumIvars);
3173 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003174 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003175 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 "{\n\t";
3177 Result += utostr(NumIvars);
3178 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003179
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003180 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003181 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003182 IVI = IDecl->ivar_begin();
3183 IVE = IDecl->ivar_end();
3184 } else {
3185 IVI = CDecl->ivar_begin();
3186 IVE = CDecl->ivar_end();
3187 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003188 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003189 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003190 Result += "\", \"";
3191 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003192 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003193 Result += StrEncoding;
3194 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003195 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003196 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003197 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003199 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003200 Result += "\", \"";
3201 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003202 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003203 Result += StrEncoding;
3204 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003205 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003206 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 }
3208
3209 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003210 }
3211
3212 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003213 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003214 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003215
3216 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003218 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003220 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003221 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003222 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003223
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003224
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003225 // Declaration of class/meta-class metadata
3226 /* struct _objc_class {
3227 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003228 const char *super_class_name;
3229 char *name;
3230 long version;
3231 long info;
3232 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003233 struct _objc_ivar_list *ivars;
3234 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003235 struct objc_cache *cache;
3236 struct objc_protocol_list *protocols;
3237 const char *ivar_layout;
3238 struct _objc_class_ext *ext;
3239 };
3240 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003241 static bool objc_class = false;
3242 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003243 Result += "\nstruct _objc_class {\n";
3244 Result += "\tstruct _objc_class *isa;\n";
3245 Result += "\tconst char *super_class_name;\n";
3246 Result += "\tchar *name;\n";
3247 Result += "\tlong version;\n";
3248 Result += "\tlong info;\n";
3249 Result += "\tlong instance_size;\n";
3250 Result += "\tstruct _objc_ivar_list *ivars;\n";
3251 Result += "\tstruct _objc_method_list *methods;\n";
3252 Result += "\tstruct objc_cache *cache;\n";
3253 Result += "\tstruct _objc_protocol_list *protocols;\n";
3254 Result += "\tconst char *ivar_layout;\n";
3255 Result += "\tstruct _objc_class_ext *ext;\n";
3256 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003257 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003258 }
3259
3260 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003261 ObjCInterfaceDecl *RootClass = 0;
3262 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003263 while (SuperClass) {
3264 RootClass = SuperClass;
3265 SuperClass = SuperClass->getSuperClass();
3266 }
3267 SuperClass = CDecl->getSuperClass();
3268
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003269 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3270 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003271 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003272 "{\n\t(struct _objc_class *)\"";
3273 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3274 Result += "\"";
3275
3276 if (SuperClass) {
3277 Result += ", \"";
3278 Result += SuperClass->getName();
3279 Result += "\", \"";
3280 Result += CDecl->getName();
3281 Result += "\"";
3282 }
3283 else {
3284 Result += ", 0, \"";
3285 Result += CDecl->getName();
3286 Result += "\"";
3287 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003288 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003289 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003290 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003291 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003292 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003293 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003294 Result += "\n";
3295 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003296 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003297 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003298 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003299 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += CDecl->getName();
3301 Result += ",0,0\n";
3302 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003303 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003304 Result += "\t,0,0,0,0\n";
3305 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003306
3307 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003308 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3309 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003310 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003311 "{\n\t&_OBJC_METACLASS_";
3312 Result += CDecl->getName();
3313 if (SuperClass) {
3314 Result += ", \"";
3315 Result += SuperClass->getName();
3316 Result += "\", \"";
3317 Result += CDecl->getName();
3318 Result += "\"";
3319 }
3320 else {
3321 Result += ", 0, \"";
3322 Result += CDecl->getName();
3323 Result += "\"";
3324 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003325 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003326 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003327 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003328 Result += ",0";
3329 else {
3330 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003331 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003332 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003333 if (LangOpts.Microsoft)
3334 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003335 Result += ")";
3336 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003337 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003338 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += CDecl->getName();
3340 Result += "\n\t";
3341 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003342 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003343 Result += ",0";
3344 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003345 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003346 Result += CDecl->getName();
3347 Result += ", 0\n\t";
3348 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003349 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003351 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003352 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003353 Result += CDecl->getName();
3354 Result += ", 0,0\n";
3355 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003356 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003357 Result += ",0,0,0\n";
3358 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003359}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003360
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003361/// RewriteImplementations - This routine rewrites all method implementations
3362/// and emits meta-data.
3363
Steve Naroffb29b4272008-04-14 22:03:09 +00003364void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003365 int ClsDefCount = ClassImplementation.size();
3366 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003367
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003368 if (ClsDefCount == 0 && CatDefCount == 0)
3369 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003370 // Rewrite implemented methods
3371 for (int i = 0; i < ClsDefCount; i++)
3372 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003373
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003374 for (int i = 0; i < CatDefCount; i++)
3375 RewriteImplementationDecl(CategoryImplementation[i]);
3376
Steve Naroff5df5b762008-05-07 21:23:49 +00003377 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003378 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003379 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003380 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003381 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003382
3383 // For each implemented category, write out all its meta data.
3384 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003385 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003386
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003387 // Write objc_symtab metadata
3388 /*
3389 struct _objc_symtab
3390 {
3391 long sel_ref_cnt;
3392 SEL *refs;
3393 short cls_def_cnt;
3394 short cat_def_cnt;
3395 void *defs[cls_def_cnt + cat_def_cnt];
3396 };
3397 */
3398
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003399 Result += "\nstruct _objc_symtab {\n";
3400 Result += "\tlong sel_ref_cnt;\n";
3401 Result += "\tSEL *refs;\n";
3402 Result += "\tshort cls_def_cnt;\n";
3403 Result += "\tshort cat_def_cnt;\n";
3404 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3405 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003406
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003407 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003408 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003409 Result += "\t0, 0, " + utostr(ClsDefCount)
3410 + ", " + utostr(CatDefCount) + "\n";
3411 for (int i = 0; i < ClsDefCount; i++) {
3412 Result += "\t,&_OBJC_CLASS_";
3413 Result += ClassImplementation[i]->getName();
3414 Result += "\n";
3415 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003416
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003417 for (int i = 0; i < CatDefCount; i++) {
3418 Result += "\t,&_OBJC_CATEGORY_";
3419 Result += CategoryImplementation[i]->getClassInterface()->getName();
3420 Result += "_";
3421 Result += CategoryImplementation[i]->getName();
3422 Result += "\n";
3423 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003424
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003425 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003426
3427 // Write objc_module metadata
3428
3429 /*
3430 struct _objc_module {
3431 long version;
3432 long size;
3433 const char *name;
3434 struct _objc_symtab *symtab;
3435 }
3436 */
3437
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003438 Result += "\nstruct _objc_module {\n";
3439 Result += "\tlong version;\n";
3440 Result += "\tlong size;\n";
3441 Result += "\tconst char *name;\n";
3442 Result += "\tstruct _objc_symtab *symtab;\n";
3443 Result += "};\n\n";
3444 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003445 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003446 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3447 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003448 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003449
3450 if (LangOpts.Microsoft) {
3451 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003452 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003453 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3454 Result += "&_OBJC_MODULES;\n";
3455 Result += "#pragma data_seg(pop)\n\n";
3456 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003457}
Chris Lattner311ff022007-10-16 22:36:42 +00003458
Steve Naroff54055232008-10-27 17:20:55 +00003459std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3460 const char *funcName,
3461 std::string Tag) {
3462 const FunctionType *AFT = CE->getFunctionType();
3463 QualType RT = AFT->getResultType();
3464 std::string StructRef = "struct " + Tag;
3465 std::string S = "static " + RT.getAsString() + " __" +
3466 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003467
Steve Naroff54055232008-10-27 17:20:55 +00003468 BlockDecl *BD = CE->getBlockDecl();
3469
3470 if (isa<FunctionTypeNoProto>(AFT)) {
3471 S += "()";
3472 } else if (BD->param_empty()) {
3473 S += "(" + StructRef + " *__cself)";
3474 } else {
3475 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3476 assert(FT && "SynthesizeBlockFunc: No function proto");
3477 S += '(';
3478 // first add the implicit argument.
3479 S += StructRef + " *__cself, ";
3480 std::string ParamStr;
3481 for (BlockDecl::param_iterator AI = BD->param_begin(),
3482 E = BD->param_end(); AI != E; ++AI) {
3483 if (AI != BD->param_begin()) S += ", ";
3484 ParamStr = (*AI)->getName();
3485 (*AI)->getType().getAsStringInternal(ParamStr);
3486 S += ParamStr;
3487 }
3488 if (FT->isVariadic()) {
3489 if (!BD->param_empty()) S += ", ";
3490 S += "...";
3491 }
3492 S += ')';
3493 }
3494 S += " {\n";
3495
3496 // Create local declarations to avoid rewriting all closure decl ref exprs.
3497 // First, emit a declaration for all "by ref" decls.
3498 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3499 E = BlockByRefDecls.end(); I != E; ++I) {
3500 S += " ";
3501 std::string Name = (*I)->getName();
3502 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3503 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3504 }
3505 // Next, emit a declaration for all "by copy" declarations.
3506 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3507 E = BlockByCopyDecls.end(); I != E; ++I) {
3508 S += " ";
3509 std::string Name = (*I)->getName();
3510 // Handle nested closure invocation. For example:
3511 //
3512 // void (^myImportedClosure)(void);
3513 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3514 //
3515 // void (^anotherClosure)(void);
3516 // anotherClosure = ^(void) {
3517 // myImportedClosure(); // import and invoke the closure
3518 // };
3519 //
3520 if (isBlockPointerType((*I)->getType()))
3521 S += "struct __block_impl *";
3522 else
3523 (*I)->getType().getAsStringInternal(Name);
3524 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3525 }
3526 std::string RewrittenStr = RewrittenBlockExprs[CE];
3527 const char *cstr = RewrittenStr.c_str();
3528 while (*cstr++ != '{') ;
3529 S += cstr;
3530 S += "\n";
3531 return S;
3532}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003533
Steve Naroff54055232008-10-27 17:20:55 +00003534std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3535 const char *funcName,
3536 std::string Tag) {
3537 std::string StructRef = "struct " + Tag;
3538 std::string S = "static void __";
3539
3540 S += funcName;
3541 S += "_block_copy_" + utostr(i);
3542 S += "(" + StructRef;
3543 S += "*dst, " + StructRef;
3544 S += "*src) {";
3545 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3546 E = ImportedBlockDecls.end(); I != E; ++I) {
3547 S += "_Block_copy_assign(&dst->";
3548 S += (*I)->getName();
3549 S += ", src->";
3550 S += (*I)->getName();
3551 S += ");}";
3552 }
3553 S += "\nstatic void __";
3554 S += funcName;
3555 S += "_block_dispose_" + utostr(i);
3556 S += "(" + StructRef;
3557 S += "*src) {";
3558 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3559 E = ImportedBlockDecls.end(); I != E; ++I) {
3560 S += "_Block_destroy(src->";
3561 S += (*I)->getName();
3562 S += ");";
3563 }
3564 S += "}\n";
3565 return S;
3566}
3567
3568std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3569 bool hasCopyDisposeHelpers) {
3570 std::string S = "struct " + Tag;
3571 std::string Constructor = " " + Tag;
3572
3573 S += " {\n struct __block_impl impl;\n";
3574
3575 if (hasCopyDisposeHelpers)
3576 S += " void *copy;\n void *dispose;\n";
3577
3578 Constructor += "(void *fp";
3579
3580 if (hasCopyDisposeHelpers)
3581 Constructor += ", void *copyHelp, void *disposeHelp";
3582
3583 if (BlockDeclRefs.size()) {
3584 // Output all "by copy" declarations.
3585 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3586 E = BlockByCopyDecls.end(); I != E; ++I) {
3587 S += " ";
3588 std::string FieldName = (*I)->getName();
3589 std::string ArgName = "_" + FieldName;
3590 // Handle nested closure invocation. For example:
3591 //
3592 // void (^myImportedBlock)(void);
3593 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3594 //
3595 // void (^anotherBlock)(void);
3596 // anotherBlock = ^(void) {
3597 // myImportedBlock(); // import and invoke the closure
3598 // };
3599 //
3600 if (isBlockPointerType((*I)->getType())) {
3601 S += "struct __block_impl *";
3602 Constructor += ", void *" + ArgName;
3603 } else {
3604 (*I)->getType().getAsStringInternal(FieldName);
3605 (*I)->getType().getAsStringInternal(ArgName);
3606 Constructor += ", " + ArgName;
3607 }
3608 S += FieldName + ";\n";
3609 }
3610 // Output all "by ref" declarations.
3611 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3612 E = BlockByRefDecls.end(); I != E; ++I) {
3613 S += " ";
3614 std::string FieldName = (*I)->getName();
3615 std::string ArgName = "_" + FieldName;
3616 // Handle nested closure invocation. For example:
3617 //
3618 // void (^myImportedBlock)(void);
3619 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3620 //
3621 // void (^anotherBlock)(void);
3622 // anotherBlock = ^(void) {
3623 // myImportedBlock(); // import and invoke the closure
3624 // };
3625 //
3626 if (isBlockPointerType((*I)->getType())) {
3627 S += "struct __block_impl *";
3628 Constructor += ", void *" + ArgName;
3629 } else {
3630 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3631 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3632 Constructor += ", " + ArgName;
3633 }
3634 S += FieldName + "; // by ref\n";
3635 }
3636 // Finish writing the constructor.
3637 // FIXME: handle NSConcreteGlobalBlock.
3638 Constructor += ", int flags=0) {\n";
3639 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3640 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3641
3642 if (hasCopyDisposeHelpers)
3643 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3644
3645 // Initialize all "by copy" arguments.
3646 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3647 E = BlockByCopyDecls.end(); I != E; ++I) {
3648 std::string Name = (*I)->getName();
3649 Constructor += " ";
3650 if (isBlockPointerType((*I)->getType()))
3651 Constructor += Name + " = (struct __block_impl *)_";
3652 else
3653 Constructor += Name + " = _";
3654 Constructor += Name + ";\n";
3655 }
3656 // Initialize all "by ref" arguments.
3657 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3658 E = BlockByRefDecls.end(); I != E; ++I) {
3659 std::string Name = (*I)->getName();
3660 Constructor += " ";
3661 if (isBlockPointerType((*I)->getType()))
3662 Constructor += Name + " = (struct __block_impl *)_";
3663 else
3664 Constructor += Name + " = _";
3665 Constructor += Name + ";\n";
3666 }
3667 } else {
3668 // Finish writing the constructor.
3669 // FIXME: handle NSConcreteGlobalBlock.
3670 Constructor += ", int flags=0) {\n";
3671 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3672 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3673 if (hasCopyDisposeHelpers)
3674 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3675 }
3676 Constructor += " ";
3677 Constructor += "}\n";
3678 S += Constructor;
3679 S += "};\n";
3680 return S;
3681}
3682
3683void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3684 const char *FunName) {
3685 // Insert closures that were part of the function.
3686 for (unsigned i = 0; i < Blocks.size(); i++) {
3687
3688 CollectBlockDeclRefInfo(Blocks[i]);
3689
3690 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3691
3692 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3693 ImportedBlockDecls.size() > 0);
3694
3695 InsertText(FunLocStart, CI.c_str(), CI.size());
3696
3697 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3698
3699 InsertText(FunLocStart, CF.c_str(), CF.size());
3700
3701 if (ImportedBlockDecls.size()) {
3702 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3703 InsertText(FunLocStart, HF.c_str(), HF.size());
3704 }
3705
3706 BlockDeclRefs.clear();
3707 BlockByRefDecls.clear();
3708 BlockByCopyDecls.clear();
3709 BlockCallExprs.clear();
3710 ImportedBlockDecls.clear();
3711 }
3712 Blocks.clear();
3713 RewrittenBlockExprs.clear();
3714}
3715
3716void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3717 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3718 const char *FuncName = FD->getName();
3719
3720 SynthesizeBlockLiterals(FunLocStart, FuncName);
3721}
3722
3723void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3724 SourceLocation FunLocStart = MD->getLocStart();
3725 std::string FuncName = std::string(MD->getSelector().getName());
3726 // Convert colons to underscores.
3727 std::string::size_type loc = 0;
3728 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3729 FuncName.replace(loc, 1, "_");
3730
3731 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3732}
3733
3734void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3735 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3736 CI != E; ++CI)
3737 if (*CI) {
3738 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3739 GetBlockDeclRefExprs(CBE->getBody());
3740 else
3741 GetBlockDeclRefExprs(*CI);
3742 }
3743 // Handle specific things.
3744 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3745 // FIXME: Handle enums.
3746 if (!isa<FunctionDecl>(CDRE->getDecl()))
3747 BlockDeclRefs.push_back(CDRE);
3748 return;
3749}
3750
3751void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3752 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3753 CI != E; ++CI)
3754 if (*CI) {
3755 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3756 GetBlockCallExprs(CBE->getBody());
3757 else
3758 GetBlockCallExprs(*CI);
3759 }
3760
3761 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3762 if (CE->getCallee()->getType()->isBlockPointerType()) {
3763 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3764 }
3765 }
3766 return;
3767}
3768
3769std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3770 // Navigate to relevant type information.
3771 const char *closureName = 0;
3772 const BlockPointerType *CPT = 0;
3773
3774 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3775 closureName = DRE->getDecl()->getName();
3776 CPT = DRE->getType()->getAsBlockPointerType();
3777 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3778 closureName = CDRE->getDecl()->getName();
3779 CPT = CDRE->getType()->getAsBlockPointerType();
3780 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3781 closureName = MExpr->getMemberDecl()->getName();
3782 CPT = MExpr->getType()->getAsBlockPointerType();
3783 } else {
3784 assert(1 && "RewriteBlockClass: Bad type");
3785 }
3786 assert(CPT && "RewriteBlockClass: Bad type");
3787 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3788 assert(FT && "RewriteBlockClass: Bad type");
3789 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3790 // FTP will be null for closures that don't take arguments.
3791
3792 // Build a closure call - start with a paren expr to enforce precedence.
3793 std::string BlockCall = "(";
3794
3795 // Synthesize the cast.
3796 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3797 BlockCall += "(struct __block_impl *";
3798 if (FTP) {
3799 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3800 E = FTP->arg_type_end(); I && (I != E); ++I)
3801 BlockCall += ", " + (*I).getAsString();
3802 }
3803 BlockCall += "))"; // close the argument list and paren expression.
3804
3805 // Invoke the closure. We need to cast it since the declaration type is
3806 // bogus (it's a function pointer type)
3807 BlockCall += "((struct __block_impl *)";
3808 std::string closureExprBufStr;
3809 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3810 Exp->getCallee()->printPretty(closureExprBuf);
3811 BlockCall += closureExprBuf.str();
3812 BlockCall += ")->FuncPtr)";
3813
3814 // Add the arguments.
3815 BlockCall += "((struct __block_impl *)";
3816 BlockCall += closureExprBuf.str();
3817 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3818 E = Exp->arg_end(); I != E; ++I) {
3819 std::string syncExprBufS;
3820 llvm::raw_string_ostream Buf(syncExprBufS);
3821 (*I)->printPretty(Buf);
3822 BlockCall += ", " + Buf.str();
3823 }
3824 return BlockCall;
3825}
3826
3827void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3828 std::string BlockCall = SynthesizeBlockCall(Exp);
3829
3830 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3831 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3832
3833 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3834 BlockCall.c_str(), BlockCall.size());
3835}
3836
3837void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3838 // FIXME: Add more elaborate code generation required by the ABI.
3839 InsertText(BDRE->getLocStart(), "*", 1);
3840}
3841
3842void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3843 SourceLocation LocStart = CE->getLocStart();
3844 SourceLocation LocEnd = CE->getLocEnd();
3845
3846 const char *startBuf = SM->getCharacterData(LocStart);
3847 const char *endBuf = SM->getCharacterData(LocEnd);
3848
3849 // advance the location to startArgList.
3850 const char *argPtr = startBuf;
3851
3852 while (*argPtr++ && (argPtr < endBuf)) {
3853 switch (*argPtr) {
3854 case '^':
3855 // Replace the '^' with '*'.
3856 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3857 ReplaceText(LocStart, 1, "*", 1);
3858 break;
3859 }
3860 }
3861 return;
3862}
3863
3864void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3865 SourceLocation DeclLoc = FD->getLocation();
3866 unsigned parenCount = 0;
3867
3868 // We have 1 or more arguments that have closure pointers.
3869 const char *startBuf = SM->getCharacterData(DeclLoc);
3870 const char *startArgList = strchr(startBuf, '(');
3871
3872 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3873
3874 parenCount++;
3875 // advance the location to startArgList.
3876 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3877 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3878
3879 const char *argPtr = startArgList;
3880
3881 while (*argPtr++ && parenCount) {
3882 switch (*argPtr) {
3883 case '^':
3884 // Replace the '^' with '*'.
3885 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3886 ReplaceText(DeclLoc, 1, "*", 1);
3887 break;
3888 case '(':
3889 parenCount++;
3890 break;
3891 case ')':
3892 parenCount--;
3893 break;
3894 }
3895 }
3896 return;
3897}
3898
3899bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3900 const FunctionTypeProto *FTP;
3901 const PointerType *PT = QT->getAsPointerType();
3902 if (PT) {
3903 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3904 } else {
3905 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3906 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3907 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3908 }
3909 if (FTP) {
3910 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3911 E = FTP->arg_type_end(); I != E; ++I)
3912 if (isBlockPointerType(*I))
3913 return true;
3914 }
3915 return false;
3916}
3917
3918void RewriteObjC::GetExtentOfArgList(const char *Name,
3919 const char *&LParen, const char *&RParen) {
3920 const char *argPtr = strchr(Name, '(');
3921 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3922
3923 LParen = argPtr; // output the start.
3924 argPtr++; // skip past the left paren.
3925 unsigned parenCount = 1;
3926
3927 while (*argPtr && parenCount) {
3928 switch (*argPtr) {
3929 case '(': parenCount++; break;
3930 case ')': parenCount--; break;
3931 default: break;
3932 }
3933 if (parenCount) argPtr++;
3934 }
3935 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3936 RParen = argPtr; // output the end
3937}
3938
3939void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3940 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3941 RewriteBlockPointerFunctionArgs(FD);
3942 return;
3943 }
3944 // Handle Variables and Typedefs.
3945 SourceLocation DeclLoc = ND->getLocation();
3946 QualType DeclT;
3947 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3948 DeclT = VD->getType();
3949 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3950 DeclT = TDD->getUnderlyingType();
3951 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3952 DeclT = FD->getType();
3953 else
3954 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3955
3956 const char *startBuf = SM->getCharacterData(DeclLoc);
3957 const char *endBuf = startBuf;
3958 // scan backward (from the decl location) for the end of the previous decl.
3959 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3960 startBuf--;
3961
3962 // *startBuf != '^' if we are dealing with a pointer to function that
3963 // may take block argument types (which will be handled below).
3964 if (*startBuf == '^') {
3965 // Replace the '^' with '*', computing a negative offset.
3966 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3967 ReplaceText(DeclLoc, 1, "*", 1);
3968 }
3969 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3970 // Replace the '^' with '*' for arguments.
3971 DeclLoc = ND->getLocation();
3972 startBuf = SM->getCharacterData(DeclLoc);
3973 const char *argListBegin, *argListEnd;
3974 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3975 while (argListBegin < argListEnd) {
3976 if (*argListBegin == '^') {
3977 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3978 ReplaceText(CaretLoc, 1, "*", 1);
3979 }
3980 argListBegin++;
3981 }
3982 }
3983 return;
3984}
3985
3986void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3987 // Add initializers for any closure decl refs.
3988 GetBlockDeclRefExprs(Exp->getBody());
3989 if (BlockDeclRefs.size()) {
3990 // Unique all "by copy" declarations.
3991 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3992 if (!BlockDeclRefs[i]->isByRef())
3993 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3994 // Unique all "by ref" declarations.
3995 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3996 if (BlockDeclRefs[i]->isByRef()) {
3997 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3998 }
3999 // Find any imported blocks...they will need special attention.
4000 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4001 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
4002 GetBlockCallExprs(Blocks[i]);
4003 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4004 }
4005 }
4006}
4007
4008std::string RewriteObjC::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
4009 Blocks.push_back(Exp);
4010
4011 CollectBlockDeclRefInfo(Exp);
4012 std::string FuncName;
4013
4014 if (CurFunctionDef)
4015 FuncName = std::string(CurFunctionDef->getName());
4016 else if (CurMethodDef) {
4017 FuncName = std::string(CurMethodDef->getSelector().getName());
4018 // Convert colons to underscores.
4019 std::string::size_type loc = 0;
4020 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4021 FuncName.replace(loc, 1, "_");
4022 } else if (VD)
4023 FuncName = std::string(VD->getName());
4024
4025 std::string BlockNumber = utostr(Blocks.size()-1);
4026
4027 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4028 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4029
4030 std::string FunkTypeStr;
4031
4032 // Get a pointer to the function type so we can cast appropriately.
4033 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
4034
4035 // Rewrite the closure block with a compound literal. The first cast is
4036 // to prevent warnings from the C compiler.
4037 std::string Init = "(" + FunkTypeStr;
4038
4039 Init += ")&" + Tag;
4040
4041 // Initialize the block function.
4042 Init += "((void*)" + Func;
4043
4044 if (ImportedBlockDecls.size()) {
4045 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
4046 Init += ",(void*)" + Buf;
4047 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
4048 Init += ",(void*)" + Buf;
4049 }
4050 // Add initializers for any closure decl refs.
4051 if (BlockDeclRefs.size()) {
4052 // Output all "by copy" declarations.
4053 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4054 E = BlockByCopyDecls.end(); I != E; ++I) {
4055 Init += ",";
4056 if (isObjCType((*I)->getType())) {
4057 Init += "[[";
4058 Init += (*I)->getName();
4059 Init += " retain] autorelease]";
4060 } else if (isBlockPointerType((*I)->getType())) {
4061 Init += "(void *)";
4062 Init += (*I)->getName();
4063 } else {
4064 Init += (*I)->getName();
4065 }
4066 }
4067 // Output all "by ref" declarations.
4068 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4069 E = BlockByRefDecls.end(); I != E; ++I) {
4070 Init += ",&";
4071 Init += (*I)->getName();
4072 }
4073 }
4074 Init += ")";
4075 BlockDeclRefs.clear();
4076 BlockByRefDecls.clear();
4077 BlockByCopyDecls.clear();
4078 ImportedBlockDecls.clear();
4079
4080 return Init;
4081}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004082