blob: 808fe98798257d9238984d77e067f444951ce06f [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 Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000021#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000022#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000023#include "clang/Lex/Lexer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000024#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000025using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000026using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000027
Chris Lattner77cd2a02007-10-11 00:43:27 +000028namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000029 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000030 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000031 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000032 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000034 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000035 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000036 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
37 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000038 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000039 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000040 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000041
42 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000043 FunctionDecl *MsgSendSuperFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000044 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000045 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000046 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000047
Steve Naroffbeaf2992007-11-03 11:27:19 +000048 // ObjC string constant support.
49 FileVarDecl *ConstantStringClassReference;
50 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000051
Steve Naroff874e2322007-11-15 10:28:18 +000052 // Needed for super.
53 ObjcMethodDecl *CurMethodDecl;
54 RecordDecl *SuperStructDecl;
55
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000056 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000057 public:
Chris Lattner01c57482007-10-17 22:35:30 +000058 void Initialize(ASTContext &context, unsigned mainFileID) {
59 Context = &context;
60 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000061 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000062 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000063 MsgSendSuperFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000064 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000065 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000066 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000067 ConstantStringClassReference = 0;
68 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 CurMethodDecl = 0;
70 SuperStructDecl = 0;
71
Chris Lattner01c57482007-10-17 22:35:30 +000072 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000073 // declaring objc_selector outside the parameter list removes a silly
74 // scope related warning...
Steve Narofff6248702007-11-15 17:06:21 +000075 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000076 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000077 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000078 "extern struct objc_object *objc_msgSendSuper"
79 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +000080 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000081 "(const char *);\n"
82 "extern void objc_exception_throw(struct objc_object *);\n"
83 "extern void objc_exception_try_enter(void *);\n"
84 "extern void objc_exception_try_exit(void *);\n"
85 "extern struct objc_object *objc_exception_extract(void *);\n"
86 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +000087 "(struct objc_class *, struct objc_object *, ...);\n"
88 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000089
Steve Naroffab972d32007-11-04 22:37:50 +000090 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
91 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000092 }
Chris Lattner8a12c272007-10-11 18:38:32 +000093
Chris Lattnerf04da132007-10-24 17:06:59 +000094 // Top Level Driver code.
95 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000096 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +000097 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +000098 ~RewriteTest();
99
100 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000101 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000102 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 void RewriteTabs();
104 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000105 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000106 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000107 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000108 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000109 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000110 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000111 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000112 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000113 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000114 void RewriteObjcQualifiedInterfaceTypes(
115 const FunctionTypeProto *proto, FunctionDecl *FD);
116 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000117 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
118 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000121 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000122 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000123 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000124 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000125 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000126 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000127 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
128 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
129 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000130 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000131 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
132 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000133 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000134 void SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000135 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000136 void SynthCFStringFunctionDecl();
137
Chris Lattnerf04da132007-10-24 17:06:59 +0000138 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000139 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
140 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000141
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000142 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
143 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000144
Steve Naroff0416fb92007-11-11 17:19:15 +0000145 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000146 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000147 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000148 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000149 const char *ClassName,
150 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000151
152 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
153 int NumProtocols,
154 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000155 const char *ClassName,
156 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000157 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
158 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000159 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
160 ObjcIvarDecl *ivar,
161 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000162 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 };
164}
165
Chris Lattnere365c502007-11-30 22:25:36 +0000166ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
167 return new RewriteTest(Diags);
168}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000169
Chris Lattnerf04da132007-10-24 17:06:59 +0000170//===----------------------------------------------------------------------===//
171// Top Level Driver Code
172//===----------------------------------------------------------------------===//
173
Chris Lattner8a12c272007-10-11 18:38:32 +0000174void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000175 // Two cases: either the decl could be in the main file, or it could be in a
176 // #included file. If the former, rewrite it now. If the later, check to see
177 // if we rewrote the #include/#import.
178 SourceLocation Loc = D->getLocation();
179 Loc = SM->getLogicalLoc(Loc);
180
181 // If this is for a builtin, ignore it.
182 if (Loc.isInvalid()) return;
183
Steve Naroffebf2b562007-10-23 23:50:29 +0000184 // Look for built-in declarations that we need to refer during the rewrite.
185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000186 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000187 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
188 // declared in <Foundation/NSString.h>
189 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
190 ConstantStringClassReference = FVD;
191 return;
192 }
Steve Naroffbef11852007-10-26 20:53:56 +0000193 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
194 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000195 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
196 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000197 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
198 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000199 } else if (ObjcForwardProtocolDecl *FP =
200 dyn_cast<ObjcForwardProtocolDecl>(D)){
201 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000202 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000203 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000204 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
205 return HandleDeclInMainFile(D);
206
Chris Lattnerf04da132007-10-24 17:06:59 +0000207 // Otherwise, see if there is a #import in the main file that should be
208 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000209 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000210}
211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212/// HandleDeclInMainFile - This is called for each top-level decl defined in the
213/// main file of the input.
214void RewriteTest::HandleDeclInMainFile(Decl *D) {
215 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
216 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000217 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000218
219 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000220 if (Stmt *Body = MD->getBody()) {
221 //Body->dump();
222 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000223 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000224 CurMethodDecl = 0;
225 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000226 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000227 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
228 ClassImplementation.push_back(CI);
229 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
230 CategoryImplementation.push_back(CI);
231 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
232 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000233 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
234 if (VD->getInit())
235 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
236 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000237 // Nothing yet.
238}
239
240RewriteTest::~RewriteTest() {
241 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000242
243 // Rewrite tabs if we care.
244 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000245
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000246 // Rewrite Objective-c meta data*
247 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000248 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
251 // we are done.
252 if (const RewriteBuffer *RewriteBuf =
253 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000254 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000255 std::string S(RewriteBuf->begin(), RewriteBuf->end());
256 printf("%s\n", S.c_str());
257 } else {
258 printf("No changes\n");
259 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000260 // Emit metadata.
261 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000262}
263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264//===----------------------------------------------------------------------===//
265// Syntactic (non-AST) Rewriting Code
266//===----------------------------------------------------------------------===//
267
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000268void RewriteTest::RewriteInclude(SourceLocation Loc) {
269 // Rip up the #include stack to the main file.
270 SourceLocation IncLoc = Loc, NextLoc = Loc;
271 do {
272 IncLoc = Loc;
273 Loc = SM->getLogicalLoc(NextLoc);
274 NextLoc = SM->getIncludeLoc(Loc);
275 } while (!NextLoc.isInvalid());
276
277 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
278 // IncLoc indicates the header that was included if it is useful.
279 IncLoc = SM->getLogicalLoc(IncLoc);
280 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
281 Loc == LastIncLoc)
282 return;
283 LastIncLoc = Loc;
284
285 unsigned IncCol = SM->getColumnNumber(Loc);
286 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
287
288 // Replace the #import with #include.
289 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
290}
291
Chris Lattnerf04da132007-10-24 17:06:59 +0000292void RewriteTest::RewriteTabs() {
293 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
294 const char *MainBufStart = MainBuf.first;
295 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297 // Loop over the whole file, looking for tabs.
298 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
299 if (*BufPtr != '\t')
300 continue;
301
302 // Okay, we found a tab. This tab will turn into at least one character,
303 // but it depends on which 'virtual column' it is in. Compute that now.
304 unsigned VCol = 0;
305 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
306 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
307 ++VCol;
308
309 // Okay, now that we know the virtual column, we know how many spaces to
310 // insert. We assume 8-character tab-stops.
311 unsigned Spaces = 8-(VCol & 7);
312
313 // Get the location of the tab.
314 SourceLocation TabLoc =
315 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
316
317 // Rewrite the single tab character into a sequence of spaces.
318 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
319 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000320}
321
322
Chris Lattnerf04da132007-10-24 17:06:59 +0000323void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
324 int numDecls = ClassDecl->getNumForwardDecls();
325 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
326
327 // Get the start location and compute the semi location.
328 SourceLocation startLoc = ClassDecl->getLocation();
329 const char *startBuf = SM->getCharacterData(startLoc);
330 const char *semiPtr = strchr(startBuf, ';');
331
332 // Translate to typedef's that forward reference structs with the same name
333 // as the class. As a convenience, we include the original declaration
334 // as a comment.
335 std::string typedefString;
336 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000337 typedefString.append(startBuf, semiPtr-startBuf+1);
338 typedefString += "\n";
339 for (int i = 0; i < numDecls; i++) {
340 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000341 typedefString += "#ifndef _REWRITER_typedef_";
342 typedefString += ForwardDecl->getName();
343 typedefString += "\n";
344 typedefString += "#define _REWRITER_typedef_";
345 typedefString += ForwardDecl->getName();
346 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000347 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000348 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000349 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000350 }
351
352 // Replace the @class with typedefs corresponding to the classes.
353 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
354 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000355}
356
Steve Naroff71c0a952007-11-13 23:01:27 +0000357void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000358 for (int i = 0; i < nMethods; i++) {
359 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000360 SourceLocation LocStart = Method->getLocStart();
361 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000362
Steve Naroff1d098f62007-11-14 14:34:23 +0000363 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
364 Rewrite.InsertText(LocStart, "/* ", 3);
365 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
366 } else {
367 Rewrite.InsertText(LocStart, "// ", 3);
368 }
Steve Naroff423cb562007-10-30 13:30:57 +0000369 }
370}
371
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000372void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
373{
374 for (int i = 0; i < nProperties; i++) {
375 ObjcPropertyDecl *Property = Properties[i];
376 SourceLocation Loc = Property->getLocation();
377
378 Rewrite.ReplaceText(Loc, 0, "// ", 3);
379
380 // FIXME: handle properties that are declared across multiple lines.
381 }
382}
383
Steve Naroff423cb562007-10-30 13:30:57 +0000384void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
385 SourceLocation LocStart = CatDecl->getLocStart();
386
387 // FIXME: handle category headers that are declared across multiple lines.
388 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
389
Steve Naroff71c0a952007-11-13 23:01:27 +0000390 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
391 CatDecl->getInstanceMethods());
392 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
393 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000394 // Lastly, comment out the @end.
395 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
396}
397
Steve Naroff752d6ef2007-10-30 16:42:30 +0000398void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000399 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000400
Steve Naroff752d6ef2007-10-30 16:42:30 +0000401 SourceLocation LocStart = PDecl->getLocStart();
402
403 // FIXME: handle protocol headers that are declared across multiple lines.
404 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
405
Steve Naroff71c0a952007-11-13 23:01:27 +0000406 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
407 PDecl->getInstanceMethods());
408 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
409 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000410 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000411 SourceLocation LocEnd = PDecl->getAtEndLoc();
412 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000413
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000414 // Must comment out @optional/@required
415 const char *startBuf = SM->getCharacterData(LocStart);
416 const char *endBuf = SM->getCharacterData(LocEnd);
417 for (const char *p = startBuf; p < endBuf; p++) {
418 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
419 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000420 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000421 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
422 CommentedOptional.c_str(), CommentedOptional.size());
423
424 }
425 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
426 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000427 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000428 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
429 CommentedRequired.c_str(), CommentedRequired.size());
430
431 }
432 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000433}
434
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000435void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
436 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000437 if (LocStart.isInvalid())
438 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000439 // FIXME: handle forward protocol that are declared across multiple lines.
440 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
441}
442
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000443void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
444 std::string &ResultStr) {
445 ResultStr += "\nstatic ";
446 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000447 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000448
449 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000450 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000451
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000452 if (OMD->isInstance())
453 NameStr += "_I_";
454 else
455 NameStr += "_C_";
456
457 NameStr += OMD->getClassInterface()->getName();
458 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000459
460 NamedDecl *MethodContext = OMD->getMethodContext();
461 if (ObjcCategoryImplDecl *CID =
462 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000463 NameStr += CID->getName();
464 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000465 }
466 // Append selector names, replacing ':' with '_'
467 const char *selName = OMD->getSelector().getName().c_str();
468 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000469 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000470 else {
471 std::string selString = OMD->getSelector().getName();
472 int len = selString.size();
473 for (int i = 0; i < len; i++)
474 if (selString[i] == ':')
475 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000476 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000477 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000478 // Remember this name for metadata emission
479 MethodInternalNames[OMD] = NameStr;
480 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000481
482 // Rewrite arguments
483 ResultStr += "(";
484
485 // invisible arguments
486 if (OMD->isInstance()) {
487 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
488 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000489 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
490 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000491 ResultStr += selfTy.getAsString();
492 }
493 else
494 ResultStr += Context->getObjcIdType().getAsString();
495
496 ResultStr += " self, ";
497 ResultStr += Context->getObjcSelType().getAsString();
498 ResultStr += " _cmd";
499
500 // Method arguments.
501 for (int i = 0; i < OMD->getNumParams(); i++) {
502 ParmVarDecl *PDecl = OMD->getParamDecl(i);
503 ResultStr += ", ";
504 ResultStr += PDecl->getType().getAsString();
505 ResultStr += " ";
506 ResultStr += PDecl->getName();
507 }
508 ResultStr += ")";
509
510}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000511void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
512 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
513 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000514
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000515 if (IMD)
516 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
517 else
518 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000519
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000520 int numMethods = IMD ? IMD->getNumInstanceMethods()
521 : CID->getNumInstanceMethods();
522
523 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000525 ObjcMethodDecl *OMD;
526 if (IMD)
527 OMD = IMD->getInstanceMethods()[i];
528 else
529 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000530 RewriteObjcMethodDecl(OMD, ResultStr);
531 SourceLocation LocStart = OMD->getLocStart();
532 SourceLocation LocEnd = OMD->getBody()->getLocStart();
533
534 const char *startBuf = SM->getCharacterData(LocStart);
535 const char *endBuf = SM->getCharacterData(LocEnd);
536 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
537 ResultStr.c_str(), ResultStr.size());
538 }
539
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000540 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
541 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000542 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000543 ObjcMethodDecl *OMD;
544 if (IMD)
545 OMD = IMD->getClassMethods()[i];
546 else
547 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000548 RewriteObjcMethodDecl(OMD, ResultStr);
549 SourceLocation LocStart = OMD->getLocStart();
550 SourceLocation LocEnd = OMD->getBody()->getLocStart();
551
552 const char *startBuf = SM->getCharacterData(LocStart);
553 const char *endBuf = SM->getCharacterData(LocEnd);
554 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
555 ResultStr.c_str(), ResultStr.size());
556 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000557 if (IMD)
558 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
559 else
560 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000561}
562
Steve Naroffbef11852007-10-26 20:53:56 +0000563void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000564 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000565 if (!ObjcForwardDecls.count(ClassDecl)) {
566 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000567 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000568 ResultStr += ClassDecl->getName();
569 ResultStr += "\n";
570 ResultStr += "#define _REWRITER_typedef_";
571 ResultStr += ClassDecl->getName();
572 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000573 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000574 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000575 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000576
577 // Mark this typedef as having been generated.
578 ObjcForwardDecls.insert(ClassDecl);
579 }
Steve Narofff908a872007-10-30 02:23:23 +0000580 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
581
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000582 RewriteProperties(ClassDecl->getNumPropertyDecl(),
583 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000584 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
585 ClassDecl->getInstanceMethods());
586 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
587 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000588
Steve Naroff2feac5e2007-10-30 03:43:13 +0000589 // Lastly, comment out the @end.
590 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000591}
592
Steve Naroff7e3411b2007-11-15 02:58:25 +0000593Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
594 ObjcIvarDecl *D = IV->getDecl();
595 if (IV->isFreeIvar()) {
596 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
597 IV->getLocation());
598 Rewrite.ReplaceStmt(IV, Replacement);
599 delete IV;
600 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000601 } else {
602 if (CurMethodDecl) {
603 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
604 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
605 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
606 IdentifierInfo *II = intT->getDecl()->getIdentifier();
607 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
608 II, 0);
609 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
610
611 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
612 // Don't forget the parens to enforce the proper binding.
613 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
614 Rewrite.ReplaceStmt(IV->getBase(), PE);
615 delete IV->getBase();
616 return PE;
617 }
618 }
619 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000620 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000621 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000622}
623
Chris Lattnerf04da132007-10-24 17:06:59 +0000624//===----------------------------------------------------------------------===//
625// Function Body / Expression rewriting
626//===----------------------------------------------------------------------===//
627
Steve Narofff3473a72007-11-09 15:20:18 +0000628Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000629 // Otherwise, just rewrite all children.
630 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
631 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000632 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000633 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000634 if (newStmt)
635 *CI = newStmt;
636 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000637
638 // Handle specific things.
639 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
640 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000641
642 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
643 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000644
645 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
646 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000647
648 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
649 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000650
Steve Naroff934f2762007-10-24 22:48:43 +0000651 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
652 // Before we rewrite it, put the original message expression in a comment.
653 SourceLocation startLoc = MessExpr->getLocStart();
654 SourceLocation endLoc = MessExpr->getLocEnd();
655
656 const char *startBuf = SM->getCharacterData(startLoc);
657 const char *endBuf = SM->getCharacterData(endLoc);
658
659 std::string messString;
660 messString += "// ";
661 messString.append(startBuf, endBuf-startBuf+1);
662 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000663
Steve Naroff934f2762007-10-24 22:48:43 +0000664 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
665 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
666 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000667 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000668 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000669 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000670
671 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
672 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000673
674 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
675 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000676#if 0
677 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
678 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
679 // Get the new text.
680 std::ostringstream Buf;
681 Replacement->printPretty(Buf);
682 const std::string &Str = Buf.str();
683
684 printf("CAST = %s\n", &Str[0]);
685 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
686 delete S;
687 return Replacement;
688 }
689#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000690 // Return this stmt unmodified.
691 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000692}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000693
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000694Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000695 // Get the start location and compute the semi location.
696 SourceLocation startLoc = S->getLocStart();
697 const char *startBuf = SM->getCharacterData(startLoc);
698
699 assert((*startBuf == '@') && "bogus @try location");
700
701 std::string buf;
702 // declare a new scope with two variables, _stack and _rethrow.
703 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
704 buf += "int buf[18/*32-bit i386*/];\n";
705 buf += "char *pointers[4];} _stack;\n";
706 buf += "id volatile _rethrow = 0;\n";
707 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000708 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000709
710 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
711
712 startLoc = S->getTryBody()->getLocEnd();
713 startBuf = SM->getCharacterData(startLoc);
714
715 assert((*startBuf == '}') && "bogus @try block");
716
717 SourceLocation lastCurlyLoc = startLoc;
718
719 startLoc = startLoc.getFileLocWithOffset(1);
720 buf = " /* @catch begin */ else {\n";
721 buf += " id _caught = objc_exception_extract(&_stack);\n";
722 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000723 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000724 buf += " _rethrow = objc_exception_extract(&_stack);\n";
725 buf += " else { /* @catch continue */";
726
Chris Lattner28d1fe82007-11-08 04:41:51 +0000727 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000728
729 bool sawIdTypedCatch = false;
730 Stmt *lastCatchBody = 0;
731 ObjcAtCatchStmt *catchList = S->getCatchStmts();
732 while (catchList) {
733 Stmt *catchStmt = catchList->getCatchParamStmt();
734
735 if (catchList == S->getCatchStmts())
736 buf = "if ("; // we are generating code for the first catch clause
737 else
738 buf = "else if (";
739 startLoc = catchList->getLocStart();
740 startBuf = SM->getCharacterData(startLoc);
741
742 assert((*startBuf == '@') && "bogus @catch location");
743
744 const char *lParenLoc = strchr(startBuf, '(');
745
746 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
747 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
748 if (t == Context->getObjcIdType()) {
749 buf += "1) { ";
750 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
751 buf.c_str(), buf.size());
752 sawIdTypedCatch = true;
753 } else if (const PointerType *pType = t->getAsPointerType()) {
754 ObjcInterfaceType *cls; // Should be a pointer to a class.
755
756 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
757 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000758 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000759 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000760 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000761 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
762 buf.c_str(), buf.size());
763 }
764 }
765 // Now rewrite the body...
766 lastCatchBody = catchList->getCatchBody();
767 SourceLocation rParenLoc = catchList->getRParenLoc();
768 SourceLocation bodyLoc = lastCatchBody->getLocStart();
769 const char *bodyBuf = SM->getCharacterData(bodyLoc);
770 const char *rParenBuf = SM->getCharacterData(rParenLoc);
771 assert((*rParenBuf == ')') && "bogus @catch paren location");
772 assert((*bodyBuf == '{') && "bogus @catch body location");
773
774 buf = " = _caught;";
775 // Here we replace ") {" with "= _caught;" (which initializes and
776 // declares the @catch parameter).
777 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
778 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000779 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000780 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000781 }
Steve Naroff75730982007-11-07 04:08:17 +0000782 catchList = catchList->getNextCatchStmt();
783 }
784 // Complete the catch list...
785 if (lastCatchBody) {
786 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
787 const char *bodyBuf = SM->getCharacterData(bodyLoc);
788 assert((*bodyBuf == '}') && "bogus @catch body location");
789 bodyLoc = bodyLoc.getFileLocWithOffset(1);
790 buf = " } } /* @catch end */\n";
791
Chris Lattner28d1fe82007-11-08 04:41:51 +0000792 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000793
794 // Set lastCurlyLoc
795 lastCurlyLoc = lastCatchBody->getLocEnd();
796 }
797 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
798 startLoc = finalStmt->getLocStart();
799 startBuf = SM->getCharacterData(startLoc);
800 assert((*startBuf == '@') && "bogus @finally start");
801
802 buf = "/* @finally */";
803 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
804
805 Stmt *body = finalStmt->getFinallyBody();
806 SourceLocation startLoc = body->getLocStart();
807 SourceLocation endLoc = body->getLocEnd();
808 const char *startBuf = SM->getCharacterData(startLoc);
809 const char *endBuf = SM->getCharacterData(endLoc);
810 assert((*startBuf == '{') && "bogus @finally body location");
811 assert((*endBuf == '}') && "bogus @finally body location");
812
813 startLoc = startLoc.getFileLocWithOffset(1);
814 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000815 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000816 endLoc = endLoc.getFileLocWithOffset(-1);
817 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000818 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000819
820 // Set lastCurlyLoc
821 lastCurlyLoc = body->getLocEnd();
822 }
823 // Now emit the final closing curly brace...
824 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
825 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000826 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000827 return 0;
828}
829
830Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
831 return 0;
832}
833
834Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
835 return 0;
836}
837
Steve Naroff2bd03922007-11-07 15:32:26 +0000838// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
839// the throw expression is typically a message expression that's already
840// been rewritten! (which implies the SourceLocation's are invalid).
841Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
842 // Get the start location and compute the semi location.
843 SourceLocation startLoc = S->getLocStart();
844 const char *startBuf = SM->getCharacterData(startLoc);
845
846 assert((*startBuf == '@') && "bogus @throw location");
847
848 std::string buf;
849 /* void objc_exception_throw(id) __attribute__((noreturn)); */
850 buf = "objc_exception_throw(";
851 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
852 const char *semiBuf = strchr(startBuf, ';');
853 assert((*semiBuf == ';') && "@throw: can't find ';'");
854 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
855 buf = ");";
856 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
857 return 0;
858}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000859
Chris Lattnere64b7772007-10-24 16:57:36 +0000860Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000861 // Create a new string expression.
862 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000863 std::string StrEncoding;
864 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
865 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
866 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000867 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000868 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
869 // replacement failed.
870 return Exp;
871 }
872
Chris Lattner07506182007-11-30 22:53:43 +0000873 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000874 delete Exp;
875 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000876}
877
Steve Naroffb42f8412007-11-05 14:50:49 +0000878Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
879 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
880 // Create a call to sel_registerName("selName").
881 llvm::SmallVector<Expr*, 8> SelExprs;
882 QualType argType = Context->getPointerType(Context->CharTy);
883 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
884 Exp->getSelector().getName().size(),
885 false, argType, SourceLocation(),
886 SourceLocation()));
887 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
888 &SelExprs[0], SelExprs.size());
889 Rewrite.ReplaceStmt(Exp, SelExp);
890 delete Exp;
891 return SelExp;
892}
893
Steve Naroff934f2762007-10-24 22:48:43 +0000894CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
895 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000896 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000897 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000898
899 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000900 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000901
902 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000903 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000904 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
905
906 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000907
Steve Naroff934f2762007-10-24 22:48:43 +0000908 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
909}
910
Steve Naroffd5255f52007-11-01 13:24:47 +0000911static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
912 const char *&startRef, const char *&endRef) {
913 while (startBuf < endBuf) {
914 if (*startBuf == '<')
915 startRef = startBuf; // mark the start.
916 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000917 if (startRef && *startRef == '<') {
918 endRef = startBuf; // mark the end.
919 return true;
920 }
921 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000922 }
923 startBuf++;
924 }
925 return false;
926}
927
928bool RewriteTest::needToScanForQualifiers(QualType T) {
929 // FIXME: we don't currently represent "id <Protocol>" in the type system.
930 if (T == Context->getObjcIdType())
931 return true;
932
933 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000934 Type *pointeeType = pType->getPointeeType().getTypePtr();
935 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
936 return true; // we have "Class <Protocol> *".
937 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000938 return false;
939}
940
941void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
942 const FunctionTypeProto *proto, FunctionDecl *FD) {
943
944 if (needToScanForQualifiers(proto->getResultType())) {
945 // Since types are unique, we need to scan the buffer.
946 SourceLocation Loc = FD->getLocation();
947
948 const char *endBuf = SM->getCharacterData(Loc);
949 const char *startBuf = endBuf;
950 while (*startBuf != ';')
951 startBuf--; // scan backward (from the decl location) for return type.
952 const char *startRef = 0, *endRef = 0;
953 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
954 // Get the locations of the startRef, endRef.
955 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
956 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
957 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000958 Rewrite.InsertText(LessLoc, "/*", 2);
959 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000960 }
961 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000962 // Now check arguments.
963 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
964 if (needToScanForQualifiers(proto->getArgType(i))) {
965 // Since types are unique, we need to scan the buffer.
966 SourceLocation Loc = FD->getLocation();
967
968 const char *startBuf = SM->getCharacterData(Loc);
969 const char *endBuf = startBuf;
970 while (*endBuf != ';')
971 endBuf++; // scan forward (from the decl location) for argument types.
972 const char *startRef = 0, *endRef = 0;
973 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
974 // Get the locations of the startRef, endRef.
975 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
976 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
977 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000978 Rewrite.InsertText(LessLoc, "/*", 2);
979 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000980 }
981 }
982 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000983}
984
Steve Naroff09b266e2007-10-30 23:14:51 +0000985void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
986 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000987 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000988 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000989 return;
990 }
991 // Check for ObjC 'id' and class types that have been adorned with protocol
992 // information (id<p>, C<p>*). The protocol references need to be rewritten!
993 const FunctionType *funcType = FD->getType()->getAsFunctionType();
994 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000995 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
996 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000997}
998
999// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1000void RewriteTest::SynthMsgSendFunctionDecl() {
1001 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1002 llvm::SmallVector<QualType, 16> ArgTys;
1003 QualType argT = Context->getObjcIdType();
1004 assert(!argT.isNull() && "Can't find 'id' type");
1005 ArgTys.push_back(argT);
1006 argT = Context->getObjcSelType();
1007 assert(!argT.isNull() && "Can't find 'SEL' type");
1008 ArgTys.push_back(argT);
1009 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1010 &ArgTys[0], ArgTys.size(),
1011 true /*isVariadic*/);
1012 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1013 msgSendIdent, msgSendType,
1014 FunctionDecl::Extern, false, 0);
1015}
1016
Steve Naroff874e2322007-11-15 10:28:18 +00001017// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1018void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1019 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1020 llvm::SmallVector<QualType, 16> ArgTys;
1021 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1022 &Context->Idents.get("objc_super"), 0);
1023 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1024 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1025 ArgTys.push_back(argT);
1026 argT = Context->getObjcSelType();
1027 assert(!argT.isNull() && "Can't find 'SEL' type");
1028 ArgTys.push_back(argT);
1029 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1030 &ArgTys[0], ArgTys.size(),
1031 true /*isVariadic*/);
1032 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1033 msgSendIdent, msgSendType,
1034 FunctionDecl::Extern, false, 0);
1035}
1036
Steve Naroff09b266e2007-10-30 23:14:51 +00001037// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1038void RewriteTest::SynthGetClassFunctionDecl() {
1039 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1040 llvm::SmallVector<QualType, 16> ArgTys;
1041 ArgTys.push_back(Context->getPointerType(
1042 Context->CharTy.getQualifiedType(QualType::Const)));
1043 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1044 &ArgTys[0], ArgTys.size(),
1045 false /*isVariadic*/);
1046 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1047 getClassIdent, getClassType,
1048 FunctionDecl::Extern, false, 0);
1049}
1050
Steve Naroff96984642007-11-08 14:30:50 +00001051// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1052void RewriteTest::SynthCFStringFunctionDecl() {
1053 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1054 llvm::SmallVector<QualType, 16> ArgTys;
1055 ArgTys.push_back(Context->getPointerType(
1056 Context->CharTy.getQualifiedType(QualType::Const)));
1057 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1058 &ArgTys[0], ArgTys.size(),
1059 false /*isVariadic*/);
1060 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1061 getClassIdent, getClassType,
1062 FunctionDecl::Extern, false, 0);
1063}
1064
Steve Naroffbeaf2992007-11-03 11:27:19 +00001065Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001066#if 1
1067 // This rewrite is specific to GCC, which has builtin support for CFString.
1068 if (!CFStringFunctionDecl)
1069 SynthCFStringFunctionDecl();
1070 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1071 llvm::SmallVector<Expr*, 8> StrExpr;
1072 StrExpr.push_back(Exp->getString());
1073 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1074 &StrExpr[0], StrExpr.size());
1075 // cast to NSConstantString *
1076 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1077 Rewrite.ReplaceStmt(Exp, cast);
1078 delete Exp;
1079 return cast;
1080#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001081 assert(ConstantStringClassReference && "Can't find constant string reference");
1082 llvm::SmallVector<Expr*, 4> InitExprs;
1083
1084 // Synthesize "(Class)&_NSConstantStringClassReference"
1085 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1086 ConstantStringClassReference->getType(),
1087 SourceLocation());
1088 QualType expType = Context->getPointerType(ClsRef->getType());
1089 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1090 expType, SourceLocation());
1091 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1092 SourceLocation());
1093 InitExprs.push_back(cast); // set the 'isa'.
1094 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1095 unsigned IntSize = static_cast<unsigned>(
1096 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1097 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1098 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1099 Exp->getLocStart());
1100 InitExprs.push_back(len); // set "int numBytes".
1101
1102 // struct NSConstantString
1103 QualType CFConstantStrType = Context->getCFConstantStringType();
1104 // (struct NSConstantString) { <exprs from above> }
1105 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1106 &InitExprs[0], InitExprs.size(),
1107 SourceLocation());
1108 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1109 // struct NSConstantString *
1110 expType = Context->getPointerType(StrRep->getType());
1111 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1112 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001113 // cast to NSConstantString *
1114 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001115 Rewrite.ReplaceStmt(Exp, cast);
1116 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001117 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001118#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001119}
1120
Steve Naroff874e2322007-11-15 10:28:18 +00001121ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1122 if (CurMethodDecl) { // check if we are sending a message to 'super'
1123 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1124 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1125 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1126 if (!strcmp(PVD->getName(), "self")) {
1127 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1128 if (ObjcInterfaceType *IT =
1129 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1130 if (IT->getDecl() ==
1131 CurMethodDecl->getClassInterface()->getSuperClass())
1132 return IT->getDecl();
1133 }
1134 }
1135 }
1136 }
1137 }
1138 }
1139 }
1140 return 0;
1141}
1142
1143// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1144QualType RewriteTest::getSuperStructType() {
1145 if (!SuperStructDecl) {
1146 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1147 &Context->Idents.get("objc_super"), 0);
1148 QualType FieldTypes[2];
1149
1150 // struct objc_object *receiver;
1151 FieldTypes[0] = Context->getObjcIdType();
1152 // struct objc_class *super;
1153 FieldTypes[1] = Context->getObjcClassType();
1154 // Create fields
1155 FieldDecl *FieldDecls[2];
1156
1157 for (unsigned i = 0; i < 2; ++i)
1158 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1159
1160 SuperStructDecl->defineBody(FieldDecls, 4);
1161 }
1162 return Context->getTagDeclType(SuperStructDecl);
1163}
1164
Steve Naroff934f2762007-10-24 22:48:43 +00001165Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001166 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001167 if (!MsgSendFunctionDecl)
1168 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001169 if (!MsgSendSuperFunctionDecl)
1170 SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001171 if (!GetClassFunctionDecl)
1172 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001173
Steve Naroff874e2322007-11-15 10:28:18 +00001174 // default to objc_msgSend().
1175 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1176
Steve Naroff934f2762007-10-24 22:48:43 +00001177 // Synthesize a call to objc_msgSend().
1178 llvm::SmallVector<Expr*, 8> MsgExprs;
1179 IdentifierInfo *clsName = Exp->getClassName();
1180
1181 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1182 if (clsName) { // class message.
1183 llvm::SmallVector<Expr*, 8> ClsExprs;
1184 QualType argType = Context->getPointerType(Context->CharTy);
1185 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1186 clsName->getLength(),
1187 false, argType, SourceLocation(),
1188 SourceLocation()));
1189 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1190 &ClsExprs[0], ClsExprs.size());
1191 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001192 } else { // instance message.
1193 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001194
1195 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1196 MsgSendFlavor = MsgSendSuperFunctionDecl;
1197 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1198
1199 llvm::SmallVector<Expr*, 4> InitExprs;
1200
1201 InitExprs.push_back(recExpr); // set the 'receiver'.
1202
1203 llvm::SmallVector<Expr*, 8> ClsExprs;
1204 QualType argType = Context->getPointerType(Context->CharTy);
1205 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1206 ID->getIdentifier()->getLength(),
1207 false, argType, SourceLocation(),
1208 SourceLocation()));
1209 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1210 &ClsExprs[0], ClsExprs.size());
1211 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1212 // struct objc_super
1213 QualType superType = getSuperStructType();
1214 // (struct objc_super) { <exprs from above> }
1215 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1216 &InitExprs[0], InitExprs.size(),
1217 SourceLocation());
1218 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1219 // struct objc_super *
1220 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1221 Context->getPointerType(SuperRep->getType()),
1222 SourceLocation());
1223 MsgExprs.push_back(Unop);
1224 } else {
1225 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1226 MsgExprs.push_back(recExpr);
1227 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001228 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001229 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001230 llvm::SmallVector<Expr*, 8> SelExprs;
1231 QualType argType = Context->getPointerType(Context->CharTy);
1232 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1233 Exp->getSelector().getName().size(),
1234 false, argType, SourceLocation(),
1235 SourceLocation()));
1236 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1237 &SelExprs[0], SelExprs.size());
1238 MsgExprs.push_back(SelExp);
1239
1240 // Now push any user supplied arguments.
1241 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001242 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001243 // Make all implicit casts explicit...ICE comes in handy:-)
1244 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1245 // Reuse the ICE type, it is exactly what the doctor ordered.
1246 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1247 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001248 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001249 // We've transferred the ownership to MsgExprs. Null out the argument in
1250 // the original expression, since we will delete it below.
1251 Exp->setArg(i, 0);
1252 }
Steve Naroffab972d32007-11-04 22:37:50 +00001253 // Generate the funky cast.
1254 CastExpr *cast;
1255 llvm::SmallVector<QualType, 8> ArgTypes;
1256 QualType returnType;
1257
1258 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001259 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1260 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1261 else
1262 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001263 ArgTypes.push_back(Context->getObjcSelType());
1264 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1265 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001266 for (int i = 0; i < mDecl->getNumParams(); i++) {
1267 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001268 ArgTypes.push_back(t);
1269 }
Steve Naroffab972d32007-11-04 22:37:50 +00001270 returnType = mDecl->getResultType();
1271 } else {
1272 returnType = Context->getObjcIdType();
1273 }
1274 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001275 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001276
1277 // Create a reference to the objc_msgSend() declaration.
Steve Naroff874e2322007-11-15 10:28:18 +00001278 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001279
1280 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1281 // If we don't do this cast, we get the following bizarre warning/note:
1282 // xx.m:13: warning: function called through a non-compatible type
1283 // xx.m:13: note: if this code is reached, the program will abort
1284 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1285 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001286
Steve Naroffab972d32007-11-04 22:37:50 +00001287 // Now do the "normal" pointer to function cast.
1288 QualType castType = Context->getFunctionType(returnType,
1289 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001290 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001291 castType = Context->getPointerType(castType);
1292 cast = new CastExpr(castType, cast, SourceLocation());
1293
1294 // Don't forget the parens to enforce the proper binding.
1295 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1296
1297 const FunctionType *FT = msgSendType->getAsFunctionType();
1298 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1299 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001300 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001301 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001302
Chris Lattnere64b7772007-10-24 16:57:36 +00001303 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001304 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001305}
1306
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001307/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1308/// an objective-c class with ivars.
1309void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1310 std::string &Result) {
1311 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1312 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001313 // Do not synthesize more than once.
1314 if (ObjcSynthesizedStructs.count(CDecl))
1315 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001316 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1317 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1318 // Do it for the root
1319 SynthesizeObjcInternalStruct(RCDecl, Result);
1320 }
1321
Steve Naroff03300712007-11-12 13:56:41 +00001322 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001323 SourceLocation LocStart = CDecl->getLocStart();
1324 SourceLocation LocEnd = CDecl->getLocEnd();
1325
1326 const char *startBuf = SM->getCharacterData(LocStart);
1327 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001328 // If no ivars and no root or if its root, directly or indirectly,
1329 // have no ivars (thus not synthesized) then no need to synthesize this class.
1330 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001331 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1332 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1333 Result.c_str(), Result.size());
1334 return;
1335 }
1336
1337 // FIXME: This has potential of causing problem. If
1338 // SynthesizeObjcInternalStruct is ever called recursively.
1339 Result += "\nstruct ";
1340 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001341
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001342 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001343 const char *cursor = strchr(startBuf, '{');
1344 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001345 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001346
1347 // rewrite the original header *without* disturbing the '{'
1348 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1349 Result.c_str(), Result.size());
1350 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1351 Result = "\n struct ";
1352 Result += RCDecl->getName();
1353 Result += " _";
1354 Result += RCDecl->getName();
1355 Result += ";\n";
1356
1357 // insert the super class structure definition.
1358 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1359 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1360 }
1361 cursor++; // past '{'
1362
1363 // Now comment out any visibility specifiers.
1364 while (cursor < endBuf) {
1365 if (*cursor == '@') {
1366 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001367 // Skip whitespace.
1368 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1369 /*scan*/;
1370
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001371 // FIXME: presence of @public, etc. inside comment results in
1372 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001373 if (!strncmp(cursor, "public", strlen("public")) ||
1374 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001375 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001376 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001377 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001378 // FIXME: If there are cases where '<' is used in ivar declaration part
1379 // of user code, then scan the ivar list and use needToScanForQualifiers
1380 // for type checking.
1381 else if (*cursor == '<') {
1382 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1383 Rewrite.InsertText(atLoc, "/* ", 3);
1384 cursor = strchr(cursor, '>');
1385 cursor++;
1386 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1387 Rewrite.InsertText(atLoc, " */", 3);
1388 }
Steve Narofffea763e82007-11-14 19:25:57 +00001389 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001390 }
Steve Narofffea763e82007-11-14 19:25:57 +00001391 // Don't forget to add a ';'!!
1392 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1393 } else { // we don't have any instance variables - insert super struct.
1394 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1395 Result += " {\n struct ";
1396 Result += RCDecl->getName();
1397 Result += " _";
1398 Result += RCDecl->getName();
1399 Result += ";\n};\n";
1400 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1401 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001402 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001403 // Mark this struct as having been generated.
1404 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001405 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001406}
1407
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001408// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1409/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001410void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001411 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001412 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001413 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001414 const char *ClassName,
1415 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001416 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001417 if (NumMethods > 0 && !objc_impl_method) {
1418 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001419 SEL _cmd;
1420 char *method_types;
1421 void *_imp;
1422 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001423 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001424 Result += "\nstruct _objc_method {\n";
1425 Result += "\tSEL _cmd;\n";
1426 Result += "\tchar *method_types;\n";
1427 Result += "\tvoid *_imp;\n";
1428 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001429
1430 /* struct _objc_method_list {
1431 struct _objc_method_list *next_method;
1432 int method_count;
1433 struct _objc_method method_list[];
1434 }
1435 */
1436 Result += "\nstruct _objc_method_list {\n";
1437 Result += "\tstruct _objc_method_list *next_method;\n";
1438 Result += "\tint method_count;\n";
1439 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001440 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001441 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001442 // Build _objc_method_list for class's methods if needed
1443 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001444 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001445 Result += prefix;
1446 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1447 Result += "_METHODS_";
1448 Result += ClassName;
1449 Result += " __attribute__ ((section (\"__OBJC, __";
1450 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001451 Result += "_meth\")))= ";
1452 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1453
1454 Result += "\t,{{(SEL)\"";
1455 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001456 std::string MethodTypeString;
1457 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1458 Result += "\", \"";
1459 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001460 Result += "\", ";
1461 Result += MethodInternalNames[Methods[0]];
1462 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001463 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001464 Result += "\t ,{(SEL)\"";
1465 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001466 std::string MethodTypeString;
1467 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1468 Result += "\", \"";
1469 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001470 Result += "\", ";
1471 Result += MethodInternalNames[Methods[i]];
1472 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001473 }
1474 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001475 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001476}
1477
1478/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1479void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1480 int NumProtocols,
1481 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001482 const char *ClassName,
1483 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001484 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001485 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001486 for (int i = 0; i < NumProtocols; i++) {
1487 ObjcProtocolDecl *PDecl = Protocols[i];
1488 // Output struct protocol_methods holder of method selector and type.
1489 if (!objc_protocol_methods &&
1490 (PDecl->getNumInstanceMethods() > 0
1491 || PDecl->getNumClassMethods() > 0)) {
1492 /* struct protocol_methods {
1493 SEL _cmd;
1494 char *method_types;
1495 }
1496 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001497 Result += "\nstruct protocol_methods {\n";
1498 Result += "\tSEL _cmd;\n";
1499 Result += "\tchar *method_types;\n";
1500 Result += "};\n";
1501
1502 /* struct _objc_protocol_method_list {
1503 int protocol_method_count;
1504 struct protocol_methods protocols[];
1505 }
1506 */
1507 Result += "\nstruct _objc_protocol_method_list {\n";
1508 Result += "\tint protocol_method_count;\n";
1509 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001510 objc_protocol_methods = true;
1511 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001512
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001513 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001514 int NumMethods = PDecl->getNumInstanceMethods();
1515 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001516 Result += "\nstatic struct _objc_protocol_method_list "
1517 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1518 Result += PDecl->getName();
1519 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1520 "{\n\t" + utostr(NumMethods) + "\n";
1521
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001522 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001523 Result += "\t,{{(SEL)\"";
1524 Result += Methods[0]->getSelector().getName().c_str();
1525 Result += "\", \"\"}\n";
1526
1527 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001528 Result += "\t ,{(SEL)\"";
1529 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001530 std::string MethodTypeString;
1531 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1532 Result += "\", \"";
1533 Result += MethodTypeString;
1534 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001535 }
1536 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001537 }
1538
1539 // Output class methods declared in this protocol.
1540 NumMethods = PDecl->getNumClassMethods();
1541 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001542 Result += "\nstatic struct _objc_protocol_method_list "
1543 "_OBJC_PROTOCOL_CLASS_METHODS_";
1544 Result += PDecl->getName();
1545 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1546 "{\n\t";
1547 Result += utostr(NumMethods);
1548 Result += "\n";
1549
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001550 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001551 Result += "\t,{{(SEL)\"";
1552 Result += Methods[0]->getSelector().getName().c_str();
1553 Result += "\", \"\"}\n";
1554
1555 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001556 Result += "\t ,{(SEL)\"";
1557 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001558 std::string MethodTypeString;
1559 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1560 Result += "\", \"";
1561 Result += MethodTypeString;
1562 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001563 }
1564 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001565 }
1566 // Output:
1567 /* struct _objc_protocol {
1568 // Objective-C 1.0 extensions
1569 struct _objc_protocol_extension *isa;
1570 char *protocol_name;
1571 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001572 struct _objc_protocol_method_list *instance_methods;
1573 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001574 };
1575 */
1576 static bool objc_protocol = false;
1577 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001578 Result += "\nstruct _objc_protocol {\n";
1579 Result += "\tstruct _objc_protocol_extension *isa;\n";
1580 Result += "\tchar *protocol_name;\n";
1581 Result += "\tstruct _objc_protocol **protocol_list;\n";
1582 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1583 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1584 Result += "};\n";
1585
1586 /* struct _objc_protocol_list {
1587 struct _objc_protocol_list *next;
1588 int protocol_count;
1589 struct _objc_protocol *class_protocols[];
1590 }
1591 */
1592 Result += "\nstruct _objc_protocol_list {\n";
1593 Result += "\tstruct _objc_protocol_list *next;\n";
1594 Result += "\tint protocol_count;\n";
1595 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1596 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001597 objc_protocol = true;
1598 }
1599
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001600 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1601 Result += PDecl->getName();
1602 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1603 "{\n\t0, \"";
1604 Result += PDecl->getName();
1605 Result += "\", 0, ";
1606 if (PDecl->getInstanceMethods() > 0) {
1607 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1608 Result += PDecl->getName();
1609 Result += ", ";
1610 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001611 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001612 Result += "0, ";
1613 if (PDecl->getClassMethods() > 0) {
1614 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1615 Result += PDecl->getName();
1616 Result += "\n";
1617 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001618 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001619 Result += "0\n";
1620 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001621 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001622 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001623 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1624 Result += prefix;
1625 Result += "_PROTOCOLS_";
1626 Result += ClassName;
1627 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1628 "{\n\t0, ";
1629 Result += utostr(NumProtocols);
1630 Result += "\n";
1631
1632 Result += "\t,{&_OBJC_PROTOCOL_";
1633 Result += Protocols[0]->getName();
1634 Result += " \n";
1635
1636 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001637 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001638 Result += "\t ,&_OBJC_PROTOCOL_";
1639 Result += PDecl->getName();
1640 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001641 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001642 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001643 }
1644}
1645
1646/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1647/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001648void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1649 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001650 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1651 // Find category declaration for this implementation.
1652 ObjcCategoryDecl *CDecl;
1653 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1654 CDecl = CDecl->getNextClassCategory())
1655 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1656 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001657
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001658 char *FullCategoryName = (char*)alloca(
1659 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1660 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1661
1662 // Build _objc_method_list for class's instance methods if needed
1663 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1664 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001665 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001666 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001667
1668 // Build _objc_method_list for class's class methods if needed
1669 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1670 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001671 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001672 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001673
1674 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001675 // Null CDecl is case of a category implementation with no category interface
1676 if (CDecl)
1677 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1678 CDecl->getNumReferencedProtocols(),
1679 "CATEGORY",
1680 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001681
1682 /* struct _objc_category {
1683 char *category_name;
1684 char *class_name;
1685 struct _objc_method_list *instance_methods;
1686 struct _objc_method_list *class_methods;
1687 struct _objc_protocol_list *protocols;
1688 // Objective-C 1.0 extensions
1689 uint32_t size; // sizeof (struct _objc_category)
1690 struct _objc_property_list *instance_properties; // category's own
1691 // @property decl.
1692 };
1693 */
1694
1695 static bool objc_category = false;
1696 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001697 Result += "\nstruct _objc_category {\n";
1698 Result += "\tchar *category_name;\n";
1699 Result += "\tchar *class_name;\n";
1700 Result += "\tstruct _objc_method_list *instance_methods;\n";
1701 Result += "\tstruct _objc_method_list *class_methods;\n";
1702 Result += "\tstruct _objc_protocol_list *protocols;\n";
1703 Result += "\tunsigned int size;\n";
1704 Result += "\tstruct _objc_property_list *instance_properties;\n";
1705 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001706 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001707 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001708 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1709 Result += FullCategoryName;
1710 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1711 Result += IDecl->getName();
1712 Result += "\"\n\t, \"";
1713 Result += ClassDecl->getName();
1714 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001715
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001716 if (IDecl->getNumInstanceMethods() > 0) {
1717 Result += "\t, (struct _objc_method_list *)"
1718 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1719 Result += FullCategoryName;
1720 Result += "\n";
1721 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001722 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001723 Result += "\t, 0\n";
1724 if (IDecl->getNumClassMethods() > 0) {
1725 Result += "\t, (struct _objc_method_list *)"
1726 "&_OBJC_CATEGORY_CLASS_METHODS_";
1727 Result += FullCategoryName;
1728 Result += "\n";
1729 }
1730 else
1731 Result += "\t, 0\n";
1732
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001733 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001734 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1735 Result += FullCategoryName;
1736 Result += "\n";
1737 }
1738 else
1739 Result += "\t, 0\n";
1740 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001741}
1742
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001743/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1744/// ivar offset.
1745void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1746 ObjcIvarDecl *ivar,
1747 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001748 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001749 Result += IDecl->getName();
1750 Result += ", ";
1751 Result += ivar->getName();
1752 Result += ")";
1753}
1754
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001755//===----------------------------------------------------------------------===//
1756// Meta Data Emission
1757//===----------------------------------------------------------------------===//
1758
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001759void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1760 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001761 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1762
1763 // Build _objc_ivar_list metadata for classes ivars if needed
1764 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1765 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001766 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00001767 // Explictly declared @interface's are already synthesized.
1768 if (CDecl->ImplicitInterfaceDecl()) {
1769 // FIXME: Implementation of a class with no @interface (legacy) doese not
1770 // produce correct synthesis as yet.
1771 SynthesizeObjcInternalStruct(CDecl, Result);
1772 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001773
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001774 if (NumIvars > 0) {
1775 static bool objc_ivar = false;
1776 if (!objc_ivar) {
1777 /* struct _objc_ivar {
1778 char *ivar_name;
1779 char *ivar_type;
1780 int ivar_offset;
1781 };
1782 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001783 Result += "\nstruct _objc_ivar {\n";
1784 Result += "\tchar *ivar_name;\n";
1785 Result += "\tchar *ivar_type;\n";
1786 Result += "\tint ivar_offset;\n";
1787 Result += "};\n";
1788
1789 /* struct _objc_ivar_list {
1790 int ivar_count;
1791 struct _objc_ivar ivar_list[];
1792 };
1793 */
1794 Result += "\nstruct _objc_ivar_list {\n";
1795 Result += "\tint ivar_count;\n";
1796 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001797 objc_ivar = true;
1798 }
1799
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001800 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1801 Result += IDecl->getName();
1802 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1803 "{\n\t";
1804 Result += utostr(NumIvars);
1805 Result += "\n";
1806
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001807 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1808 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001809 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001810 Result += "\t,{{\"";
1811 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001812 Result += "\", \"";
1813 std::string StrEncoding;
1814 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1815 Result += StrEncoding;
1816 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001817 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1818 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001820 Result += "\t ,{\"";
1821 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001822 Result += "\", \"";
1823 std::string StrEncoding;
1824 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1825 Result += StrEncoding;
1826 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001827 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1828 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001829 }
1830
1831 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001832 }
1833
1834 // Build _objc_method_list for class's instance methods if needed
1835 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1836 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001837 true,
1838 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001839
1840 // Build _objc_method_list for class's class methods if needed
1841 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001842 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001843 false,
1844 "", IDecl->getName(), Result);
1845
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001846 // Protocols referenced in class declaration?
1847 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1848 CDecl->getNumIntfRefProtocols(),
1849 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001850 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001851
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001852
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001853 // Declaration of class/meta-class metadata
1854 /* struct _objc_class {
1855 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001856 const char *super_class_name;
1857 char *name;
1858 long version;
1859 long info;
1860 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001861 struct _objc_ivar_list *ivars;
1862 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001863 struct objc_cache *cache;
1864 struct objc_protocol_list *protocols;
1865 const char *ivar_layout;
1866 struct _objc_class_ext *ext;
1867 };
1868 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001869 static bool objc_class = false;
1870 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001871 Result += "\nstruct _objc_class {\n";
1872 Result += "\tstruct _objc_class *isa;\n";
1873 Result += "\tconst char *super_class_name;\n";
1874 Result += "\tchar *name;\n";
1875 Result += "\tlong version;\n";
1876 Result += "\tlong info;\n";
1877 Result += "\tlong instance_size;\n";
1878 Result += "\tstruct _objc_ivar_list *ivars;\n";
1879 Result += "\tstruct _objc_method_list *methods;\n";
1880 Result += "\tstruct objc_cache *cache;\n";
1881 Result += "\tstruct _objc_protocol_list *protocols;\n";
1882 Result += "\tconst char *ivar_layout;\n";
1883 Result += "\tstruct _objc_class_ext *ext;\n";
1884 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001885 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001886 }
1887
1888 // Meta-class metadata generation.
1889 ObjcInterfaceDecl *RootClass = 0;
1890 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1891 while (SuperClass) {
1892 RootClass = SuperClass;
1893 SuperClass = SuperClass->getSuperClass();
1894 }
1895 SuperClass = CDecl->getSuperClass();
1896
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001897 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1898 Result += CDecl->getName();
1899 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1900 "{\n\t(struct _objc_class *)\"";
1901 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1902 Result += "\"";
1903
1904 if (SuperClass) {
1905 Result += ", \"";
1906 Result += SuperClass->getName();
1907 Result += "\", \"";
1908 Result += CDecl->getName();
1909 Result += "\"";
1910 }
1911 else {
1912 Result += ", 0, \"";
1913 Result += CDecl->getName();
1914 Result += "\"";
1915 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001916 // TODO: 'ivars' field for root class is currently set to 0.
1917 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001918 Result += ", 0,2, sizeof(struct _objc_class), 0";
1919 if (CDecl->getNumClassMethods() > 0) {
1920 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1921 Result += CDecl->getName();
1922 Result += "\n";
1923 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001924 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001925 Result += ", 0\n";
1926 if (CDecl->getNumIntfRefProtocols() > 0) {
1927 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1928 Result += CDecl->getName();
1929 Result += ",0,0\n";
1930 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001931 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001932 Result += "\t,0,0,0,0\n";
1933 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001934
1935 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001936 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1937 Result += CDecl->getName();
1938 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1939 "{\n\t&_OBJC_METACLASS_";
1940 Result += CDecl->getName();
1941 if (SuperClass) {
1942 Result += ", \"";
1943 Result += SuperClass->getName();
1944 Result += "\", \"";
1945 Result += CDecl->getName();
1946 Result += "\"";
1947 }
1948 else {
1949 Result += ", 0, \"";
1950 Result += CDecl->getName();
1951 Result += "\"";
1952 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001953 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001954 Result += ", 0,1";
1955 if (!ObjcSynthesizedStructs.count(CDecl))
1956 Result += ",0";
1957 else {
1958 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001959 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001960 Result += CDecl->getName();
1961 Result += ")";
1962 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001963 if (NumIvars > 0) {
1964 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1965 Result += CDecl->getName();
1966 Result += "\n\t";
1967 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001968 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001969 Result += ",0";
1970 if (IDecl->getNumInstanceMethods() > 0) {
1971 Result += ", &_OBJC_INSTANCE_METHODS_";
1972 Result += CDecl->getName();
1973 Result += ", 0\n\t";
1974 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001975 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001976 Result += ",0,0";
1977 if (CDecl->getNumIntfRefProtocols() > 0) {
1978 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1979 Result += CDecl->getName();
1980 Result += ", 0,0\n";
1981 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001982 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001983 Result += ",0,0,0\n";
1984 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001985}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001986
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001987/// RewriteImplementations - This routine rewrites all method implementations
1988/// and emits meta-data.
1989
1990void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001991 int ClsDefCount = ClassImplementation.size();
1992 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001993
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001994 if (ClsDefCount == 0 && CatDefCount == 0)
1995 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001996 // Rewrite implemented methods
1997 for (int i = 0; i < ClsDefCount; i++)
1998 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001999
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002000 for (int i = 0; i < CatDefCount; i++)
2001 RewriteImplementationDecl(CategoryImplementation[i]);
2002
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002003 // This is needed for use of offsetof
2004 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002005
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002006 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002007 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002008 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002009
2010 // For each implemented category, write out all its meta data.
2011 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002012 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002013
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002014 // Write objc_symtab metadata
2015 /*
2016 struct _objc_symtab
2017 {
2018 long sel_ref_cnt;
2019 SEL *refs;
2020 short cls_def_cnt;
2021 short cat_def_cnt;
2022 void *defs[cls_def_cnt + cat_def_cnt];
2023 };
2024 */
2025
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002026 Result += "\nstruct _objc_symtab {\n";
2027 Result += "\tlong sel_ref_cnt;\n";
2028 Result += "\tSEL *refs;\n";
2029 Result += "\tshort cls_def_cnt;\n";
2030 Result += "\tshort cat_def_cnt;\n";
2031 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2032 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002033
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002034 Result += "static struct _objc_symtab "
2035 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2036 Result += "\t0, 0, " + utostr(ClsDefCount)
2037 + ", " + utostr(CatDefCount) + "\n";
2038 for (int i = 0; i < ClsDefCount; i++) {
2039 Result += "\t,&_OBJC_CLASS_";
2040 Result += ClassImplementation[i]->getName();
2041 Result += "\n";
2042 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002043
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002044 for (int i = 0; i < CatDefCount; i++) {
2045 Result += "\t,&_OBJC_CATEGORY_";
2046 Result += CategoryImplementation[i]->getClassInterface()->getName();
2047 Result += "_";
2048 Result += CategoryImplementation[i]->getName();
2049 Result += "\n";
2050 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002051
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002052 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002053
2054 // Write objc_module metadata
2055
2056 /*
2057 struct _objc_module {
2058 long version;
2059 long size;
2060 const char *name;
2061 struct _objc_symtab *symtab;
2062 }
2063 */
2064
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002065 Result += "\nstruct _objc_module {\n";
2066 Result += "\tlong version;\n";
2067 Result += "\tlong size;\n";
2068 Result += "\tconst char *name;\n";
2069 Result += "\tstruct _objc_symtab *symtab;\n";
2070 Result += "};\n\n";
2071 Result += "static struct _objc_module "
2072 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002073 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2074 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002075 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002076
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002077}
Chris Lattner311ff022007-10-16 22:36:42 +00002078