blob: ba480c9e25e6f4fd8ea71a1fa22c005b4a896fe0 [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;
597 }
598 else
599 return IV;
600}
601
Chris Lattnerf04da132007-10-24 17:06:59 +0000602//===----------------------------------------------------------------------===//
603// Function Body / Expression rewriting
604//===----------------------------------------------------------------------===//
605
Steve Narofff3473a72007-11-09 15:20:18 +0000606Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000607 // Otherwise, just rewrite all children.
608 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
609 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000610 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000611 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000612 if (newStmt)
613 *CI = newStmt;
614 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000615
616 // Handle specific things.
617 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
618 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000619
620 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
621 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000622
623 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
624 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000625
626 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
627 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000628
Steve Naroff934f2762007-10-24 22:48:43 +0000629 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
630 // Before we rewrite it, put the original message expression in a comment.
631 SourceLocation startLoc = MessExpr->getLocStart();
632 SourceLocation endLoc = MessExpr->getLocEnd();
633
634 const char *startBuf = SM->getCharacterData(startLoc);
635 const char *endBuf = SM->getCharacterData(endLoc);
636
637 std::string messString;
638 messString += "// ";
639 messString.append(startBuf, endBuf-startBuf+1);
640 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000641
Steve Naroff934f2762007-10-24 22:48:43 +0000642 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
643 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
644 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000645 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000646 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000647 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000648
649 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
650 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000651
652 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
653 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000654#if 0
655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
656 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
657 // Get the new text.
658 std::ostringstream Buf;
659 Replacement->printPretty(Buf);
660 const std::string &Str = Buf.str();
661
662 printf("CAST = %s\n", &Str[0]);
663 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
664 delete S;
665 return Replacement;
666 }
667#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000668 // Return this stmt unmodified.
669 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000670}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000671
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000672Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000673 // Get the start location and compute the semi location.
674 SourceLocation startLoc = S->getLocStart();
675 const char *startBuf = SM->getCharacterData(startLoc);
676
677 assert((*startBuf == '@') && "bogus @try location");
678
679 std::string buf;
680 // declare a new scope with two variables, _stack and _rethrow.
681 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
682 buf += "int buf[18/*32-bit i386*/];\n";
683 buf += "char *pointers[4];} _stack;\n";
684 buf += "id volatile _rethrow = 0;\n";
685 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000686 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000687
688 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
689
690 startLoc = S->getTryBody()->getLocEnd();
691 startBuf = SM->getCharacterData(startLoc);
692
693 assert((*startBuf == '}') && "bogus @try block");
694
695 SourceLocation lastCurlyLoc = startLoc;
696
697 startLoc = startLoc.getFileLocWithOffset(1);
698 buf = " /* @catch begin */ else {\n";
699 buf += " id _caught = objc_exception_extract(&_stack);\n";
700 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000701 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
703 buf += " else { /* @catch continue */";
704
Chris Lattner28d1fe82007-11-08 04:41:51 +0000705 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000706
707 bool sawIdTypedCatch = false;
708 Stmt *lastCatchBody = 0;
709 ObjcAtCatchStmt *catchList = S->getCatchStmts();
710 while (catchList) {
711 Stmt *catchStmt = catchList->getCatchParamStmt();
712
713 if (catchList == S->getCatchStmts())
714 buf = "if ("; // we are generating code for the first catch clause
715 else
716 buf = "else if (";
717 startLoc = catchList->getLocStart();
718 startBuf = SM->getCharacterData(startLoc);
719
720 assert((*startBuf == '@') && "bogus @catch location");
721
722 const char *lParenLoc = strchr(startBuf, '(');
723
724 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
725 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
726 if (t == Context->getObjcIdType()) {
727 buf += "1) { ";
728 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
729 buf.c_str(), buf.size());
730 sawIdTypedCatch = true;
731 } else if (const PointerType *pType = t->getAsPointerType()) {
732 ObjcInterfaceType *cls; // Should be a pointer to a class.
733
734 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
735 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000736 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000737 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000738 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000739 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
740 buf.c_str(), buf.size());
741 }
742 }
743 // Now rewrite the body...
744 lastCatchBody = catchList->getCatchBody();
745 SourceLocation rParenLoc = catchList->getRParenLoc();
746 SourceLocation bodyLoc = lastCatchBody->getLocStart();
747 const char *bodyBuf = SM->getCharacterData(bodyLoc);
748 const char *rParenBuf = SM->getCharacterData(rParenLoc);
749 assert((*rParenBuf == ')') && "bogus @catch paren location");
750 assert((*bodyBuf == '{') && "bogus @catch body location");
751
752 buf = " = _caught;";
753 // Here we replace ") {" with "= _caught;" (which initializes and
754 // declares the @catch parameter).
755 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
756 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000757 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000758 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000759 }
Steve Naroff75730982007-11-07 04:08:17 +0000760 catchList = catchList->getNextCatchStmt();
761 }
762 // Complete the catch list...
763 if (lastCatchBody) {
764 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
765 const char *bodyBuf = SM->getCharacterData(bodyLoc);
766 assert((*bodyBuf == '}') && "bogus @catch body location");
767 bodyLoc = bodyLoc.getFileLocWithOffset(1);
768 buf = " } } /* @catch end */\n";
769
Chris Lattner28d1fe82007-11-08 04:41:51 +0000770 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000771
772 // Set lastCurlyLoc
773 lastCurlyLoc = lastCatchBody->getLocEnd();
774 }
775 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
776 startLoc = finalStmt->getLocStart();
777 startBuf = SM->getCharacterData(startLoc);
778 assert((*startBuf == '@') && "bogus @finally start");
779
780 buf = "/* @finally */";
781 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
782
783 Stmt *body = finalStmt->getFinallyBody();
784 SourceLocation startLoc = body->getLocStart();
785 SourceLocation endLoc = body->getLocEnd();
786 const char *startBuf = SM->getCharacterData(startLoc);
787 const char *endBuf = SM->getCharacterData(endLoc);
788 assert((*startBuf == '{') && "bogus @finally body location");
789 assert((*endBuf == '}') && "bogus @finally body location");
790
791 startLoc = startLoc.getFileLocWithOffset(1);
792 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000793 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000794 endLoc = endLoc.getFileLocWithOffset(-1);
795 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000796 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000797
798 // Set lastCurlyLoc
799 lastCurlyLoc = body->getLocEnd();
800 }
801 // Now emit the final closing curly brace...
802 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
803 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000804 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000805 return 0;
806}
807
808Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
809 return 0;
810}
811
812Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
813 return 0;
814}
815
Steve Naroff2bd03922007-11-07 15:32:26 +0000816// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
817// the throw expression is typically a message expression that's already
818// been rewritten! (which implies the SourceLocation's are invalid).
819Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
820 // Get the start location and compute the semi location.
821 SourceLocation startLoc = S->getLocStart();
822 const char *startBuf = SM->getCharacterData(startLoc);
823
824 assert((*startBuf == '@') && "bogus @throw location");
825
826 std::string buf;
827 /* void objc_exception_throw(id) __attribute__((noreturn)); */
828 buf = "objc_exception_throw(";
829 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
830 const char *semiBuf = strchr(startBuf, ';');
831 assert((*semiBuf == ';') && "@throw: can't find ';'");
832 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
833 buf = ");";
834 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
835 return 0;
836}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000837
Chris Lattnere64b7772007-10-24 16:57:36 +0000838Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000839 // Create a new string expression.
840 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000841 std::string StrEncoding;
842 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
843 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
844 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000845 SourceLocation(), SourceLocation());
846 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000847 delete Exp;
848 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000849}
850
Steve Naroffb42f8412007-11-05 14:50:49 +0000851Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
852 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
853 // Create a call to sel_registerName("selName").
854 llvm::SmallVector<Expr*, 8> SelExprs;
855 QualType argType = Context->getPointerType(Context->CharTy);
856 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
857 Exp->getSelector().getName().size(),
858 false, argType, SourceLocation(),
859 SourceLocation()));
860 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
861 &SelExprs[0], SelExprs.size());
862 Rewrite.ReplaceStmt(Exp, SelExp);
863 delete Exp;
864 return SelExp;
865}
866
Steve Naroff934f2762007-10-24 22:48:43 +0000867CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
868 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000869 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000870 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000871
872 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000873 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000874
875 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000876 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000877 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
878
879 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000880
Steve Naroff934f2762007-10-24 22:48:43 +0000881 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
882}
883
Steve Naroffd5255f52007-11-01 13:24:47 +0000884static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
885 const char *&startRef, const char *&endRef) {
886 while (startBuf < endBuf) {
887 if (*startBuf == '<')
888 startRef = startBuf; // mark the start.
889 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000890 if (startRef && *startRef == '<') {
891 endRef = startBuf; // mark the end.
892 return true;
893 }
894 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000895 }
896 startBuf++;
897 }
898 return false;
899}
900
901bool RewriteTest::needToScanForQualifiers(QualType T) {
902 // FIXME: we don't currently represent "id <Protocol>" in the type system.
903 if (T == Context->getObjcIdType())
904 return true;
905
906 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000907 Type *pointeeType = pType->getPointeeType().getTypePtr();
908 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
909 return true; // we have "Class <Protocol> *".
910 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000911 return false;
912}
913
914void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
915 const FunctionTypeProto *proto, FunctionDecl *FD) {
916
917 if (needToScanForQualifiers(proto->getResultType())) {
918 // Since types are unique, we need to scan the buffer.
919 SourceLocation Loc = FD->getLocation();
920
921 const char *endBuf = SM->getCharacterData(Loc);
922 const char *startBuf = endBuf;
923 while (*startBuf != ';')
924 startBuf--; // scan backward (from the decl location) for return type.
925 const char *startRef = 0, *endRef = 0;
926 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
927 // Get the locations of the startRef, endRef.
928 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
929 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
930 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000931 Rewrite.InsertText(LessLoc, "/*", 2);
932 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000933 }
934 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000935 // Now check arguments.
936 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
937 if (needToScanForQualifiers(proto->getArgType(i))) {
938 // Since types are unique, we need to scan the buffer.
939 SourceLocation Loc = FD->getLocation();
940
941 const char *startBuf = SM->getCharacterData(Loc);
942 const char *endBuf = startBuf;
943 while (*endBuf != ';')
944 endBuf++; // scan forward (from the decl location) for argument types.
945 const char *startRef = 0, *endRef = 0;
946 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
947 // Get the locations of the startRef, endRef.
948 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
949 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
950 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000951 Rewrite.InsertText(LessLoc, "/*", 2);
952 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000953 }
954 }
955 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000956}
957
Steve Naroff09b266e2007-10-30 23:14:51 +0000958void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
959 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000960 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000961 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000962 return;
963 }
964 // Check for ObjC 'id' and class types that have been adorned with protocol
965 // information (id<p>, C<p>*). The protocol references need to be rewritten!
966 const FunctionType *funcType = FD->getType()->getAsFunctionType();
967 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000968 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
969 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000970}
971
972// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
973void RewriteTest::SynthMsgSendFunctionDecl() {
974 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
975 llvm::SmallVector<QualType, 16> ArgTys;
976 QualType argT = Context->getObjcIdType();
977 assert(!argT.isNull() && "Can't find 'id' type");
978 ArgTys.push_back(argT);
979 argT = Context->getObjcSelType();
980 assert(!argT.isNull() && "Can't find 'SEL' type");
981 ArgTys.push_back(argT);
982 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
983 &ArgTys[0], ArgTys.size(),
984 true /*isVariadic*/);
985 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
986 msgSendIdent, msgSendType,
987 FunctionDecl::Extern, false, 0);
988}
989
Steve Naroff874e2322007-11-15 10:28:18 +0000990// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
991void RewriteTest::SynthMsgSendSuperFunctionDecl() {
992 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
993 llvm::SmallVector<QualType, 16> ArgTys;
994 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
995 &Context->Idents.get("objc_super"), 0);
996 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
997 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
998 ArgTys.push_back(argT);
999 argT = Context->getObjcSelType();
1000 assert(!argT.isNull() && "Can't find 'SEL' type");
1001 ArgTys.push_back(argT);
1002 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1003 &ArgTys[0], ArgTys.size(),
1004 true /*isVariadic*/);
1005 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1006 msgSendIdent, msgSendType,
1007 FunctionDecl::Extern, false, 0);
1008}
1009
Steve Naroff09b266e2007-10-30 23:14:51 +00001010// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1011void RewriteTest::SynthGetClassFunctionDecl() {
1012 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1013 llvm::SmallVector<QualType, 16> ArgTys;
1014 ArgTys.push_back(Context->getPointerType(
1015 Context->CharTy.getQualifiedType(QualType::Const)));
1016 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1017 &ArgTys[0], ArgTys.size(),
1018 false /*isVariadic*/);
1019 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1020 getClassIdent, getClassType,
1021 FunctionDecl::Extern, false, 0);
1022}
1023
Steve Naroff96984642007-11-08 14:30:50 +00001024// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1025void RewriteTest::SynthCFStringFunctionDecl() {
1026 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1027 llvm::SmallVector<QualType, 16> ArgTys;
1028 ArgTys.push_back(Context->getPointerType(
1029 Context->CharTy.getQualifiedType(QualType::Const)));
1030 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1031 &ArgTys[0], ArgTys.size(),
1032 false /*isVariadic*/);
1033 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1034 getClassIdent, getClassType,
1035 FunctionDecl::Extern, false, 0);
1036}
1037
Steve Naroffbeaf2992007-11-03 11:27:19 +00001038Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001039#if 1
1040 // This rewrite is specific to GCC, which has builtin support for CFString.
1041 if (!CFStringFunctionDecl)
1042 SynthCFStringFunctionDecl();
1043 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1044 llvm::SmallVector<Expr*, 8> StrExpr;
1045 StrExpr.push_back(Exp->getString());
1046 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1047 &StrExpr[0], StrExpr.size());
1048 // cast to NSConstantString *
1049 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1050 Rewrite.ReplaceStmt(Exp, cast);
1051 delete Exp;
1052 return cast;
1053#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001054 assert(ConstantStringClassReference && "Can't find constant string reference");
1055 llvm::SmallVector<Expr*, 4> InitExprs;
1056
1057 // Synthesize "(Class)&_NSConstantStringClassReference"
1058 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1059 ConstantStringClassReference->getType(),
1060 SourceLocation());
1061 QualType expType = Context->getPointerType(ClsRef->getType());
1062 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1063 expType, SourceLocation());
1064 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1065 SourceLocation());
1066 InitExprs.push_back(cast); // set the 'isa'.
1067 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1068 unsigned IntSize = static_cast<unsigned>(
1069 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1070 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1071 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1072 Exp->getLocStart());
1073 InitExprs.push_back(len); // set "int numBytes".
1074
1075 // struct NSConstantString
1076 QualType CFConstantStrType = Context->getCFConstantStringType();
1077 // (struct NSConstantString) { <exprs from above> }
1078 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1079 &InitExprs[0], InitExprs.size(),
1080 SourceLocation());
1081 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1082 // struct NSConstantString *
1083 expType = Context->getPointerType(StrRep->getType());
1084 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1085 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001086 // cast to NSConstantString *
1087 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001088 Rewrite.ReplaceStmt(Exp, cast);
1089 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001090 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001091#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001092}
1093
Steve Naroff874e2322007-11-15 10:28:18 +00001094ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1095 if (CurMethodDecl) { // check if we are sending a message to 'super'
1096 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1097 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1098 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1099 if (!strcmp(PVD->getName(), "self")) {
1100 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1101 if (ObjcInterfaceType *IT =
1102 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1103 if (IT->getDecl() ==
1104 CurMethodDecl->getClassInterface()->getSuperClass())
1105 return IT->getDecl();
1106 }
1107 }
1108 }
1109 }
1110 }
1111 }
1112 }
1113 return 0;
1114}
1115
1116// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1117QualType RewriteTest::getSuperStructType() {
1118 if (!SuperStructDecl) {
1119 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1120 &Context->Idents.get("objc_super"), 0);
1121 QualType FieldTypes[2];
1122
1123 // struct objc_object *receiver;
1124 FieldTypes[0] = Context->getObjcIdType();
1125 // struct objc_class *super;
1126 FieldTypes[1] = Context->getObjcClassType();
1127 // Create fields
1128 FieldDecl *FieldDecls[2];
1129
1130 for (unsigned i = 0; i < 2; ++i)
1131 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1132
1133 SuperStructDecl->defineBody(FieldDecls, 4);
1134 }
1135 return Context->getTagDeclType(SuperStructDecl);
1136}
1137
Steve Naroff934f2762007-10-24 22:48:43 +00001138Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001139 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001140 if (!MsgSendFunctionDecl)
1141 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001142 if (!MsgSendSuperFunctionDecl)
1143 SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001144 if (!GetClassFunctionDecl)
1145 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001146
Steve Naroff874e2322007-11-15 10:28:18 +00001147 // default to objc_msgSend().
1148 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1149
Steve Naroff934f2762007-10-24 22:48:43 +00001150 // Synthesize a call to objc_msgSend().
1151 llvm::SmallVector<Expr*, 8> MsgExprs;
1152 IdentifierInfo *clsName = Exp->getClassName();
1153
1154 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1155 if (clsName) { // class message.
1156 llvm::SmallVector<Expr*, 8> ClsExprs;
1157 QualType argType = Context->getPointerType(Context->CharTy);
1158 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1159 clsName->getLength(),
1160 false, argType, SourceLocation(),
1161 SourceLocation()));
1162 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1163 &ClsExprs[0], ClsExprs.size());
1164 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001165 } else { // instance message.
1166 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001167
1168 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1169 MsgSendFlavor = MsgSendSuperFunctionDecl;
1170 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1171
1172 llvm::SmallVector<Expr*, 4> InitExprs;
1173
1174 InitExprs.push_back(recExpr); // set the 'receiver'.
1175
1176 llvm::SmallVector<Expr*, 8> ClsExprs;
1177 QualType argType = Context->getPointerType(Context->CharTy);
1178 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1179 ID->getIdentifier()->getLength(),
1180 false, argType, SourceLocation(),
1181 SourceLocation()));
1182 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1183 &ClsExprs[0], ClsExprs.size());
1184 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1185 // struct objc_super
1186 QualType superType = getSuperStructType();
1187 // (struct objc_super) { <exprs from above> }
1188 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1189 &InitExprs[0], InitExprs.size(),
1190 SourceLocation());
1191 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1192 // struct objc_super *
1193 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1194 Context->getPointerType(SuperRep->getType()),
1195 SourceLocation());
1196 MsgExprs.push_back(Unop);
1197 } else {
1198 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1199 MsgExprs.push_back(recExpr);
1200 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001201 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001202 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001203 llvm::SmallVector<Expr*, 8> SelExprs;
1204 QualType argType = Context->getPointerType(Context->CharTy);
1205 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1206 Exp->getSelector().getName().size(),
1207 false, argType, SourceLocation(),
1208 SourceLocation()));
1209 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1210 &SelExprs[0], SelExprs.size());
1211 MsgExprs.push_back(SelExp);
1212
1213 // Now push any user supplied arguments.
1214 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001215 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001216 // Make all implicit casts explicit...ICE comes in handy:-)
1217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1218 // Reuse the ICE type, it is exactly what the doctor ordered.
1219 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1220 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001221 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001222 // We've transferred the ownership to MsgExprs. Null out the argument in
1223 // the original expression, since we will delete it below.
1224 Exp->setArg(i, 0);
1225 }
Steve Naroffab972d32007-11-04 22:37:50 +00001226 // Generate the funky cast.
1227 CastExpr *cast;
1228 llvm::SmallVector<QualType, 8> ArgTypes;
1229 QualType returnType;
1230
1231 // Push 'id' and 'SEL', the 2 implicit arguments.
1232 ArgTypes.push_back(Context->getObjcIdType());
1233 ArgTypes.push_back(Context->getObjcSelType());
1234 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1235 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001236 for (int i = 0; i < mDecl->getNumParams(); i++) {
1237 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001238 ArgTypes.push_back(t);
1239 }
Steve Naroffab972d32007-11-04 22:37:50 +00001240 returnType = mDecl->getResultType();
1241 } else {
1242 returnType = Context->getObjcIdType();
1243 }
1244 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001245 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001246
1247 // Create a reference to the objc_msgSend() declaration.
Steve Naroff874e2322007-11-15 10:28:18 +00001248 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001249
1250 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1251 // If we don't do this cast, we get the following bizarre warning/note:
1252 // xx.m:13: warning: function called through a non-compatible type
1253 // xx.m:13: note: if this code is reached, the program will abort
1254 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1255 SourceLocation());
1256
1257 // Now do the "normal" pointer to function cast.
1258 QualType castType = Context->getFunctionType(returnType,
1259 &ArgTypes[0], ArgTypes.size(),
1260 false/*FIXME:variadic*/);
1261 castType = Context->getPointerType(castType);
1262 cast = new CastExpr(castType, cast, SourceLocation());
1263
1264 // Don't forget the parens to enforce the proper binding.
1265 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1266
1267 const FunctionType *FT = msgSendType->getAsFunctionType();
1268 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1269 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001270 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001271 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001272
Chris Lattnere64b7772007-10-24 16:57:36 +00001273 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001274 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001275}
1276
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001277/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1278/// an objective-c class with ivars.
1279void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1280 std::string &Result) {
1281 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1282 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001283 // Do not synthesize more than once.
1284 if (ObjcSynthesizedStructs.count(CDecl))
1285 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001286 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1287 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1288 // Do it for the root
1289 SynthesizeObjcInternalStruct(RCDecl, Result);
1290 }
1291
Steve Naroff03300712007-11-12 13:56:41 +00001292 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001293 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001294 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001295 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1296 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001297 // FIXME: This has potential of causing problem. If
1298 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001299 Result += "\nstruct ";
1300 Result += CDecl->getName();
1301
1302 SourceLocation LocStart = CDecl->getLocStart();
1303 SourceLocation LocEnd = CDecl->getLocEnd();
1304
1305 const char *startBuf = SM->getCharacterData(LocStart);
1306 const char *endBuf = SM->getCharacterData(LocEnd);
1307
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001308 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001309 const char *cursor = strchr(startBuf, '{');
1310 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001311 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001312
1313 // rewrite the original header *without* disturbing the '{'
1314 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1315 Result.c_str(), Result.size());
1316 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1317 Result = "\n struct ";
1318 Result += RCDecl->getName();
1319 Result += " _";
1320 Result += RCDecl->getName();
1321 Result += ";\n";
1322
1323 // insert the super class structure definition.
1324 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1325 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1326 }
1327 cursor++; // past '{'
1328
1329 // Now comment out any visibility specifiers.
1330 while (cursor < endBuf) {
1331 if (*cursor == '@') {
1332 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001333 // Skip whitespace.
1334 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1335 /*scan*/;
1336
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001337 // FIXME: presence of @public, etc. inside comment results in
1338 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001339 if (!strncmp(cursor, "public", strlen("public")) ||
1340 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001341 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001342 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001343 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001344 // FIXME: If there are cases where '<' is used in ivar declaration part
1345 // of user code, then scan the ivar list and use needToScanForQualifiers
1346 // for type checking.
1347 else if (*cursor == '<') {
1348 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1349 Rewrite.InsertText(atLoc, "/* ", 3);
1350 cursor = strchr(cursor, '>');
1351 cursor++;
1352 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1353 Rewrite.InsertText(atLoc, " */", 3);
1354 }
Steve Narofffea763e82007-11-14 19:25:57 +00001355 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001356 }
Steve Narofffea763e82007-11-14 19:25:57 +00001357 // Don't forget to add a ';'!!
1358 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1359 } else { // we don't have any instance variables - insert super struct.
1360 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1361 Result += " {\n struct ";
1362 Result += RCDecl->getName();
1363 Result += " _";
1364 Result += RCDecl->getName();
1365 Result += ";\n};\n";
1366 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1367 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001368 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001369 // Mark this struct as having been generated.
1370 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001371 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001372}
1373
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001374// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1375/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001376void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001377 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001378 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001379 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001380 const char *ClassName,
1381 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001382 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001383 if (NumMethods > 0 && !objc_impl_method) {
1384 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001385 SEL _cmd;
1386 char *method_types;
1387 void *_imp;
1388 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001389 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001390 Result += "\nstruct _objc_method {\n";
1391 Result += "\tSEL _cmd;\n";
1392 Result += "\tchar *method_types;\n";
1393 Result += "\tvoid *_imp;\n";
1394 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001395
1396 /* struct _objc_method_list {
1397 struct _objc_method_list *next_method;
1398 int method_count;
1399 struct _objc_method method_list[];
1400 }
1401 */
1402 Result += "\nstruct _objc_method_list {\n";
1403 Result += "\tstruct _objc_method_list *next_method;\n";
1404 Result += "\tint method_count;\n";
1405 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001406 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001407 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001408 // Build _objc_method_list for class's methods if needed
1409 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001410 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001411 Result += prefix;
1412 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1413 Result += "_METHODS_";
1414 Result += ClassName;
1415 Result += " __attribute__ ((section (\"__OBJC, __";
1416 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001417 Result += "_meth\")))= ";
1418 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1419
1420 Result += "\t,{{(SEL)\"";
1421 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001422 std::string MethodTypeString;
1423 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1424 Result += "\", \"";
1425 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001426 Result += "\", ";
1427 Result += MethodInternalNames[Methods[0]];
1428 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001429 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001430 Result += "\t ,{(SEL)\"";
1431 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001432 std::string MethodTypeString;
1433 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1434 Result += "\", \"";
1435 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001436 Result += "\", ";
1437 Result += MethodInternalNames[Methods[i]];
1438 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001439 }
1440 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001441 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001442}
1443
1444/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1445void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1446 int NumProtocols,
1447 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001448 const char *ClassName,
1449 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001450 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001451 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001452 for (int i = 0; i < NumProtocols; i++) {
1453 ObjcProtocolDecl *PDecl = Protocols[i];
1454 // Output struct protocol_methods holder of method selector and type.
1455 if (!objc_protocol_methods &&
1456 (PDecl->getNumInstanceMethods() > 0
1457 || PDecl->getNumClassMethods() > 0)) {
1458 /* struct protocol_methods {
1459 SEL _cmd;
1460 char *method_types;
1461 }
1462 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001463 Result += "\nstruct protocol_methods {\n";
1464 Result += "\tSEL _cmd;\n";
1465 Result += "\tchar *method_types;\n";
1466 Result += "};\n";
1467
1468 /* struct _objc_protocol_method_list {
1469 int protocol_method_count;
1470 struct protocol_methods protocols[];
1471 }
1472 */
1473 Result += "\nstruct _objc_protocol_method_list {\n";
1474 Result += "\tint protocol_method_count;\n";
1475 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001476 objc_protocol_methods = true;
1477 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001478
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001479 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001480 int NumMethods = PDecl->getNumInstanceMethods();
1481 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001482 Result += "\nstatic struct _objc_protocol_method_list "
1483 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1484 Result += PDecl->getName();
1485 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1486 "{\n\t" + utostr(NumMethods) + "\n";
1487
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001488 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001489 Result += "\t,{{(SEL)\"";
1490 Result += Methods[0]->getSelector().getName().c_str();
1491 Result += "\", \"\"}\n";
1492
1493 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001494 Result += "\t ,{(SEL)\"";
1495 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001496 std::string MethodTypeString;
1497 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1498 Result += "\", \"";
1499 Result += MethodTypeString;
1500 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001501 }
1502 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001503 }
1504
1505 // Output class methods declared in this protocol.
1506 NumMethods = PDecl->getNumClassMethods();
1507 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001508 Result += "\nstatic struct _objc_protocol_method_list "
1509 "_OBJC_PROTOCOL_CLASS_METHODS_";
1510 Result += PDecl->getName();
1511 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1512 "{\n\t";
1513 Result += utostr(NumMethods);
1514 Result += "\n";
1515
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001516 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001517 Result += "\t,{{(SEL)\"";
1518 Result += Methods[0]->getSelector().getName().c_str();
1519 Result += "\", \"\"}\n";
1520
1521 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001522 Result += "\t ,{(SEL)\"";
1523 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001524 std::string MethodTypeString;
1525 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1526 Result += "\", \"";
1527 Result += MethodTypeString;
1528 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001529 }
1530 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001531 }
1532 // Output:
1533 /* struct _objc_protocol {
1534 // Objective-C 1.0 extensions
1535 struct _objc_protocol_extension *isa;
1536 char *protocol_name;
1537 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001538 struct _objc_protocol_method_list *instance_methods;
1539 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001540 };
1541 */
1542 static bool objc_protocol = false;
1543 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001544 Result += "\nstruct _objc_protocol {\n";
1545 Result += "\tstruct _objc_protocol_extension *isa;\n";
1546 Result += "\tchar *protocol_name;\n";
1547 Result += "\tstruct _objc_protocol **protocol_list;\n";
1548 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1549 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1550 Result += "};\n";
1551
1552 /* struct _objc_protocol_list {
1553 struct _objc_protocol_list *next;
1554 int protocol_count;
1555 struct _objc_protocol *class_protocols[];
1556 }
1557 */
1558 Result += "\nstruct _objc_protocol_list {\n";
1559 Result += "\tstruct _objc_protocol_list *next;\n";
1560 Result += "\tint protocol_count;\n";
1561 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1562 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001563 objc_protocol = true;
1564 }
1565
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001566 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1567 Result += PDecl->getName();
1568 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1569 "{\n\t0, \"";
1570 Result += PDecl->getName();
1571 Result += "\", 0, ";
1572 if (PDecl->getInstanceMethods() > 0) {
1573 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1574 Result += PDecl->getName();
1575 Result += ", ";
1576 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001577 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001578 Result += "0, ";
1579 if (PDecl->getClassMethods() > 0) {
1580 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1581 Result += PDecl->getName();
1582 Result += "\n";
1583 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001584 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001585 Result += "0\n";
1586 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001587 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001588 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001589 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1590 Result += prefix;
1591 Result += "_PROTOCOLS_";
1592 Result += ClassName;
1593 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1594 "{\n\t0, ";
1595 Result += utostr(NumProtocols);
1596 Result += "\n";
1597
1598 Result += "\t,{&_OBJC_PROTOCOL_";
1599 Result += Protocols[0]->getName();
1600 Result += " \n";
1601
1602 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001603 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001604 Result += "\t ,&_OBJC_PROTOCOL_";
1605 Result += PDecl->getName();
1606 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001607 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001608 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001609 }
1610}
1611
1612/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1613/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001614void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1615 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001616 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1617 // Find category declaration for this implementation.
1618 ObjcCategoryDecl *CDecl;
1619 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1620 CDecl = CDecl->getNextClassCategory())
1621 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1622 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001623
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001624 char *FullCategoryName = (char*)alloca(
1625 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1626 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1627
1628 // Build _objc_method_list for class's instance methods if needed
1629 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1630 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001631 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001632 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001633
1634 // Build _objc_method_list for class's class methods if needed
1635 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1636 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001637 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001638 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001639
1640 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001641 // Null CDecl is case of a category implementation with no category interface
1642 if (CDecl)
1643 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1644 CDecl->getNumReferencedProtocols(),
1645 "CATEGORY",
1646 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001647
1648 /* struct _objc_category {
1649 char *category_name;
1650 char *class_name;
1651 struct _objc_method_list *instance_methods;
1652 struct _objc_method_list *class_methods;
1653 struct _objc_protocol_list *protocols;
1654 // Objective-C 1.0 extensions
1655 uint32_t size; // sizeof (struct _objc_category)
1656 struct _objc_property_list *instance_properties; // category's own
1657 // @property decl.
1658 };
1659 */
1660
1661 static bool objc_category = false;
1662 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001663 Result += "\nstruct _objc_category {\n";
1664 Result += "\tchar *category_name;\n";
1665 Result += "\tchar *class_name;\n";
1666 Result += "\tstruct _objc_method_list *instance_methods;\n";
1667 Result += "\tstruct _objc_method_list *class_methods;\n";
1668 Result += "\tstruct _objc_protocol_list *protocols;\n";
1669 Result += "\tunsigned int size;\n";
1670 Result += "\tstruct _objc_property_list *instance_properties;\n";
1671 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001672 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001673 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001674 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1675 Result += FullCategoryName;
1676 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1677 Result += IDecl->getName();
1678 Result += "\"\n\t, \"";
1679 Result += ClassDecl->getName();
1680 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001681
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001682 if (IDecl->getNumInstanceMethods() > 0) {
1683 Result += "\t, (struct _objc_method_list *)"
1684 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1685 Result += FullCategoryName;
1686 Result += "\n";
1687 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001688 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001689 Result += "\t, 0\n";
1690 if (IDecl->getNumClassMethods() > 0) {
1691 Result += "\t, (struct _objc_method_list *)"
1692 "&_OBJC_CATEGORY_CLASS_METHODS_";
1693 Result += FullCategoryName;
1694 Result += "\n";
1695 }
1696 else
1697 Result += "\t, 0\n";
1698
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001699 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001700 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1701 Result += FullCategoryName;
1702 Result += "\n";
1703 }
1704 else
1705 Result += "\t, 0\n";
1706 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001707}
1708
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001709/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1710/// ivar offset.
1711void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1712 ObjcIvarDecl *ivar,
1713 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001714 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001715 Result += IDecl->getName();
1716 Result += ", ";
1717 Result += ivar->getName();
1718 Result += ")";
1719}
1720
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001721//===----------------------------------------------------------------------===//
1722// Meta Data Emission
1723//===----------------------------------------------------------------------===//
1724
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001725void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1726 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001727 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1728
1729 // Build _objc_ivar_list metadata for classes ivars if needed
1730 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1731 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001732 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001733
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001734 SynthesizeObjcInternalStruct(CDecl, Result);
1735
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001736 if (NumIvars > 0) {
1737 static bool objc_ivar = false;
1738 if (!objc_ivar) {
1739 /* struct _objc_ivar {
1740 char *ivar_name;
1741 char *ivar_type;
1742 int ivar_offset;
1743 };
1744 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001745 Result += "\nstruct _objc_ivar {\n";
1746 Result += "\tchar *ivar_name;\n";
1747 Result += "\tchar *ivar_type;\n";
1748 Result += "\tint ivar_offset;\n";
1749 Result += "};\n";
1750
1751 /* struct _objc_ivar_list {
1752 int ivar_count;
1753 struct _objc_ivar ivar_list[];
1754 };
1755 */
1756 Result += "\nstruct _objc_ivar_list {\n";
1757 Result += "\tint ivar_count;\n";
1758 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001759 objc_ivar = true;
1760 }
1761
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001762 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1763 Result += IDecl->getName();
1764 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1765 "{\n\t";
1766 Result += utostr(NumIvars);
1767 Result += "\n";
1768
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001769 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1770 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001771 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001772 Result += "\t,{{\"";
1773 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001774 Result += "\", \"";
1775 std::string StrEncoding;
1776 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1777 Result += StrEncoding;
1778 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001779 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1780 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001781 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001782 Result += "\t ,{\"";
1783 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001784 Result += "\", \"";
1785 std::string StrEncoding;
1786 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1787 Result += StrEncoding;
1788 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001789 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1790 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001791 }
1792
1793 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001794 }
1795
1796 // Build _objc_method_list for class's instance methods if needed
1797 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1798 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001799 true,
1800 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001801
1802 // Build _objc_method_list for class's class methods if needed
1803 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001804 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001805 false,
1806 "", IDecl->getName(), Result);
1807
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001808 // Protocols referenced in class declaration?
1809 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1810 CDecl->getNumIntfRefProtocols(),
1811 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001812 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001813
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001814
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001815 // Declaration of class/meta-class metadata
1816 /* struct _objc_class {
1817 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001818 const char *super_class_name;
1819 char *name;
1820 long version;
1821 long info;
1822 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001823 struct _objc_ivar_list *ivars;
1824 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001825 struct objc_cache *cache;
1826 struct objc_protocol_list *protocols;
1827 const char *ivar_layout;
1828 struct _objc_class_ext *ext;
1829 };
1830 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001831 static bool objc_class = false;
1832 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001833 Result += "\nstruct _objc_class {\n";
1834 Result += "\tstruct _objc_class *isa;\n";
1835 Result += "\tconst char *super_class_name;\n";
1836 Result += "\tchar *name;\n";
1837 Result += "\tlong version;\n";
1838 Result += "\tlong info;\n";
1839 Result += "\tlong instance_size;\n";
1840 Result += "\tstruct _objc_ivar_list *ivars;\n";
1841 Result += "\tstruct _objc_method_list *methods;\n";
1842 Result += "\tstruct objc_cache *cache;\n";
1843 Result += "\tstruct _objc_protocol_list *protocols;\n";
1844 Result += "\tconst char *ivar_layout;\n";
1845 Result += "\tstruct _objc_class_ext *ext;\n";
1846 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001847 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001848 }
1849
1850 // Meta-class metadata generation.
1851 ObjcInterfaceDecl *RootClass = 0;
1852 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1853 while (SuperClass) {
1854 RootClass = SuperClass;
1855 SuperClass = SuperClass->getSuperClass();
1856 }
1857 SuperClass = CDecl->getSuperClass();
1858
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001859 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1860 Result += CDecl->getName();
1861 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1862 "{\n\t(struct _objc_class *)\"";
1863 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1864 Result += "\"";
1865
1866 if (SuperClass) {
1867 Result += ", \"";
1868 Result += SuperClass->getName();
1869 Result += "\", \"";
1870 Result += CDecl->getName();
1871 Result += "\"";
1872 }
1873 else {
1874 Result += ", 0, \"";
1875 Result += CDecl->getName();
1876 Result += "\"";
1877 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001878 // TODO: 'ivars' field for root class is currently set to 0.
1879 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001880 Result += ", 0,2, sizeof(struct _objc_class), 0";
1881 if (CDecl->getNumClassMethods() > 0) {
1882 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1883 Result += CDecl->getName();
1884 Result += "\n";
1885 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001886 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001887 Result += ", 0\n";
1888 if (CDecl->getNumIntfRefProtocols() > 0) {
1889 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1890 Result += CDecl->getName();
1891 Result += ",0,0\n";
1892 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001893 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001894 Result += "\t,0,0,0,0\n";
1895 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001896
1897 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001898 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1899 Result += CDecl->getName();
1900 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1901 "{\n\t&_OBJC_METACLASS_";
1902 Result += CDecl->getName();
1903 if (SuperClass) {
1904 Result += ", \"";
1905 Result += SuperClass->getName();
1906 Result += "\", \"";
1907 Result += CDecl->getName();
1908 Result += "\"";
1909 }
1910 else {
1911 Result += ", 0, \"";
1912 Result += CDecl->getName();
1913 Result += "\"";
1914 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001915 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001916 Result += ", 0,1";
1917 if (!ObjcSynthesizedStructs.count(CDecl))
1918 Result += ",0";
1919 else {
1920 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001921 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001922 Result += CDecl->getName();
1923 Result += ")";
1924 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001925 if (NumIvars > 0) {
1926 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1927 Result += CDecl->getName();
1928 Result += "\n\t";
1929 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001930 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001931 Result += ",0";
1932 if (IDecl->getNumInstanceMethods() > 0) {
1933 Result += ", &_OBJC_INSTANCE_METHODS_";
1934 Result += CDecl->getName();
1935 Result += ", 0\n\t";
1936 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001937 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001938 Result += ",0,0";
1939 if (CDecl->getNumIntfRefProtocols() > 0) {
1940 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1941 Result += CDecl->getName();
1942 Result += ", 0,0\n";
1943 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001944 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001945 Result += ",0,0,0\n";
1946 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001947}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001948
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001949/// RewriteImplementations - This routine rewrites all method implementations
1950/// and emits meta-data.
1951
1952void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001953 int ClsDefCount = ClassImplementation.size();
1954 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001955
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001956 if (ClsDefCount == 0 && CatDefCount == 0)
1957 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001958 // Rewrite implemented methods
1959 for (int i = 0; i < ClsDefCount; i++)
1960 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001961
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001962 for (int i = 0; i < CatDefCount; i++)
1963 RewriteImplementationDecl(CategoryImplementation[i]);
1964
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001965 // This is needed for use of offsetof
1966 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001967
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001968 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001969 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001970 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001971
1972 // For each implemented category, write out all its meta data.
1973 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001974 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001975
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001976 // Write objc_symtab metadata
1977 /*
1978 struct _objc_symtab
1979 {
1980 long sel_ref_cnt;
1981 SEL *refs;
1982 short cls_def_cnt;
1983 short cat_def_cnt;
1984 void *defs[cls_def_cnt + cat_def_cnt];
1985 };
1986 */
1987
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001988 Result += "\nstruct _objc_symtab {\n";
1989 Result += "\tlong sel_ref_cnt;\n";
1990 Result += "\tSEL *refs;\n";
1991 Result += "\tshort cls_def_cnt;\n";
1992 Result += "\tshort cat_def_cnt;\n";
1993 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1994 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001995
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001996 Result += "static struct _objc_symtab "
1997 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1998 Result += "\t0, 0, " + utostr(ClsDefCount)
1999 + ", " + utostr(CatDefCount) + "\n";
2000 for (int i = 0; i < ClsDefCount; i++) {
2001 Result += "\t,&_OBJC_CLASS_";
2002 Result += ClassImplementation[i]->getName();
2003 Result += "\n";
2004 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002005
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002006 for (int i = 0; i < CatDefCount; i++) {
2007 Result += "\t,&_OBJC_CATEGORY_";
2008 Result += CategoryImplementation[i]->getClassInterface()->getName();
2009 Result += "_";
2010 Result += CategoryImplementation[i]->getName();
2011 Result += "\n";
2012 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002013
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002014 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002015
2016 // Write objc_module metadata
2017
2018 /*
2019 struct _objc_module {
2020 long version;
2021 long size;
2022 const char *name;
2023 struct _objc_symtab *symtab;
2024 }
2025 */
2026
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002027 Result += "\nstruct _objc_module {\n";
2028 Result += "\tlong version;\n";
2029 Result += "\tlong size;\n";
2030 Result += "\tconst char *name;\n";
2031 Result += "\tstruct _objc_symtab *symtab;\n";
2032 Result += "};\n\n";
2033 Result += "static struct _objc_module "
2034 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002035 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2036 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002037 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002038
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002039}
Chris Lattner311ff022007-10-16 22:36:42 +00002040