blob: a768d17b3a582842953cbd2a450fb56068143ef1 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000023#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000024using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000025using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000026
Chris Lattner77cd2a02007-10-11 00:43:27 +000027namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000028 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000029 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000030 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000032 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000033 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000034 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
35 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000037 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000038 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000039
40 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000041 FunctionDecl *MsgSendSuperFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000042 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000043 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000044 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000045
Steve Naroffbeaf2992007-11-03 11:27:19 +000046 // ObjC string constant support.
47 FileVarDecl *ConstantStringClassReference;
48 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000049
Steve Naroff874e2322007-11-15 10:28:18 +000050 // Needed for super.
51 ObjcMethodDecl *CurMethodDecl;
52 RecordDecl *SuperStructDecl;
53
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000054 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000055 public:
Chris Lattner01c57482007-10-17 22:35:30 +000056 void Initialize(ASTContext &context, unsigned mainFileID) {
57 Context = &context;
58 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000059 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000060 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000061 MsgSendSuperFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000062 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000063 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000064 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000065 ConstantStringClassReference = 0;
66 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000067 CurMethodDecl = 0;
68 SuperStructDecl = 0;
69
Chris Lattner01c57482007-10-17 22:35:30 +000070 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000071 // declaring objc_selector outside the parameter list removes a silly
72 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000073 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000074 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000075 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000076 "struct objc_super { struct objc_object *receiver; struct objc_class *super; };\n"
77 "extern struct objc_object *objc_msgSendSuper"
78 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +000079 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000080 "(const char *);\n"
81 "extern void objc_exception_throw(struct objc_object *);\n"
82 "extern void objc_exception_try_enter(void *);\n"
83 "extern void objc_exception_try_exit(void *);\n"
84 "extern struct objc_object *objc_exception_extract(void *);\n"
85 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +000086 "(struct objc_class *, struct objc_object *, ...);\n"
87 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000088
Steve Naroffab972d32007-11-04 22:37:50 +000089 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
90 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000091 }
Chris Lattner8a12c272007-10-11 18:38:32 +000092
Chris Lattnerf04da132007-10-24 17:06:59 +000093 // Top Level Driver code.
94 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000095 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000096 ~RewriteTest();
97
98 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000099 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000100 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000101 void RewriteTabs();
102 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000103 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000104 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000105 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000106 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000107 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000108 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000109 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000110 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000111 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000112 void RewriteObjcQualifiedInterfaceTypes(
113 const FunctionTypeProto *proto, FunctionDecl *FD);
114 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000115 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
116 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000119 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000120 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000121 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000122 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000123 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000124 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000125 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
126 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
127 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000128 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000129 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
130 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000131 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000132 void SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000133 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000134 void SynthCFStringFunctionDecl();
135
Chris Lattnerf04da132007-10-24 17:06:59 +0000136 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000137 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
138 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000140 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
141 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000142
Steve Naroff0416fb92007-11-11 17:19:15 +0000143 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000144 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000145 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000146 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000147 const char *ClassName,
148 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000149
150 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
151 int NumProtocols,
152 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000153 const char *ClassName,
154 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000155 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
156 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000157 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
158 ObjcIvarDecl *ivar,
159 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000160 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000161 };
162}
163
Chris Lattner8a12c272007-10-11 18:38:32 +0000164ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166//===----------------------------------------------------------------------===//
167// Top Level Driver Code
168//===----------------------------------------------------------------------===//
169
Chris Lattner8a12c272007-10-11 18:38:32 +0000170void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000171 // Two cases: either the decl could be in the main file, or it could be in a
172 // #included file. If the former, rewrite it now. If the later, check to see
173 // if we rewrote the #include/#import.
174 SourceLocation Loc = D->getLocation();
175 Loc = SM->getLogicalLoc(Loc);
176
177 // If this is for a builtin, ignore it.
178 if (Loc.isInvalid()) return;
179
Steve Naroffebf2b562007-10-23 23:50:29 +0000180 // Look for built-in declarations that we need to refer during the rewrite.
181 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000182 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000183 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
184 // declared in <Foundation/NSString.h>
185 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
186 ConstantStringClassReference = FVD;
187 return;
188 }
Steve Naroffbef11852007-10-26 20:53:56 +0000189 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
190 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000191 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
192 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000193 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
194 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000195 } else if (ObjcForwardProtocolDecl *FP =
196 dyn_cast<ObjcForwardProtocolDecl>(D)){
197 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000198 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000199 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000200 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
201 return HandleDeclInMainFile(D);
202
Chris Lattnerf04da132007-10-24 17:06:59 +0000203 // Otherwise, see if there is a #import in the main file that should be
204 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000205 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000206}
207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208/// HandleDeclInMainFile - This is called for each top-level decl defined in the
209/// main file of the input.
210void RewriteTest::HandleDeclInMainFile(Decl *D) {
211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
212 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000213 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000214
215 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000216 if (Stmt *Body = MD->getBody()) {
217 //Body->dump();
218 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000219 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000220 CurMethodDecl = 0;
221 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000222 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
224 ClassImplementation.push_back(CI);
225 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
226 CategoryImplementation.push_back(CI);
227 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
228 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000229 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
230 if (VD->getInit())
231 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233 // Nothing yet.
234}
235
236RewriteTest::~RewriteTest() {
237 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000238
239 // Rewrite tabs if we care.
240 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000241
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000242 // Rewrite Objective-c meta data*
243 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000244 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000245
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
247 // we are done.
248 if (const RewriteBuffer *RewriteBuf =
249 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000250 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000251 std::string S(RewriteBuf->begin(), RewriteBuf->end());
252 printf("%s\n", S.c_str());
253 } else {
254 printf("No changes\n");
255 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000256 // Emit metadata.
257 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000258}
259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260//===----------------------------------------------------------------------===//
261// Syntactic (non-AST) Rewriting Code
262//===----------------------------------------------------------------------===//
263
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000264void RewriteTest::RewriteInclude(SourceLocation Loc) {
265 // Rip up the #include stack to the main file.
266 SourceLocation IncLoc = Loc, NextLoc = Loc;
267 do {
268 IncLoc = Loc;
269 Loc = SM->getLogicalLoc(NextLoc);
270 NextLoc = SM->getIncludeLoc(Loc);
271 } while (!NextLoc.isInvalid());
272
273 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
274 // IncLoc indicates the header that was included if it is useful.
275 IncLoc = SM->getLogicalLoc(IncLoc);
276 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
277 Loc == LastIncLoc)
278 return;
279 LastIncLoc = Loc;
280
281 unsigned IncCol = SM->getColumnNumber(Loc);
282 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
283
284 // Replace the #import with #include.
285 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
286}
287
Chris Lattnerf04da132007-10-24 17:06:59 +0000288void RewriteTest::RewriteTabs() {
289 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
290 const char *MainBufStart = MainBuf.first;
291 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Loop over the whole file, looking for tabs.
294 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
295 if (*BufPtr != '\t')
296 continue;
297
298 // Okay, we found a tab. This tab will turn into at least one character,
299 // but it depends on which 'virtual column' it is in. Compute that now.
300 unsigned VCol = 0;
301 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
302 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
303 ++VCol;
304
305 // Okay, now that we know the virtual column, we know how many spaces to
306 // insert. We assume 8-character tab-stops.
307 unsigned Spaces = 8-(VCol & 7);
308
309 // Get the location of the tab.
310 SourceLocation TabLoc =
311 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
312
313 // Rewrite the single tab character into a sequence of spaces.
314 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
315 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000316}
317
318
Chris Lattnerf04da132007-10-24 17:06:59 +0000319void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
320 int numDecls = ClassDecl->getNumForwardDecls();
321 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
322
323 // Get the start location and compute the semi location.
324 SourceLocation startLoc = ClassDecl->getLocation();
325 const char *startBuf = SM->getCharacterData(startLoc);
326 const char *semiPtr = strchr(startBuf, ';');
327
328 // Translate to typedef's that forward reference structs with the same name
329 // as the class. As a convenience, we include the original declaration
330 // as a comment.
331 std::string typedefString;
332 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000333 typedefString.append(startBuf, semiPtr-startBuf+1);
334 typedefString += "\n";
335 for (int i = 0; i < numDecls; i++) {
336 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000337 typedefString += "#ifndef _REWRITER_typedef_";
338 typedefString += ForwardDecl->getName();
339 typedefString += "\n";
340 typedefString += "#define _REWRITER_typedef_";
341 typedefString += ForwardDecl->getName();
342 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000343 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000344 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000345 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000346 }
347
348 // Replace the @class with typedefs corresponding to the classes.
349 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
350 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000351}
352
Steve Naroff71c0a952007-11-13 23:01:27 +0000353void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000354 for (int i = 0; i < nMethods; i++) {
355 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000356 SourceLocation LocStart = Method->getLocStart();
357 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000358
Steve Naroff1d098f62007-11-14 14:34:23 +0000359 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
360 Rewrite.InsertText(LocStart, "/* ", 3);
361 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
362 } else {
363 Rewrite.InsertText(LocStart, "// ", 3);
364 }
Steve Naroff423cb562007-10-30 13:30:57 +0000365 }
366}
367
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000368void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
369{
370 for (int i = 0; i < nProperties; i++) {
371 ObjcPropertyDecl *Property = Properties[i];
372 SourceLocation Loc = Property->getLocation();
373
374 Rewrite.ReplaceText(Loc, 0, "// ", 3);
375
376 // FIXME: handle properties that are declared across multiple lines.
377 }
378}
379
Steve Naroff423cb562007-10-30 13:30:57 +0000380void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
381 SourceLocation LocStart = CatDecl->getLocStart();
382
383 // FIXME: handle category headers that are declared across multiple lines.
384 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
385
Steve Naroff71c0a952007-11-13 23:01:27 +0000386 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
387 CatDecl->getInstanceMethods());
388 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
389 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000390 // Lastly, comment out the @end.
391 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
392}
393
Steve Naroff752d6ef2007-10-30 16:42:30 +0000394void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000395 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000396
Steve Naroff752d6ef2007-10-30 16:42:30 +0000397 SourceLocation LocStart = PDecl->getLocStart();
398
399 // FIXME: handle protocol headers that are declared across multiple lines.
400 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
401
Steve Naroff71c0a952007-11-13 23:01:27 +0000402 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
403 PDecl->getInstanceMethods());
404 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
405 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000406 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000407 SourceLocation LocEnd = PDecl->getAtEndLoc();
408 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000409
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000410 // Must comment out @optional/@required
411 const char *startBuf = SM->getCharacterData(LocStart);
412 const char *endBuf = SM->getCharacterData(LocEnd);
413 for (const char *p = startBuf; p < endBuf; p++) {
414 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
415 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000416 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000417 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
418 CommentedOptional.c_str(), CommentedOptional.size());
419
420 }
421 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
422 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000423 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000424 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
425 CommentedRequired.c_str(), CommentedRequired.size());
426
427 }
428 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000429}
430
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000431void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
432 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000433 if (LocStart.isInvalid())
434 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000435 // FIXME: handle forward protocol that are declared across multiple lines.
436 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
437}
438
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000439void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
440 std::string &ResultStr) {
441 ResultStr += "\nstatic ";
442 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000443 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000444
445 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000446 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000447
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000448 if (OMD->isInstance())
449 NameStr += "_I_";
450 else
451 NameStr += "_C_";
452
453 NameStr += OMD->getClassInterface()->getName();
454 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000455
456 NamedDecl *MethodContext = OMD->getMethodContext();
457 if (ObjcCategoryImplDecl *CID =
458 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000459 NameStr += CID->getName();
460 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000461 }
462 // Append selector names, replacing ':' with '_'
463 const char *selName = OMD->getSelector().getName().c_str();
464 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000465 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000466 else {
467 std::string selString = OMD->getSelector().getName();
468 int len = selString.size();
469 for (int i = 0; i < len; i++)
470 if (selString[i] == ':')
471 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000472 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000473 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000474 // Remember this name for metadata emission
475 MethodInternalNames[OMD] = NameStr;
476 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000477
478 // Rewrite arguments
479 ResultStr += "(";
480
481 // invisible arguments
482 if (OMD->isInstance()) {
483 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
484 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000485 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
486 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000487 ResultStr += selfTy.getAsString();
488 }
489 else
490 ResultStr += Context->getObjcIdType().getAsString();
491
492 ResultStr += " self, ";
493 ResultStr += Context->getObjcSelType().getAsString();
494 ResultStr += " _cmd";
495
496 // Method arguments.
497 for (int i = 0; i < OMD->getNumParams(); i++) {
498 ParmVarDecl *PDecl = OMD->getParamDecl(i);
499 ResultStr += ", ";
500 ResultStr += PDecl->getType().getAsString();
501 ResultStr += " ";
502 ResultStr += PDecl->getName();
503 }
504 ResultStr += ")";
505
506}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000507void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
508 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
509 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000510
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000511 if (IMD)
512 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
513 else
514 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000516 int numMethods = IMD ? IMD->getNumInstanceMethods()
517 : CID->getNumInstanceMethods();
518
519 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000521 ObjcMethodDecl *OMD;
522 if (IMD)
523 OMD = IMD->getInstanceMethods()[i];
524 else
525 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000526 RewriteObjcMethodDecl(OMD, ResultStr);
527 SourceLocation LocStart = OMD->getLocStart();
528 SourceLocation LocEnd = OMD->getBody()->getLocStart();
529
530 const char *startBuf = SM->getCharacterData(LocStart);
531 const char *endBuf = SM->getCharacterData(LocEnd);
532 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
533 ResultStr.c_str(), ResultStr.size());
534 }
535
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000536 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
537 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000538 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 ObjcMethodDecl *OMD;
540 if (IMD)
541 OMD = IMD->getClassMethods()[i];
542 else
543 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000544 RewriteObjcMethodDecl(OMD, ResultStr);
545 SourceLocation LocStart = OMD->getLocStart();
546 SourceLocation LocEnd = OMD->getBody()->getLocStart();
547
548 const char *startBuf = SM->getCharacterData(LocStart);
549 const char *endBuf = SM->getCharacterData(LocEnd);
550 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
551 ResultStr.c_str(), ResultStr.size());
552 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000553 if (IMD)
554 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
555 else
556 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557}
558
Steve Naroffbef11852007-10-26 20:53:56 +0000559void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000560 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000561 if (!ObjcForwardDecls.count(ClassDecl)) {
562 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000563 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000564 ResultStr += ClassDecl->getName();
565 ResultStr += "\n";
566 ResultStr += "#define _REWRITER_typedef_";
567 ResultStr += ClassDecl->getName();
568 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000569 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000570 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000571 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000572
573 // Mark this typedef as having been generated.
574 ObjcForwardDecls.insert(ClassDecl);
575 }
Steve Narofff908a872007-10-30 02:23:23 +0000576 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
577
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000578 RewriteProperties(ClassDecl->getNumPropertyDecl(),
579 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000580 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
581 ClassDecl->getInstanceMethods());
582 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
583 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000584
Steve Naroff2feac5e2007-10-30 03:43:13 +0000585 // Lastly, comment out the @end.
586 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000587}
588
Steve Naroff7e3411b2007-11-15 02:58:25 +0000589Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
590 ObjcIvarDecl *D = IV->getDecl();
591 if (IV->isFreeIvar()) {
592 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
593 IV->getLocation());
594 Rewrite.ReplaceStmt(IV, Replacement);
595 delete IV;
596 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000597 } else {
598 if (CurMethodDecl) {
599 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
600 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
601 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
602 IdentifierInfo *II = intT->getDecl()->getIdentifier();
603 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
604 II, 0);
605 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
606
607 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
608 // Don't forget the parens to enforce the proper binding.
609 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
610 Rewrite.ReplaceStmt(IV->getBase(), PE);
611 delete IV->getBase();
612 return PE;
613 }
614 }
615 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000616 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000617 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000618}
619
Chris Lattnerf04da132007-10-24 17:06:59 +0000620//===----------------------------------------------------------------------===//
621// Function Body / Expression rewriting
622//===----------------------------------------------------------------------===//
623
Steve Narofff3473a72007-11-09 15:20:18 +0000624Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000625 // Otherwise, just rewrite all children.
626 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
627 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000628 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000629 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000630 if (newStmt)
631 *CI = newStmt;
632 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000633
634 // Handle specific things.
635 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
636 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000637
638 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
639 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000640
641 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
642 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000643
644 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
645 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000646
Steve Naroff934f2762007-10-24 22:48:43 +0000647 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
648 // Before we rewrite it, put the original message expression in a comment.
649 SourceLocation startLoc = MessExpr->getLocStart();
650 SourceLocation endLoc = MessExpr->getLocEnd();
651
652 const char *startBuf = SM->getCharacterData(startLoc);
653 const char *endBuf = SM->getCharacterData(endLoc);
654
655 std::string messString;
656 messString += "// ";
657 messString.append(startBuf, endBuf-startBuf+1);
658 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000659
Steve Naroff934f2762007-10-24 22:48:43 +0000660 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
661 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
662 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000663 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000664 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000665 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000666
667 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
668 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000669
670 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
671 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000672#if 0
673 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
674 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
675 // Get the new text.
676 std::ostringstream Buf;
677 Replacement->printPretty(Buf);
678 const std::string &Str = Buf.str();
679
680 printf("CAST = %s\n", &Str[0]);
681 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
682 delete S;
683 return Replacement;
684 }
685#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000686 // Return this stmt unmodified.
687 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000688}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000689
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000690Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000691 // Get the start location and compute the semi location.
692 SourceLocation startLoc = S->getLocStart();
693 const char *startBuf = SM->getCharacterData(startLoc);
694
695 assert((*startBuf == '@') && "bogus @try location");
696
697 std::string buf;
698 // declare a new scope with two variables, _stack and _rethrow.
699 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
700 buf += "int buf[18/*32-bit i386*/];\n";
701 buf += "char *pointers[4];} _stack;\n";
702 buf += "id volatile _rethrow = 0;\n";
703 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000704 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000705
706 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
707
708 startLoc = S->getTryBody()->getLocEnd();
709 startBuf = SM->getCharacterData(startLoc);
710
711 assert((*startBuf == '}') && "bogus @try block");
712
713 SourceLocation lastCurlyLoc = startLoc;
714
715 startLoc = startLoc.getFileLocWithOffset(1);
716 buf = " /* @catch begin */ else {\n";
717 buf += " id _caught = objc_exception_extract(&_stack);\n";
718 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000719 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000720 buf += " _rethrow = objc_exception_extract(&_stack);\n";
721 buf += " else { /* @catch continue */";
722
Chris Lattner28d1fe82007-11-08 04:41:51 +0000723 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000724
725 bool sawIdTypedCatch = false;
726 Stmt *lastCatchBody = 0;
727 ObjcAtCatchStmt *catchList = S->getCatchStmts();
728 while (catchList) {
729 Stmt *catchStmt = catchList->getCatchParamStmt();
730
731 if (catchList == S->getCatchStmts())
732 buf = "if ("; // we are generating code for the first catch clause
733 else
734 buf = "else if (";
735 startLoc = catchList->getLocStart();
736 startBuf = SM->getCharacterData(startLoc);
737
738 assert((*startBuf == '@') && "bogus @catch location");
739
740 const char *lParenLoc = strchr(startBuf, '(');
741
742 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
743 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
744 if (t == Context->getObjcIdType()) {
745 buf += "1) { ";
746 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
747 buf.c_str(), buf.size());
748 sawIdTypedCatch = true;
749 } else if (const PointerType *pType = t->getAsPointerType()) {
750 ObjcInterfaceType *cls; // Should be a pointer to a class.
751
752 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
753 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000754 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000755 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000756 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000757 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
758 buf.c_str(), buf.size());
759 }
760 }
761 // Now rewrite the body...
762 lastCatchBody = catchList->getCatchBody();
763 SourceLocation rParenLoc = catchList->getRParenLoc();
764 SourceLocation bodyLoc = lastCatchBody->getLocStart();
765 const char *bodyBuf = SM->getCharacterData(bodyLoc);
766 const char *rParenBuf = SM->getCharacterData(rParenLoc);
767 assert((*rParenBuf == ')') && "bogus @catch paren location");
768 assert((*bodyBuf == '{') && "bogus @catch body location");
769
770 buf = " = _caught;";
771 // Here we replace ") {" with "= _caught;" (which initializes and
772 // declares the @catch parameter).
773 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
774 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000775 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000776 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000777 }
Steve Naroff75730982007-11-07 04:08:17 +0000778 catchList = catchList->getNextCatchStmt();
779 }
780 // Complete the catch list...
781 if (lastCatchBody) {
782 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
783 const char *bodyBuf = SM->getCharacterData(bodyLoc);
784 assert((*bodyBuf == '}') && "bogus @catch body location");
785 bodyLoc = bodyLoc.getFileLocWithOffset(1);
786 buf = " } } /* @catch end */\n";
787
Chris Lattner28d1fe82007-11-08 04:41:51 +0000788 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000789
790 // Set lastCurlyLoc
791 lastCurlyLoc = lastCatchBody->getLocEnd();
792 }
793 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
794 startLoc = finalStmt->getLocStart();
795 startBuf = SM->getCharacterData(startLoc);
796 assert((*startBuf == '@') && "bogus @finally start");
797
798 buf = "/* @finally */";
799 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
800
801 Stmt *body = finalStmt->getFinallyBody();
802 SourceLocation startLoc = body->getLocStart();
803 SourceLocation endLoc = body->getLocEnd();
804 const char *startBuf = SM->getCharacterData(startLoc);
805 const char *endBuf = SM->getCharacterData(endLoc);
806 assert((*startBuf == '{') && "bogus @finally body location");
807 assert((*endBuf == '}') && "bogus @finally body location");
808
809 startLoc = startLoc.getFileLocWithOffset(1);
810 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000811 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000812 endLoc = endLoc.getFileLocWithOffset(-1);
813 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000814 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000815
816 // Set lastCurlyLoc
817 lastCurlyLoc = body->getLocEnd();
818 }
819 // Now emit the final closing curly brace...
820 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
821 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000822 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000823 return 0;
824}
825
826Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
827 return 0;
828}
829
830Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
831 return 0;
832}
833
Steve Naroff2bd03922007-11-07 15:32:26 +0000834// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
835// the throw expression is typically a message expression that's already
836// been rewritten! (which implies the SourceLocation's are invalid).
837Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
838 // Get the start location and compute the semi location.
839 SourceLocation startLoc = S->getLocStart();
840 const char *startBuf = SM->getCharacterData(startLoc);
841
842 assert((*startBuf == '@') && "bogus @throw location");
843
844 std::string buf;
845 /* void objc_exception_throw(id) __attribute__((noreturn)); */
846 buf = "objc_exception_throw(";
847 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
848 const char *semiBuf = strchr(startBuf, ';');
849 assert((*semiBuf == ';') && "@throw: can't find ';'");
850 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
851 buf = ");";
852 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
853 return 0;
854}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000855
Chris Lattnere64b7772007-10-24 16:57:36 +0000856Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000857 // Create a new string expression.
858 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000859 std::string StrEncoding;
860 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
861 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
862 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000863 SourceLocation(), SourceLocation());
864 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000865 delete Exp;
866 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000867}
868
Steve Naroffb42f8412007-11-05 14:50:49 +0000869Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
870 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
871 // Create a call to sel_registerName("selName").
872 llvm::SmallVector<Expr*, 8> SelExprs;
873 QualType argType = Context->getPointerType(Context->CharTy);
874 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
875 Exp->getSelector().getName().size(),
876 false, argType, SourceLocation(),
877 SourceLocation()));
878 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
879 &SelExprs[0], SelExprs.size());
880 Rewrite.ReplaceStmt(Exp, SelExp);
881 delete Exp;
882 return SelExp;
883}
884
Steve Naroff934f2762007-10-24 22:48:43 +0000885CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
886 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000887 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000888 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000889
890 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000891 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000892
893 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000894 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000895 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
896
897 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000898
Steve Naroff934f2762007-10-24 22:48:43 +0000899 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
900}
901
Steve Naroffd5255f52007-11-01 13:24:47 +0000902static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
903 const char *&startRef, const char *&endRef) {
904 while (startBuf < endBuf) {
905 if (*startBuf == '<')
906 startRef = startBuf; // mark the start.
907 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000908 if (startRef && *startRef == '<') {
909 endRef = startBuf; // mark the end.
910 return true;
911 }
912 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000913 }
914 startBuf++;
915 }
916 return false;
917}
918
919bool RewriteTest::needToScanForQualifiers(QualType T) {
920 // FIXME: we don't currently represent "id <Protocol>" in the type system.
921 if (T == Context->getObjcIdType())
922 return true;
923
924 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000925 Type *pointeeType = pType->getPointeeType().getTypePtr();
926 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
927 return true; // we have "Class <Protocol> *".
928 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000929 return false;
930}
931
932void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
933 const FunctionTypeProto *proto, FunctionDecl *FD) {
934
935 if (needToScanForQualifiers(proto->getResultType())) {
936 // Since types are unique, we need to scan the buffer.
937 SourceLocation Loc = FD->getLocation();
938
939 const char *endBuf = SM->getCharacterData(Loc);
940 const char *startBuf = endBuf;
941 while (*startBuf != ';')
942 startBuf--; // scan backward (from the decl location) for return type.
943 const char *startRef = 0, *endRef = 0;
944 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
945 // Get the locations of the startRef, endRef.
946 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
947 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
948 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000949 Rewrite.InsertText(LessLoc, "/*", 2);
950 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000951 }
952 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000953 // Now check arguments.
954 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
955 if (needToScanForQualifiers(proto->getArgType(i))) {
956 // Since types are unique, we need to scan the buffer.
957 SourceLocation Loc = FD->getLocation();
958
959 const char *startBuf = SM->getCharacterData(Loc);
960 const char *endBuf = startBuf;
961 while (*endBuf != ';')
962 endBuf++; // scan forward (from the decl location) for argument types.
963 const char *startRef = 0, *endRef = 0;
964 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
965 // Get the locations of the startRef, endRef.
966 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
967 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
968 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000969 Rewrite.InsertText(LessLoc, "/*", 2);
970 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000971 }
972 }
973 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000974}
975
Steve Naroff09b266e2007-10-30 23:14:51 +0000976void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
977 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000978 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000979 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000980 return;
981 }
982 // Check for ObjC 'id' and class types that have been adorned with protocol
983 // information (id<p>, C<p>*). The protocol references need to be rewritten!
984 const FunctionType *funcType = FD->getType()->getAsFunctionType();
985 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000986 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
987 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000988}
989
990// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
991void RewriteTest::SynthMsgSendFunctionDecl() {
992 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
993 llvm::SmallVector<QualType, 16> ArgTys;
994 QualType argT = Context->getObjcIdType();
995 assert(!argT.isNull() && "Can't find 'id' type");
996 ArgTys.push_back(argT);
997 argT = Context->getObjcSelType();
998 assert(!argT.isNull() && "Can't find 'SEL' type");
999 ArgTys.push_back(argT);
1000 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1001 &ArgTys[0], ArgTys.size(),
1002 true /*isVariadic*/);
1003 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1004 msgSendIdent, msgSendType,
1005 FunctionDecl::Extern, false, 0);
1006}
1007
Steve Naroff874e2322007-11-15 10:28:18 +00001008// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1009void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1010 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1011 llvm::SmallVector<QualType, 16> ArgTys;
1012 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1013 &Context->Idents.get("objc_super"), 0);
1014 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1015 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1016 ArgTys.push_back(argT);
1017 argT = Context->getObjcSelType();
1018 assert(!argT.isNull() && "Can't find 'SEL' type");
1019 ArgTys.push_back(argT);
1020 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1021 &ArgTys[0], ArgTys.size(),
1022 true /*isVariadic*/);
1023 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1024 msgSendIdent, msgSendType,
1025 FunctionDecl::Extern, false, 0);
1026}
1027
Steve Naroff09b266e2007-10-30 23:14:51 +00001028// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1029void RewriteTest::SynthGetClassFunctionDecl() {
1030 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1031 llvm::SmallVector<QualType, 16> ArgTys;
1032 ArgTys.push_back(Context->getPointerType(
1033 Context->CharTy.getQualifiedType(QualType::Const)));
1034 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1035 &ArgTys[0], ArgTys.size(),
1036 false /*isVariadic*/);
1037 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1038 getClassIdent, getClassType,
1039 FunctionDecl::Extern, false, 0);
1040}
1041
Steve Naroff96984642007-11-08 14:30:50 +00001042// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1043void RewriteTest::SynthCFStringFunctionDecl() {
1044 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1045 llvm::SmallVector<QualType, 16> ArgTys;
1046 ArgTys.push_back(Context->getPointerType(
1047 Context->CharTy.getQualifiedType(QualType::Const)));
1048 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1049 &ArgTys[0], ArgTys.size(),
1050 false /*isVariadic*/);
1051 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1052 getClassIdent, getClassType,
1053 FunctionDecl::Extern, false, 0);
1054}
1055
Steve Naroffbeaf2992007-11-03 11:27:19 +00001056Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001057#if 1
1058 // This rewrite is specific to GCC, which has builtin support for CFString.
1059 if (!CFStringFunctionDecl)
1060 SynthCFStringFunctionDecl();
1061 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1062 llvm::SmallVector<Expr*, 8> StrExpr;
1063 StrExpr.push_back(Exp->getString());
1064 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1065 &StrExpr[0], StrExpr.size());
1066 // cast to NSConstantString *
1067 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1068 Rewrite.ReplaceStmt(Exp, cast);
1069 delete Exp;
1070 return cast;
1071#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001072 assert(ConstantStringClassReference && "Can't find constant string reference");
1073 llvm::SmallVector<Expr*, 4> InitExprs;
1074
1075 // Synthesize "(Class)&_NSConstantStringClassReference"
1076 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1077 ConstantStringClassReference->getType(),
1078 SourceLocation());
1079 QualType expType = Context->getPointerType(ClsRef->getType());
1080 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1081 expType, SourceLocation());
1082 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1083 SourceLocation());
1084 InitExprs.push_back(cast); // set the 'isa'.
1085 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1086 unsigned IntSize = static_cast<unsigned>(
1087 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1088 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1089 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1090 Exp->getLocStart());
1091 InitExprs.push_back(len); // set "int numBytes".
1092
1093 // struct NSConstantString
1094 QualType CFConstantStrType = Context->getCFConstantStringType();
1095 // (struct NSConstantString) { <exprs from above> }
1096 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1097 &InitExprs[0], InitExprs.size(),
1098 SourceLocation());
1099 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1100 // struct NSConstantString *
1101 expType = Context->getPointerType(StrRep->getType());
1102 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1103 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001104 // cast to NSConstantString *
1105 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001106 Rewrite.ReplaceStmt(Exp, cast);
1107 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001108 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001109#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001110}
1111
Steve Naroff874e2322007-11-15 10:28:18 +00001112ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1113 if (CurMethodDecl) { // check if we are sending a message to 'super'
1114 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1115 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1116 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1117 if (!strcmp(PVD->getName(), "self")) {
1118 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1119 if (ObjcInterfaceType *IT =
1120 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1121 if (IT->getDecl() ==
1122 CurMethodDecl->getClassInterface()->getSuperClass())
1123 return IT->getDecl();
1124 }
1125 }
1126 }
1127 }
1128 }
1129 }
1130 }
1131 return 0;
1132}
1133
1134// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1135QualType RewriteTest::getSuperStructType() {
1136 if (!SuperStructDecl) {
1137 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1138 &Context->Idents.get("objc_super"), 0);
1139 QualType FieldTypes[2];
1140
1141 // struct objc_object *receiver;
1142 FieldTypes[0] = Context->getObjcIdType();
1143 // struct objc_class *super;
1144 FieldTypes[1] = Context->getObjcClassType();
1145 // Create fields
1146 FieldDecl *FieldDecls[2];
1147
1148 for (unsigned i = 0; i < 2; ++i)
1149 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1150
1151 SuperStructDecl->defineBody(FieldDecls, 4);
1152 }
1153 return Context->getTagDeclType(SuperStructDecl);
1154}
1155
Steve Naroff934f2762007-10-24 22:48:43 +00001156Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001157 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001158 if (!MsgSendFunctionDecl)
1159 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001160 if (!MsgSendSuperFunctionDecl)
1161 SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001162 if (!GetClassFunctionDecl)
1163 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001164
Steve Naroff874e2322007-11-15 10:28:18 +00001165 // default to objc_msgSend().
1166 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1167
Steve Naroff934f2762007-10-24 22:48:43 +00001168 // Synthesize a call to objc_msgSend().
1169 llvm::SmallVector<Expr*, 8> MsgExprs;
1170 IdentifierInfo *clsName = Exp->getClassName();
1171
1172 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1173 if (clsName) { // class message.
1174 llvm::SmallVector<Expr*, 8> ClsExprs;
1175 QualType argType = Context->getPointerType(Context->CharTy);
1176 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1177 clsName->getLength(),
1178 false, argType, SourceLocation(),
1179 SourceLocation()));
1180 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1181 &ClsExprs[0], ClsExprs.size());
1182 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001183 } else { // instance message.
1184 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001185
1186 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1187 MsgSendFlavor = MsgSendSuperFunctionDecl;
1188 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1189
1190 llvm::SmallVector<Expr*, 4> InitExprs;
1191
1192 InitExprs.push_back(recExpr); // set the 'receiver'.
1193
1194 llvm::SmallVector<Expr*, 8> ClsExprs;
1195 QualType argType = Context->getPointerType(Context->CharTy);
1196 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1197 ID->getIdentifier()->getLength(),
1198 false, argType, SourceLocation(),
1199 SourceLocation()));
1200 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1201 &ClsExprs[0], ClsExprs.size());
1202 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1203 // struct objc_super
1204 QualType superType = getSuperStructType();
1205 // (struct objc_super) { <exprs from above> }
1206 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1207 &InitExprs[0], InitExprs.size(),
1208 SourceLocation());
1209 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1210 // struct objc_super *
1211 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1212 Context->getPointerType(SuperRep->getType()),
1213 SourceLocation());
1214 MsgExprs.push_back(Unop);
1215 } else {
1216 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1217 MsgExprs.push_back(recExpr);
1218 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001219 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001220 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001221 llvm::SmallVector<Expr*, 8> SelExprs;
1222 QualType argType = Context->getPointerType(Context->CharTy);
1223 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1224 Exp->getSelector().getName().size(),
1225 false, argType, SourceLocation(),
1226 SourceLocation()));
1227 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1228 &SelExprs[0], SelExprs.size());
1229 MsgExprs.push_back(SelExp);
1230
1231 // Now push any user supplied arguments.
1232 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001233 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001234 // Make all implicit casts explicit...ICE comes in handy:-)
1235 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1236 // Reuse the ICE type, it is exactly what the doctor ordered.
1237 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1238 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001239 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001240 // We've transferred the ownership to MsgExprs. Null out the argument in
1241 // the original expression, since we will delete it below.
1242 Exp->setArg(i, 0);
1243 }
Steve Naroffab972d32007-11-04 22:37:50 +00001244 // Generate the funky cast.
1245 CastExpr *cast;
1246 llvm::SmallVector<QualType, 8> ArgTypes;
1247 QualType returnType;
1248
1249 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001250 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1251 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1252 else
1253 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001254 ArgTypes.push_back(Context->getObjcSelType());
1255 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1256 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001257 for (int i = 0; i < mDecl->getNumParams(); i++) {
1258 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001259 ArgTypes.push_back(t);
1260 }
Steve Naroffab972d32007-11-04 22:37:50 +00001261 returnType = mDecl->getResultType();
1262 } else {
1263 returnType = Context->getObjcIdType();
1264 }
1265 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001266 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001267
1268 // Create a reference to the objc_msgSend() declaration.
Steve Naroff874e2322007-11-15 10:28:18 +00001269 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001270
1271 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1272 // If we don't do this cast, we get the following bizarre warning/note:
1273 // xx.m:13: warning: function called through a non-compatible type
1274 // xx.m:13: note: if this code is reached, the program will abort
1275 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1276 SourceLocation());
1277
1278 // Now do the "normal" pointer to function cast.
1279 QualType castType = Context->getFunctionType(returnType,
1280 &ArgTypes[0], ArgTypes.size(),
1281 false/*FIXME:variadic*/);
1282 castType = Context->getPointerType(castType);
1283 cast = new CastExpr(castType, cast, SourceLocation());
1284
1285 // Don't forget the parens to enforce the proper binding.
1286 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1287
1288 const FunctionType *FT = msgSendType->getAsFunctionType();
1289 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1290 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001291 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001292 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001293
Chris Lattnere64b7772007-10-24 16:57:36 +00001294 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001295 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001296}
1297
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001298/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1299/// an objective-c class with ivars.
1300void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1301 std::string &Result) {
1302 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1303 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001304 // Do not synthesize more than once.
1305 if (ObjcSynthesizedStructs.count(CDecl))
1306 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001307 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1308 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1309 // Do it for the root
1310 SynthesizeObjcInternalStruct(RCDecl, Result);
1311 }
1312
Steve Naroff03300712007-11-12 13:56:41 +00001313 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001314 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001315 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001316 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1317 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001318 // FIXME: This has potential of causing problem. If
1319 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001320 Result += "\nstruct ";
1321 Result += CDecl->getName();
1322
1323 SourceLocation LocStart = CDecl->getLocStart();
1324 SourceLocation LocEnd = CDecl->getLocEnd();
1325
1326 const char *startBuf = SM->getCharacterData(LocStart);
1327 const char *endBuf = SM->getCharacterData(LocEnd);
1328
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001329 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001330 const char *cursor = strchr(startBuf, '{');
1331 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001332 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001333
1334 // rewrite the original header *without* disturbing the '{'
1335 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1336 Result.c_str(), Result.size());
1337 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1338 Result = "\n struct ";
1339 Result += RCDecl->getName();
1340 Result += " _";
1341 Result += RCDecl->getName();
1342 Result += ";\n";
1343
1344 // insert the super class structure definition.
1345 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1346 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1347 }
1348 cursor++; // past '{'
1349
1350 // Now comment out any visibility specifiers.
1351 while (cursor < endBuf) {
1352 if (*cursor == '@') {
1353 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001354 // Skip whitespace.
1355 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1356 /*scan*/;
1357
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001358 // FIXME: presence of @public, etc. inside comment results in
1359 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001360 if (!strncmp(cursor, "public", strlen("public")) ||
1361 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001362 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001363 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001364 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001365 // FIXME: If there are cases where '<' is used in ivar declaration part
1366 // of user code, then scan the ivar list and use needToScanForQualifiers
1367 // for type checking.
1368 else if (*cursor == '<') {
1369 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1370 Rewrite.InsertText(atLoc, "/* ", 3);
1371 cursor = strchr(cursor, '>');
1372 cursor++;
1373 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1374 Rewrite.InsertText(atLoc, " */", 3);
1375 }
Steve Narofffea763e82007-11-14 19:25:57 +00001376 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001377 }
Steve Narofffea763e82007-11-14 19:25:57 +00001378 // Don't forget to add a ';'!!
1379 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1380 } else { // we don't have any instance variables - insert super struct.
1381 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1382 Result += " {\n struct ";
1383 Result += RCDecl->getName();
1384 Result += " _";
1385 Result += RCDecl->getName();
1386 Result += ";\n};\n";
1387 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1388 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001389 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001390 // Mark this struct as having been generated.
1391 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001392 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001393}
1394
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001395// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1396/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001397void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001398 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001399 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001400 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001401 const char *ClassName,
1402 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001403 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001404 if (NumMethods > 0 && !objc_impl_method) {
1405 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001406 SEL _cmd;
1407 char *method_types;
1408 void *_imp;
1409 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001410 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001411 Result += "\nstruct _objc_method {\n";
1412 Result += "\tSEL _cmd;\n";
1413 Result += "\tchar *method_types;\n";
1414 Result += "\tvoid *_imp;\n";
1415 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001416
1417 /* struct _objc_method_list {
1418 struct _objc_method_list *next_method;
1419 int method_count;
1420 struct _objc_method method_list[];
1421 }
1422 */
1423 Result += "\nstruct _objc_method_list {\n";
1424 Result += "\tstruct _objc_method_list *next_method;\n";
1425 Result += "\tint method_count;\n";
1426 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001427 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001428 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001429 // Build _objc_method_list for class's methods if needed
1430 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001431 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001432 Result += prefix;
1433 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1434 Result += "_METHODS_";
1435 Result += ClassName;
1436 Result += " __attribute__ ((section (\"__OBJC, __";
1437 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001438 Result += "_meth\")))= ";
1439 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1440
1441 Result += "\t,{{(SEL)\"";
1442 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001443 std::string MethodTypeString;
1444 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1445 Result += "\", \"";
1446 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001447 Result += "\", ";
1448 Result += MethodInternalNames[Methods[0]];
1449 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001450 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001451 Result += "\t ,{(SEL)\"";
1452 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001453 std::string MethodTypeString;
1454 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1455 Result += "\", \"";
1456 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001457 Result += "\", ";
1458 Result += MethodInternalNames[Methods[i]];
1459 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001460 }
1461 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001462 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001463}
1464
1465/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1466void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1467 int NumProtocols,
1468 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001469 const char *ClassName,
1470 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001471 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001472 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001473 for (int i = 0; i < NumProtocols; i++) {
1474 ObjcProtocolDecl *PDecl = Protocols[i];
1475 // Output struct protocol_methods holder of method selector and type.
1476 if (!objc_protocol_methods &&
1477 (PDecl->getNumInstanceMethods() > 0
1478 || PDecl->getNumClassMethods() > 0)) {
1479 /* struct protocol_methods {
1480 SEL _cmd;
1481 char *method_types;
1482 }
1483 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001484 Result += "\nstruct protocol_methods {\n";
1485 Result += "\tSEL _cmd;\n";
1486 Result += "\tchar *method_types;\n";
1487 Result += "};\n";
1488
1489 /* struct _objc_protocol_method_list {
1490 int protocol_method_count;
1491 struct protocol_methods protocols[];
1492 }
1493 */
1494 Result += "\nstruct _objc_protocol_method_list {\n";
1495 Result += "\tint protocol_method_count;\n";
1496 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001497 objc_protocol_methods = true;
1498 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001499
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001500 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001501 int NumMethods = PDecl->getNumInstanceMethods();
1502 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001503 Result += "\nstatic struct _objc_protocol_method_list "
1504 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1505 Result += PDecl->getName();
1506 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1507 "{\n\t" + utostr(NumMethods) + "\n";
1508
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001509 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001510 Result += "\t,{{(SEL)\"";
1511 Result += Methods[0]->getSelector().getName().c_str();
1512 Result += "\", \"\"}\n";
1513
1514 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001515 Result += "\t ,{(SEL)\"";
1516 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001517 std::string MethodTypeString;
1518 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1519 Result += "\", \"";
1520 Result += MethodTypeString;
1521 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001522 }
1523 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001524 }
1525
1526 // Output class methods declared in this protocol.
1527 NumMethods = PDecl->getNumClassMethods();
1528 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001529 Result += "\nstatic struct _objc_protocol_method_list "
1530 "_OBJC_PROTOCOL_CLASS_METHODS_";
1531 Result += PDecl->getName();
1532 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1533 "{\n\t";
1534 Result += utostr(NumMethods);
1535 Result += "\n";
1536
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001537 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001538 Result += "\t,{{(SEL)\"";
1539 Result += Methods[0]->getSelector().getName().c_str();
1540 Result += "\", \"\"}\n";
1541
1542 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001543 Result += "\t ,{(SEL)\"";
1544 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001545 std::string MethodTypeString;
1546 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1547 Result += "\", \"";
1548 Result += MethodTypeString;
1549 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001550 }
1551 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001552 }
1553 // Output:
1554 /* struct _objc_protocol {
1555 // Objective-C 1.0 extensions
1556 struct _objc_protocol_extension *isa;
1557 char *protocol_name;
1558 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001559 struct _objc_protocol_method_list *instance_methods;
1560 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001561 };
1562 */
1563 static bool objc_protocol = false;
1564 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001565 Result += "\nstruct _objc_protocol {\n";
1566 Result += "\tstruct _objc_protocol_extension *isa;\n";
1567 Result += "\tchar *protocol_name;\n";
1568 Result += "\tstruct _objc_protocol **protocol_list;\n";
1569 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1570 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1571 Result += "};\n";
1572
1573 /* struct _objc_protocol_list {
1574 struct _objc_protocol_list *next;
1575 int protocol_count;
1576 struct _objc_protocol *class_protocols[];
1577 }
1578 */
1579 Result += "\nstruct _objc_protocol_list {\n";
1580 Result += "\tstruct _objc_protocol_list *next;\n";
1581 Result += "\tint protocol_count;\n";
1582 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1583 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001584 objc_protocol = true;
1585 }
1586
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001587 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1588 Result += PDecl->getName();
1589 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1590 "{\n\t0, \"";
1591 Result += PDecl->getName();
1592 Result += "\", 0, ";
1593 if (PDecl->getInstanceMethods() > 0) {
1594 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1595 Result += PDecl->getName();
1596 Result += ", ";
1597 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001598 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001599 Result += "0, ";
1600 if (PDecl->getClassMethods() > 0) {
1601 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1602 Result += PDecl->getName();
1603 Result += "\n";
1604 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001605 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001606 Result += "0\n";
1607 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001608 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001609 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001610 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1611 Result += prefix;
1612 Result += "_PROTOCOLS_";
1613 Result += ClassName;
1614 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1615 "{\n\t0, ";
1616 Result += utostr(NumProtocols);
1617 Result += "\n";
1618
1619 Result += "\t,{&_OBJC_PROTOCOL_";
1620 Result += Protocols[0]->getName();
1621 Result += " \n";
1622
1623 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001624 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001625 Result += "\t ,&_OBJC_PROTOCOL_";
1626 Result += PDecl->getName();
1627 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001628 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001629 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001630 }
1631}
1632
1633/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1634/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001635void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1636 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001637 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1638 // Find category declaration for this implementation.
1639 ObjcCategoryDecl *CDecl;
1640 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1641 CDecl = CDecl->getNextClassCategory())
1642 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1643 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001644
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001645 char *FullCategoryName = (char*)alloca(
1646 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1647 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1648
1649 // Build _objc_method_list for class's instance methods if needed
1650 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1651 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001652 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001653 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001654
1655 // Build _objc_method_list for class's class methods if needed
1656 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1657 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001658 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001659 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001660
1661 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001662 // Null CDecl is case of a category implementation with no category interface
1663 if (CDecl)
1664 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1665 CDecl->getNumReferencedProtocols(),
1666 "CATEGORY",
1667 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001668
1669 /* struct _objc_category {
1670 char *category_name;
1671 char *class_name;
1672 struct _objc_method_list *instance_methods;
1673 struct _objc_method_list *class_methods;
1674 struct _objc_protocol_list *protocols;
1675 // Objective-C 1.0 extensions
1676 uint32_t size; // sizeof (struct _objc_category)
1677 struct _objc_property_list *instance_properties; // category's own
1678 // @property decl.
1679 };
1680 */
1681
1682 static bool objc_category = false;
1683 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001684 Result += "\nstruct _objc_category {\n";
1685 Result += "\tchar *category_name;\n";
1686 Result += "\tchar *class_name;\n";
1687 Result += "\tstruct _objc_method_list *instance_methods;\n";
1688 Result += "\tstruct _objc_method_list *class_methods;\n";
1689 Result += "\tstruct _objc_protocol_list *protocols;\n";
1690 Result += "\tunsigned int size;\n";
1691 Result += "\tstruct _objc_property_list *instance_properties;\n";
1692 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001693 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001694 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001695 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1696 Result += FullCategoryName;
1697 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1698 Result += IDecl->getName();
1699 Result += "\"\n\t, \"";
1700 Result += ClassDecl->getName();
1701 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001702
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001703 if (IDecl->getNumInstanceMethods() > 0) {
1704 Result += "\t, (struct _objc_method_list *)"
1705 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1706 Result += FullCategoryName;
1707 Result += "\n";
1708 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001709 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001710 Result += "\t, 0\n";
1711 if (IDecl->getNumClassMethods() > 0) {
1712 Result += "\t, (struct _objc_method_list *)"
1713 "&_OBJC_CATEGORY_CLASS_METHODS_";
1714 Result += FullCategoryName;
1715 Result += "\n";
1716 }
1717 else
1718 Result += "\t, 0\n";
1719
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001720 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001721 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1722 Result += FullCategoryName;
1723 Result += "\n";
1724 }
1725 else
1726 Result += "\t, 0\n";
1727 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001728}
1729
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001730/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1731/// ivar offset.
1732void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1733 ObjcIvarDecl *ivar,
1734 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001735 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001736 Result += IDecl->getName();
1737 Result += ", ";
1738 Result += ivar->getName();
1739 Result += ")";
1740}
1741
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001742//===----------------------------------------------------------------------===//
1743// Meta Data Emission
1744//===----------------------------------------------------------------------===//
1745
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001746void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1747 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001748 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1749
1750 // Build _objc_ivar_list metadata for classes ivars if needed
1751 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1752 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001753 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001754
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001755 SynthesizeObjcInternalStruct(CDecl, Result);
1756
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001757 if (NumIvars > 0) {
1758 static bool objc_ivar = false;
1759 if (!objc_ivar) {
1760 /* struct _objc_ivar {
1761 char *ivar_name;
1762 char *ivar_type;
1763 int ivar_offset;
1764 };
1765 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001766 Result += "\nstruct _objc_ivar {\n";
1767 Result += "\tchar *ivar_name;\n";
1768 Result += "\tchar *ivar_type;\n";
1769 Result += "\tint ivar_offset;\n";
1770 Result += "};\n";
1771
1772 /* struct _objc_ivar_list {
1773 int ivar_count;
1774 struct _objc_ivar ivar_list[];
1775 };
1776 */
1777 Result += "\nstruct _objc_ivar_list {\n";
1778 Result += "\tint ivar_count;\n";
1779 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001780 objc_ivar = true;
1781 }
1782
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001783 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1784 Result += IDecl->getName();
1785 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1786 "{\n\t";
1787 Result += utostr(NumIvars);
1788 Result += "\n";
1789
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001790 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1791 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001792 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001793 Result += "\t,{{\"";
1794 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001795 Result += "\", \"";
1796 std::string StrEncoding;
1797 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1798 Result += StrEncoding;
1799 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001800 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1801 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001802 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001803 Result += "\t ,{\"";
1804 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001805 Result += "\", \"";
1806 std::string StrEncoding;
1807 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1808 Result += StrEncoding;
1809 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001810 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1811 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001812 }
1813
1814 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001815 }
1816
1817 // Build _objc_method_list for class's instance methods if needed
1818 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1819 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001820 true,
1821 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001822
1823 // Build _objc_method_list for class's class methods if needed
1824 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001825 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001826 false,
1827 "", IDecl->getName(), Result);
1828
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001829 // Protocols referenced in class declaration?
1830 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1831 CDecl->getNumIntfRefProtocols(),
1832 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001833 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001834
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001835
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001836 // Declaration of class/meta-class metadata
1837 /* struct _objc_class {
1838 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001839 const char *super_class_name;
1840 char *name;
1841 long version;
1842 long info;
1843 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001844 struct _objc_ivar_list *ivars;
1845 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001846 struct objc_cache *cache;
1847 struct objc_protocol_list *protocols;
1848 const char *ivar_layout;
1849 struct _objc_class_ext *ext;
1850 };
1851 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001852 static bool objc_class = false;
1853 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001854 Result += "\nstruct _objc_class {\n";
1855 Result += "\tstruct _objc_class *isa;\n";
1856 Result += "\tconst char *super_class_name;\n";
1857 Result += "\tchar *name;\n";
1858 Result += "\tlong version;\n";
1859 Result += "\tlong info;\n";
1860 Result += "\tlong instance_size;\n";
1861 Result += "\tstruct _objc_ivar_list *ivars;\n";
1862 Result += "\tstruct _objc_method_list *methods;\n";
1863 Result += "\tstruct objc_cache *cache;\n";
1864 Result += "\tstruct _objc_protocol_list *protocols;\n";
1865 Result += "\tconst char *ivar_layout;\n";
1866 Result += "\tstruct _objc_class_ext *ext;\n";
1867 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001868 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001869 }
1870
1871 // Meta-class metadata generation.
1872 ObjcInterfaceDecl *RootClass = 0;
1873 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1874 while (SuperClass) {
1875 RootClass = SuperClass;
1876 SuperClass = SuperClass->getSuperClass();
1877 }
1878 SuperClass = CDecl->getSuperClass();
1879
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001880 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1881 Result += CDecl->getName();
1882 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1883 "{\n\t(struct _objc_class *)\"";
1884 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1885 Result += "\"";
1886
1887 if (SuperClass) {
1888 Result += ", \"";
1889 Result += SuperClass->getName();
1890 Result += "\", \"";
1891 Result += CDecl->getName();
1892 Result += "\"";
1893 }
1894 else {
1895 Result += ", 0, \"";
1896 Result += CDecl->getName();
1897 Result += "\"";
1898 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001899 // TODO: 'ivars' field for root class is currently set to 0.
1900 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001901 Result += ", 0,2, sizeof(struct _objc_class), 0";
1902 if (CDecl->getNumClassMethods() > 0) {
1903 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1904 Result += CDecl->getName();
1905 Result += "\n";
1906 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001907 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001908 Result += ", 0\n";
1909 if (CDecl->getNumIntfRefProtocols() > 0) {
1910 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1911 Result += CDecl->getName();
1912 Result += ",0,0\n";
1913 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001914 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001915 Result += "\t,0,0,0,0\n";
1916 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001917
1918 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001919 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1920 Result += CDecl->getName();
1921 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1922 "{\n\t&_OBJC_METACLASS_";
1923 Result += CDecl->getName();
1924 if (SuperClass) {
1925 Result += ", \"";
1926 Result += SuperClass->getName();
1927 Result += "\", \"";
1928 Result += CDecl->getName();
1929 Result += "\"";
1930 }
1931 else {
1932 Result += ", 0, \"";
1933 Result += CDecl->getName();
1934 Result += "\"";
1935 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001936 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001937 Result += ", 0,1";
1938 if (!ObjcSynthesizedStructs.count(CDecl))
1939 Result += ",0";
1940 else {
1941 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001942 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001943 Result += CDecl->getName();
1944 Result += ")";
1945 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001946 if (NumIvars > 0) {
1947 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1948 Result += CDecl->getName();
1949 Result += "\n\t";
1950 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001951 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001952 Result += ",0";
1953 if (IDecl->getNumInstanceMethods() > 0) {
1954 Result += ", &_OBJC_INSTANCE_METHODS_";
1955 Result += CDecl->getName();
1956 Result += ", 0\n\t";
1957 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001958 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001959 Result += ",0,0";
1960 if (CDecl->getNumIntfRefProtocols() > 0) {
1961 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1962 Result += CDecl->getName();
1963 Result += ", 0,0\n";
1964 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001965 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001966 Result += ",0,0,0\n";
1967 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001968}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001969
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001970/// RewriteImplementations - This routine rewrites all method implementations
1971/// and emits meta-data.
1972
1973void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001974 int ClsDefCount = ClassImplementation.size();
1975 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001976
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001977 if (ClsDefCount == 0 && CatDefCount == 0)
1978 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001979 // Rewrite implemented methods
1980 for (int i = 0; i < ClsDefCount; i++)
1981 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001982
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001983 for (int i = 0; i < CatDefCount; i++)
1984 RewriteImplementationDecl(CategoryImplementation[i]);
1985
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001986 // This is needed for use of offsetof
1987 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001988
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001989 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001990 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001991 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001992
1993 // For each implemented category, write out all its meta data.
1994 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001995 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001996
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001997 // Write objc_symtab metadata
1998 /*
1999 struct _objc_symtab
2000 {
2001 long sel_ref_cnt;
2002 SEL *refs;
2003 short cls_def_cnt;
2004 short cat_def_cnt;
2005 void *defs[cls_def_cnt + cat_def_cnt];
2006 };
2007 */
2008
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002009 Result += "\nstruct _objc_symtab {\n";
2010 Result += "\tlong sel_ref_cnt;\n";
2011 Result += "\tSEL *refs;\n";
2012 Result += "\tshort cls_def_cnt;\n";
2013 Result += "\tshort cat_def_cnt;\n";
2014 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2015 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002016
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002017 Result += "static struct _objc_symtab "
2018 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2019 Result += "\t0, 0, " + utostr(ClsDefCount)
2020 + ", " + utostr(CatDefCount) + "\n";
2021 for (int i = 0; i < ClsDefCount; i++) {
2022 Result += "\t,&_OBJC_CLASS_";
2023 Result += ClassImplementation[i]->getName();
2024 Result += "\n";
2025 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002026
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002027 for (int i = 0; i < CatDefCount; i++) {
2028 Result += "\t,&_OBJC_CATEGORY_";
2029 Result += CategoryImplementation[i]->getClassInterface()->getName();
2030 Result += "_";
2031 Result += CategoryImplementation[i]->getName();
2032 Result += "\n";
2033 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002034
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002035 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002036
2037 // Write objc_module metadata
2038
2039 /*
2040 struct _objc_module {
2041 long version;
2042 long size;
2043 const char *name;
2044 struct _objc_symtab *symtab;
2045 }
2046 */
2047
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002048 Result += "\nstruct _objc_module {\n";
2049 Result += "\tlong version;\n";
2050 Result += "\tlong size;\n";
2051 Result += "\tconst char *name;\n";
2052 Result += "\tstruct _objc_symtab *symtab;\n";
2053 Result += "};\n\n";
2054 Result += "static struct _objc_module "
2055 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002056 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2057 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002058 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002059
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002060}
Chris Lattner311ff022007-10-16 22:36:42 +00002061