blob: 2073f7e391f2882b8c04f07db35258cc27cefa46 [file] [log] [blame]
Chris Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000021#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000022#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff1ccf4632007-10-30 03:43:13 +000023#include "clang/Lex/Lexer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000024#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000025using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000026using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000027
Chris Lattnerb429ae42007-10-11 00:43:27 +000028namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000029 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000030 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000031 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000032 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000034 unsigned MainFileID;
Chris Lattner74db1682007-10-16 21:07:07 +000035 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000036 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
37 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000038 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000039 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000040 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000041
42 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000043 FunctionDecl *MsgSendSuperFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000044 FunctionDecl *GetClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000045 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000046 FunctionDecl *CFStringFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000047
Steve Naroff0add5d22007-11-03 11:27:19 +000048 // ObjC string constant support.
49 FileVarDecl *ConstantStringClassReference;
50 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000051
Steve Naroff764c1ae2007-11-15 10:28:18 +000052 // Needed for super.
53 ObjcMethodDecl *CurMethodDecl;
54 RecordDecl *SuperStructDecl;
55
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000056 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000057 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000058 void Initialize(ASTContext &context, unsigned mainFileID) {
59 Context = &context;
60 SM = &Context->SourceMgr;
Chris Lattner569faa62007-10-11 18:38:32 +000061 MainFileID = mainFileID;
Steve Naroffe9780582007-10-23 23:50:29 +000062 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000063 MsgSendSuperFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000064 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000065 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000066 CFStringFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000067 ConstantStringClassReference = 0;
68 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 CurMethodDecl = 0;
70 SuperStructDecl = 0;
71
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000072 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000073 // declaring objc_selector outside the parameter list removes a silly
74 // scope related warning...
Steve Naroff9b99a262007-11-15 17:06:21 +000075 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Narofffcab7932007-11-05 14:55:35 +000076 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000077 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 "extern struct objc_object *objc_msgSendSuper"
79 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +000080 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-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 Jahanian8d9c7352007-11-14 22:26:25 +000087 "(struct objc_class *, struct objc_object *, ...);\n"
88 "#include <Objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +000089
Steve Naroff0744c472007-11-04 22:37:50 +000090 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
91 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000092 }
Chris Lattner569faa62007-10-11 18:38:32 +000093
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000094 // Top Level Driver code.
95 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000096 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +000097 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000098 ~RewriteTest();
99
100 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000101 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000102 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000103 void RewriteTabs();
104 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000105 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000106 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000107 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000108 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000109 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000110 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +0000111 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000112 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000113 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000114 void RewriteObjcQualifiedInterfaceTypes(
115 const FunctionTypeProto *proto, FunctionDecl *FD);
116 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000117 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
118 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000119
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000120 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000121 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000122 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000123 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000124 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000125 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000126 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000127 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
128 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
129 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000130 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000131 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
132 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000133 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000134 void SynthMsgSendSuperFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000135 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000136 void SynthCFStringFunctionDecl();
137
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000138 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000139 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
140 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000141
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000142 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
143 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000144
Steve Naroffb82c50f2007-11-11 17:19:15 +0000145 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000146 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000147 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000148 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000149 const char *ClassName,
150 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000151
152 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
153 int NumProtocols,
154 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000155 const char *ClassName,
156 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000157 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
158 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000159 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
160 ObjcIvarDecl *ivar,
161 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000162 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000163 };
164}
165
Chris Lattner258f26c2007-11-30 22:25:36 +0000166ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
167 return new RewriteTest(Diags);
168}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000169
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000170//===----------------------------------------------------------------------===//
171// Top Level Driver Code
172//===----------------------------------------------------------------------===//
173
Chris Lattner569faa62007-10-11 18:38:32 +0000174void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-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 Naroffe9780582007-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 Naroff02a82aa2007-10-30 23:14:51 +0000186 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-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 Naroff3774dd92007-10-26 20:53:56 +0000193 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
194 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000195 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
196 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000197 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
198 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000199 } else if (ObjcForwardProtocolDecl *FP =
200 dyn_cast<ObjcForwardProtocolDecl>(D)){
201 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000202 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000203 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000204 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
205 return HandleDeclInMainFile(D);
206
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000207 // Otherwise, see if there is a #import in the main file that should be
208 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000209 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000210}
211
Chris Lattnerfce2c5a2007-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 Naroff334fbc22007-11-09 15:20:18 +0000217 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000218
219 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000220 if (Stmt *Body = MD->getBody()) {
221 //Body->dump();
222 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000223 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000224 CurMethodDecl = 0;
225 }
Steve Naroff18c83382007-11-13 23:01:27 +0000226 }
Chris Lattnerfce2c5a2007-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 Naroff334fbc22007-11-09 15:20:18 +0000233 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
234 if (VD->getInit())
235 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
236 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000237 // Nothing yet.
238}
239
240RewriteTest::~RewriteTest() {
241 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000242
243 // Rewrite tabs if we care.
244 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000245
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000246 // Rewrite Objective-c meta data*
247 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000248 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000249
Chris Lattnerfce2c5a2007-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 Naroff0add5d22007-11-03 11:27:19 +0000254 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-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 Jahanian70ef5462007-11-07 18:40:28 +0000260 // Emit metadata.
261 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000262}
263
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000264//===----------------------------------------------------------------------===//
265// Syntactic (non-AST) Rewriting Code
266//===----------------------------------------------------------------------===//
267
Chris Lattner74db1682007-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 Lattnerfce2c5a2007-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 Jahanian640a01f2007-10-18 19:23:00 +0000296
Chris Lattnerfce2c5a2007-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 Lattner569faa62007-10-11 18:38:32 +0000320}
321
322
Chris Lattnerfce2c5a2007-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 Naroff71226032007-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 Naroff2aeae312007-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 Naroff4242b972007-11-05 14:36:37 +0000347 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000348 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000349 typedefString += ";\n#endif\n";
Steve Naroff71226032007-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 Lattnerfce2c5a2007-10-24 17:06:59 +0000355}
356
Steve Naroff18c83382007-11-13 23:01:27 +0000357void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000358 for (int i = 0; i < nMethods; i++) {
359 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000360 SourceLocation LocStart = Method->getLocStart();
361 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000362
Steve Narofffbfb46d2007-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 Naroff667f1682007-10-30 13:30:57 +0000369 }
370}
371
Fariborz Jahanianeca7fad2007-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 Naroff667f1682007-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 Naroff18c83382007-11-13 23:01:27 +0000390 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
391 CatDecl->getInstanceMethods());
392 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
393 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000394 // Lastly, comment out the @end.
395 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
396}
397
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000398void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000399 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000400
Steve Narofff4b7d6a2007-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 Naroff18c83382007-11-13 23:01:27 +0000406 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
407 PDecl->getInstanceMethods());
408 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
409 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000410 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000411 SourceLocation LocEnd = PDecl->getAtEndLoc();
412 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000413
Fariborz Jahanian3960e9c2007-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 Naroff268fa592007-11-14 15:03:57 +0000420 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-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 Naroff268fa592007-11-14 15:03:57 +0000427 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000428 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
429 CommentedRequired.c_str(), CommentedRequired.size());
430
431 }
432 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000433}
434
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000435void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
436 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000437 if (LocStart.isInvalid())
438 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-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 Jahanian5ea3a762007-11-13 18:44:14 +0000443void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
444 std::string &ResultStr) {
445 ResultStr += "\nstatic ";
446 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000447 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000448
449 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000450 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000451
Fariborz Jahanianbd2fd922007-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 Jahanian5ea3a762007-11-13 18:44:14 +0000459
460 NamedDecl *MethodContext = OMD->getMethodContext();
461 if (ObjcCategoryImplDecl *CID =
462 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000463 NameStr += CID->getName();
464 NameStr += "_";
Fariborz Jahanian5ea3a762007-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 Jahanianbd2fd922007-11-13 21:02:00 +0000469 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-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 Jahanianbd2fd922007-11-13 21:02:00 +0000476 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000477 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000478 // Remember this name for metadata emission
479 MethodInternalNames[OMD] = NameStr;
480 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-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 Jahanian0136e372007-11-13 20:04:28 +0000489 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
490 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-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 Jahanian0136e372007-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 Jahanian5ea3a762007-11-13 18:44:14 +0000514
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000515 if (IMD)
516 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
517 else
518 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000519
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000520 int numMethods = IMD ? IMD->getNumInstanceMethods()
521 : CID->getNumInstanceMethods();
522
523 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000524 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000525 ObjcMethodDecl *OMD;
526 if (IMD)
527 OMD = IMD->getInstanceMethods()[i];
528 else
529 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-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 Jahanian0136e372007-11-13 20:04:28 +0000540 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
541 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000542 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000543 ObjcMethodDecl *OMD;
544 if (IMD)
545 OMD = IMD->getClassMethods()[i];
546 else
547 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-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 Jahanian0136e372007-11-13 20:04:28 +0000557 if (IMD)
558 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
559 else
560 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000561}
562
Steve Naroff3774dd92007-10-26 20:53:56 +0000563void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000564 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000565 if (!ObjcForwardDecls.count(ClassDecl)) {
566 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000567 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-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 Naroff4242b972007-11-05 14:36:37 +0000573 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000574 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000575 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000576
577 // Mark this typedef as having been generated.
578 ObjcForwardDecls.insert(ClassDecl);
579 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000580 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
581
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000582 RewriteProperties(ClassDecl->getNumPropertyDecl(),
583 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000584 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
585 ClassDecl->getInstanceMethods());
586 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
587 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000588
Steve Naroff1ccf4632007-10-30 03:43:13 +0000589 // Lastly, comment out the @end.
590 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000591}
592
Steve Naroff6b759ce2007-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 Naroff292b7b92007-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 Naroff6b759ce2007-11-15 02:58:25 +0000620 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000621 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000622}
623
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000624//===----------------------------------------------------------------------===//
625// Function Body / Expression rewriting
626//===----------------------------------------------------------------------===//
627
Steve Naroff334fbc22007-11-09 15:20:18 +0000628Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-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 Naroffe9f69842007-11-07 04:08:17 +0000632 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000633 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000634 if (newStmt)
635 *CI = newStmt;
636 }
Steve Naroffe9780582007-10-23 23:50:29 +0000637
638 // Handle specific things.
639 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
640 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000641
642 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
643 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000644
645 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
646 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000647
648 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
649 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000650
Steve Naroff71226032007-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 Naroff3774dd92007-10-26 20:53:56 +0000663
Steve Naroff71226032007-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 Narofff4b7d6a2007-10-30 16:42:30 +0000667 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000668 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000669 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000670
671 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
672 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000673
674 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
675 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff764c1ae2007-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 Lattner0021f452007-10-24 16:57:36 +0000690 // Return this stmt unmodified.
691 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000692}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000693
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000694Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-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 Naroffd3287d82007-11-07 18:43:40 +0000708 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-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 Naroffd3287d82007-11-07 18:43:40 +0000723 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000724 buf += " _rethrow = objc_exception_extract(&_stack);\n";
725 buf += " else { /* @catch continue */";
726
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000727 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-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 Naroffd3287d82007-11-07 18:43:40 +0000758 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000759 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000760 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-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 Naroff8b1fb8c2007-11-07 15:32:26 +0000779 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000780 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000781 }
Steve Naroffe9f69842007-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 Lattner3c82a7e2007-11-08 04:41:51 +0000792 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-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 Lattner3c82a7e2007-11-08 04:41:51 +0000815 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000816 endLoc = endLoc.getFileLocWithOffset(-1);
817 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000818 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-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 Lattner3c82a7e2007-11-08 04:41:51 +0000826 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-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 Naroff8b1fb8c2007-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 Jahanian9447e462007-11-05 17:47:33 +0000859
Chris Lattner0021f452007-10-24 16:57:36 +0000860Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000861 // Create a new string expression.
862 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-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 Lattnerbf0bfa62007-10-17 22:35:30 +0000867 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000868 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
869 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000870 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
871 "rewriter could not replace sub-expression due to macros");
872 SourceRange Range = Exp->getSourceRange();
873 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
874 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000875 return Exp;
876 }
877
Chris Lattner4478db92007-11-30 22:53:43 +0000878 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000879 delete Exp;
880 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000881}
882
Steve Naroff296b74f2007-11-05 14:50:49 +0000883Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
884 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
885 // Create a call to sel_registerName("selName").
886 llvm::SmallVector<Expr*, 8> SelExprs;
887 QualType argType = Context->getPointerType(Context->CharTy);
888 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
889 Exp->getSelector().getName().size(),
890 false, argType, SourceLocation(),
891 SourceLocation()));
892 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
893 &SelExprs[0], SelExprs.size());
894 Rewrite.ReplaceStmt(Exp, SelExp);
895 delete Exp;
896 return SelExp;
897}
898
Steve Naroff71226032007-10-24 22:48:43 +0000899CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
900 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000901 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000902 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000903
904 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000905 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000906
907 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000908 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000909 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
910
911 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000912
Steve Naroff71226032007-10-24 22:48:43 +0000913 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
914}
915
Steve Naroffc8a92d12007-11-01 13:24:47 +0000916static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
917 const char *&startRef, const char *&endRef) {
918 while (startBuf < endBuf) {
919 if (*startBuf == '<')
920 startRef = startBuf; // mark the start.
921 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000922 if (startRef && *startRef == '<') {
923 endRef = startBuf; // mark the end.
924 return true;
925 }
926 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000927 }
928 startBuf++;
929 }
930 return false;
931}
932
933bool RewriteTest::needToScanForQualifiers(QualType T) {
934 // FIXME: we don't currently represent "id <Protocol>" in the type system.
935 if (T == Context->getObjcIdType())
936 return true;
937
938 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000939 Type *pointeeType = pType->getPointeeType().getTypePtr();
940 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
941 return true; // we have "Class <Protocol> *".
942 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000943 return false;
944}
945
946void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
947 const FunctionTypeProto *proto, FunctionDecl *FD) {
948
949 if (needToScanForQualifiers(proto->getResultType())) {
950 // Since types are unique, we need to scan the buffer.
951 SourceLocation Loc = FD->getLocation();
952
953 const char *endBuf = SM->getCharacterData(Loc);
954 const char *startBuf = endBuf;
955 while (*startBuf != ';')
956 startBuf--; // scan backward (from the decl location) for return type.
957 const char *startRef = 0, *endRef = 0;
958 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
959 // Get the locations of the startRef, endRef.
960 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
961 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
962 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000963 Rewrite.InsertText(LessLoc, "/*", 2);
964 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000965 }
966 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000967 // Now check arguments.
968 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
969 if (needToScanForQualifiers(proto->getArgType(i))) {
970 // Since types are unique, we need to scan the buffer.
971 SourceLocation Loc = FD->getLocation();
972
973 const char *startBuf = SM->getCharacterData(Loc);
974 const char *endBuf = startBuf;
975 while (*endBuf != ';')
976 endBuf++; // scan forward (from the decl location) for argument types.
977 const char *startRef = 0, *endRef = 0;
978 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
979 // Get the locations of the startRef, endRef.
980 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
981 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
982 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000983 Rewrite.InsertText(LessLoc, "/*", 2);
984 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000985 }
986 }
987 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000988}
989
Steve Naroff02a82aa2007-10-30 23:14:51 +0000990void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
991 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000992 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000993 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000994 return;
995 }
996 // Check for ObjC 'id' and class types that have been adorned with protocol
997 // information (id<p>, C<p>*). The protocol references need to be rewritten!
998 const FunctionType *funcType = FD->getType()->getAsFunctionType();
999 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +00001000 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1001 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001002}
1003
1004// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1005void RewriteTest::SynthMsgSendFunctionDecl() {
1006 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1007 llvm::SmallVector<QualType, 16> ArgTys;
1008 QualType argT = Context->getObjcIdType();
1009 assert(!argT.isNull() && "Can't find 'id' type");
1010 ArgTys.push_back(argT);
1011 argT = Context->getObjcSelType();
1012 assert(!argT.isNull() && "Can't find 'SEL' type");
1013 ArgTys.push_back(argT);
1014 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1015 &ArgTys[0], ArgTys.size(),
1016 true /*isVariadic*/);
1017 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1018 msgSendIdent, msgSendType,
1019 FunctionDecl::Extern, false, 0);
1020}
1021
Steve Naroff764c1ae2007-11-15 10:28:18 +00001022// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1023void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1024 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1025 llvm::SmallVector<QualType, 16> ArgTys;
1026 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1027 &Context->Idents.get("objc_super"), 0);
1028 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1029 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1030 ArgTys.push_back(argT);
1031 argT = Context->getObjcSelType();
1032 assert(!argT.isNull() && "Can't find 'SEL' type");
1033 ArgTys.push_back(argT);
1034 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1035 &ArgTys[0], ArgTys.size(),
1036 true /*isVariadic*/);
1037 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1038 msgSendIdent, msgSendType,
1039 FunctionDecl::Extern, false, 0);
1040}
1041
Steve Naroff02a82aa2007-10-30 23:14:51 +00001042// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1043void RewriteTest::SynthGetClassFunctionDecl() {
1044 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1045 llvm::SmallVector<QualType, 16> ArgTys;
1046 ArgTys.push_back(Context->getPointerType(
1047 Context->CharTy.getQualifiedType(QualType::Const)));
1048 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1049 &ArgTys[0], ArgTys.size(),
1050 false /*isVariadic*/);
1051 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1052 getClassIdent, getClassType,
1053 FunctionDecl::Extern, false, 0);
1054}
1055
Steve Naroffabb96362007-11-08 14:30:50 +00001056// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1057void RewriteTest::SynthCFStringFunctionDecl() {
1058 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1059 llvm::SmallVector<QualType, 16> ArgTys;
1060 ArgTys.push_back(Context->getPointerType(
1061 Context->CharTy.getQualifiedType(QualType::Const)));
1062 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1063 &ArgTys[0], ArgTys.size(),
1064 false /*isVariadic*/);
1065 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1066 getClassIdent, getClassType,
1067 FunctionDecl::Extern, false, 0);
1068}
1069
Steve Naroff0add5d22007-11-03 11:27:19 +00001070Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001071#if 1
1072 // This rewrite is specific to GCC, which has builtin support for CFString.
1073 if (!CFStringFunctionDecl)
1074 SynthCFStringFunctionDecl();
1075 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1076 llvm::SmallVector<Expr*, 8> StrExpr;
1077 StrExpr.push_back(Exp->getString());
1078 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1079 &StrExpr[0], StrExpr.size());
1080 // cast to NSConstantString *
1081 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1082 Rewrite.ReplaceStmt(Exp, cast);
1083 delete Exp;
1084 return cast;
1085#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001086 assert(ConstantStringClassReference && "Can't find constant string reference");
1087 llvm::SmallVector<Expr*, 4> InitExprs;
1088
1089 // Synthesize "(Class)&_NSConstantStringClassReference"
1090 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1091 ConstantStringClassReference->getType(),
1092 SourceLocation());
1093 QualType expType = Context->getPointerType(ClsRef->getType());
1094 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1095 expType, SourceLocation());
1096 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1097 SourceLocation());
1098 InitExprs.push_back(cast); // set the 'isa'.
1099 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1100 unsigned IntSize = static_cast<unsigned>(
1101 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1102 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1103 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1104 Exp->getLocStart());
1105 InitExprs.push_back(len); // set "int numBytes".
1106
1107 // struct NSConstantString
1108 QualType CFConstantStrType = Context->getCFConstantStringType();
1109 // (struct NSConstantString) { <exprs from above> }
1110 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1111 &InitExprs[0], InitExprs.size(),
1112 SourceLocation());
1113 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1114 // struct NSConstantString *
1115 expType = Context->getPointerType(StrRep->getType());
1116 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1117 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001118 // cast to NSConstantString *
1119 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001120 Rewrite.ReplaceStmt(Exp, cast);
1121 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001122 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001123#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001124}
1125
Steve Naroff764c1ae2007-11-15 10:28:18 +00001126ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1127 if (CurMethodDecl) { // check if we are sending a message to 'super'
1128 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1129 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1130 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1131 if (!strcmp(PVD->getName(), "self")) {
1132 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1133 if (ObjcInterfaceType *IT =
1134 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1135 if (IT->getDecl() ==
1136 CurMethodDecl->getClassInterface()->getSuperClass())
1137 return IT->getDecl();
1138 }
1139 }
1140 }
1141 }
1142 }
1143 }
1144 }
1145 return 0;
1146}
1147
1148// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1149QualType RewriteTest::getSuperStructType() {
1150 if (!SuperStructDecl) {
1151 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1152 &Context->Idents.get("objc_super"), 0);
1153 QualType FieldTypes[2];
1154
1155 // struct objc_object *receiver;
1156 FieldTypes[0] = Context->getObjcIdType();
1157 // struct objc_class *super;
1158 FieldTypes[1] = Context->getObjcClassType();
1159 // Create fields
1160 FieldDecl *FieldDecls[2];
1161
1162 for (unsigned i = 0; i < 2; ++i)
1163 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1164
1165 SuperStructDecl->defineBody(FieldDecls, 4);
1166 }
1167 return Context->getTagDeclType(SuperStructDecl);
1168}
1169
Steve Naroff71226032007-10-24 22:48:43 +00001170Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001171 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001172 if (!MsgSendFunctionDecl)
1173 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001174 if (!MsgSendSuperFunctionDecl)
1175 SynthMsgSendSuperFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001176 if (!GetClassFunctionDecl)
1177 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +00001178
Steve Naroff764c1ae2007-11-15 10:28:18 +00001179 // default to objc_msgSend().
1180 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1181
Steve Naroff71226032007-10-24 22:48:43 +00001182 // Synthesize a call to objc_msgSend().
1183 llvm::SmallVector<Expr*, 8> MsgExprs;
1184 IdentifierInfo *clsName = Exp->getClassName();
1185
1186 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1187 if (clsName) { // class message.
1188 llvm::SmallVector<Expr*, 8> ClsExprs;
1189 QualType argType = Context->getPointerType(Context->CharTy);
1190 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1191 clsName->getLength(),
1192 false, argType, SourceLocation(),
1193 SourceLocation()));
1194 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1195 &ClsExprs[0], ClsExprs.size());
1196 MsgExprs.push_back(Cls);
Steve Naroff885e2122007-11-14 23:54:14 +00001197 } else { // instance message.
1198 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001199
1200 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1201 MsgSendFlavor = MsgSendSuperFunctionDecl;
1202 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1203
1204 llvm::SmallVector<Expr*, 4> InitExprs;
1205
1206 InitExprs.push_back(recExpr); // set the 'receiver'.
1207
1208 llvm::SmallVector<Expr*, 8> ClsExprs;
1209 QualType argType = Context->getPointerType(Context->CharTy);
1210 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1211 ID->getIdentifier()->getLength(),
1212 false, argType, SourceLocation(),
1213 SourceLocation()));
1214 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1215 &ClsExprs[0], ClsExprs.size());
1216 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1217 // struct objc_super
1218 QualType superType = getSuperStructType();
1219 // (struct objc_super) { <exprs from above> }
1220 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1221 &InitExprs[0], InitExprs.size(),
1222 SourceLocation());
1223 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1224 // struct objc_super *
1225 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1226 Context->getPointerType(SuperRep->getType()),
1227 SourceLocation());
1228 MsgExprs.push_back(Unop);
1229 } else {
1230 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1231 MsgExprs.push_back(recExpr);
1232 }
Steve Naroff885e2122007-11-14 23:54:14 +00001233 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001234 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001235 llvm::SmallVector<Expr*, 8> SelExprs;
1236 QualType argType = Context->getPointerType(Context->CharTy);
1237 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1238 Exp->getSelector().getName().size(),
1239 false, argType, SourceLocation(),
1240 SourceLocation()));
1241 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1242 &SelExprs[0], SelExprs.size());
1243 MsgExprs.push_back(SelExp);
1244
1245 // Now push any user supplied arguments.
1246 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001247 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001248 // Make all implicit casts explicit...ICE comes in handy:-)
1249 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1250 // Reuse the ICE type, it is exactly what the doctor ordered.
1251 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1252 }
Steve Naroff885e2122007-11-14 23:54:14 +00001253 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001254 // We've transferred the ownership to MsgExprs. Null out the argument in
1255 // the original expression, since we will delete it below.
1256 Exp->setArg(i, 0);
1257 }
Steve Naroff0744c472007-11-04 22:37:50 +00001258 // Generate the funky cast.
1259 CastExpr *cast;
1260 llvm::SmallVector<QualType, 8> ArgTypes;
1261 QualType returnType;
1262
1263 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001264 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1265 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1266 else
1267 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001268 ArgTypes.push_back(Context->getObjcSelType());
1269 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1270 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001271 for (int i = 0; i < mDecl->getNumParams(); i++) {
1272 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001273 ArgTypes.push_back(t);
1274 }
Steve Naroff0744c472007-11-04 22:37:50 +00001275 returnType = mDecl->getResultType();
1276 } else {
1277 returnType = Context->getObjcIdType();
1278 }
1279 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001280 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001281
1282 // Create a reference to the objc_msgSend() declaration.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001283 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001284
1285 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1286 // If we don't do this cast, we get the following bizarre warning/note:
1287 // xx.m:13: warning: function called through a non-compatible type
1288 // xx.m:13: note: if this code is reached, the program will abort
1289 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1290 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001291
Steve Naroff0744c472007-11-04 22:37:50 +00001292 // Now do the "normal" pointer to function cast.
1293 QualType castType = Context->getFunctionType(returnType,
1294 &ArgTypes[0], ArgTypes.size(),
Steve Naroff29fe7462007-11-15 12:35:21 +00001295 Exp->getMethodDecl()->isVariadic());
Steve Naroff0744c472007-11-04 22:37:50 +00001296 castType = Context->getPointerType(castType);
1297 cast = new CastExpr(castType, cast, SourceLocation());
1298
1299 // Don't forget the parens to enforce the proper binding.
1300 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1301
1302 const FunctionType *FT = msgSendType->getAsFunctionType();
1303 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1304 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001305 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001306 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001307
Chris Lattner0021f452007-10-24 16:57:36 +00001308 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001309 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001310}
1311
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001312/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1313/// an objective-c class with ivars.
1314void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1315 std::string &Result) {
1316 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1317 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001318 // Do not synthesize more than once.
1319 if (ObjcSynthesizedStructs.count(CDecl))
1320 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001321 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1322 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1323 // Do it for the root
1324 SynthesizeObjcInternalStruct(RCDecl, Result);
1325 }
1326
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001327 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001328 SourceLocation LocStart = CDecl->getLocStart();
1329 SourceLocation LocEnd = CDecl->getLocEnd();
1330
1331 const char *startBuf = SM->getCharacterData(LocStart);
1332 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001333 // If no ivars and no root or if its root, directly or indirectly,
1334 // have no ivars (thus not synthesized) then no need to synthesize this class.
1335 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001336 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1337 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1338 Result.c_str(), Result.size());
1339 return;
1340 }
1341
1342 // FIXME: This has potential of causing problem. If
1343 // SynthesizeObjcInternalStruct is ever called recursively.
1344 Result += "\nstruct ";
1345 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001346
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001347 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001348 const char *cursor = strchr(startBuf, '{');
1349 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001350 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001351
1352 // rewrite the original header *without* disturbing the '{'
1353 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1354 Result.c_str(), Result.size());
1355 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1356 Result = "\n struct ";
1357 Result += RCDecl->getName();
1358 Result += " _";
1359 Result += RCDecl->getName();
1360 Result += ";\n";
1361
1362 // insert the super class structure definition.
1363 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1364 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1365 }
1366 cursor++; // past '{'
1367
1368 // Now comment out any visibility specifiers.
1369 while (cursor < endBuf) {
1370 if (*cursor == '@') {
1371 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001372 // Skip whitespace.
1373 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1374 /*scan*/;
1375
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001376 // FIXME: presence of @public, etc. inside comment results in
1377 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001378 if (!strncmp(cursor, "public", strlen("public")) ||
1379 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001380 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001381 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001382 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001383 // FIXME: If there are cases where '<' is used in ivar declaration part
1384 // of user code, then scan the ivar list and use needToScanForQualifiers
1385 // for type checking.
1386 else if (*cursor == '<') {
1387 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1388 Rewrite.InsertText(atLoc, "/* ", 3);
1389 cursor = strchr(cursor, '>');
1390 cursor++;
1391 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1392 Rewrite.InsertText(atLoc, " */", 3);
1393 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001394 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001395 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001396 // Don't forget to add a ';'!!
1397 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1398 } else { // we don't have any instance variables - insert super struct.
1399 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1400 Result += " {\n struct ";
1401 Result += RCDecl->getName();
1402 Result += " _";
1403 Result += RCDecl->getName();
1404 Result += ";\n};\n";
1405 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1406 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001407 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001408 // Mark this struct as having been generated.
1409 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001410 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001411}
1412
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001413// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1414/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001415void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001416 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001417 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001418 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001419 const char *ClassName,
1420 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001421 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001422 if (NumMethods > 0 && !objc_impl_method) {
1423 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001424 SEL _cmd;
1425 char *method_types;
1426 void *_imp;
1427 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001428 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001429 Result += "\nstruct _objc_method {\n";
1430 Result += "\tSEL _cmd;\n";
1431 Result += "\tchar *method_types;\n";
1432 Result += "\tvoid *_imp;\n";
1433 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001434
1435 /* struct _objc_method_list {
1436 struct _objc_method_list *next_method;
1437 int method_count;
1438 struct _objc_method method_list[];
1439 }
1440 */
1441 Result += "\nstruct _objc_method_list {\n";
1442 Result += "\tstruct _objc_method_list *next_method;\n";
1443 Result += "\tint method_count;\n";
1444 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001445 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001446 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001447 // Build _objc_method_list for class's methods if needed
1448 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001449 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001450 Result += prefix;
1451 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1452 Result += "_METHODS_";
1453 Result += ClassName;
1454 Result += " __attribute__ ((section (\"__OBJC, __";
1455 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001456 Result += "_meth\")))= ";
1457 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1458
1459 Result += "\t,{{(SEL)\"";
1460 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001461 std::string MethodTypeString;
1462 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1463 Result += "\", \"";
1464 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001465 Result += "\", ";
1466 Result += MethodInternalNames[Methods[0]];
1467 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001468 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001469 Result += "\t ,{(SEL)\"";
1470 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001471 std::string MethodTypeString;
1472 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1473 Result += "\", \"";
1474 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001475 Result += "\", ";
1476 Result += MethodInternalNames[Methods[i]];
1477 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001478 }
1479 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001480 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001481}
1482
1483/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1484void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1485 int NumProtocols,
1486 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001487 const char *ClassName,
1488 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001489 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001490 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001491 for (int i = 0; i < NumProtocols; i++) {
1492 ObjcProtocolDecl *PDecl = Protocols[i];
1493 // Output struct protocol_methods holder of method selector and type.
1494 if (!objc_protocol_methods &&
1495 (PDecl->getNumInstanceMethods() > 0
1496 || PDecl->getNumClassMethods() > 0)) {
1497 /* struct protocol_methods {
1498 SEL _cmd;
1499 char *method_types;
1500 }
1501 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001502 Result += "\nstruct protocol_methods {\n";
1503 Result += "\tSEL _cmd;\n";
1504 Result += "\tchar *method_types;\n";
1505 Result += "};\n";
1506
1507 /* struct _objc_protocol_method_list {
1508 int protocol_method_count;
1509 struct protocol_methods protocols[];
1510 }
1511 */
1512 Result += "\nstruct _objc_protocol_method_list {\n";
1513 Result += "\tint protocol_method_count;\n";
1514 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001515 objc_protocol_methods = true;
1516 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001517
Fariborz Jahanian04455192007-10-22 21:41:37 +00001518 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001519 int NumMethods = PDecl->getNumInstanceMethods();
1520 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001521 Result += "\nstatic struct _objc_protocol_method_list "
1522 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1523 Result += PDecl->getName();
1524 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1525 "{\n\t" + utostr(NumMethods) + "\n";
1526
Fariborz Jahanian04455192007-10-22 21:41:37 +00001527 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001528 Result += "\t,{{(SEL)\"";
1529 Result += Methods[0]->getSelector().getName().c_str();
1530 Result += "\", \"\"}\n";
1531
1532 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001533 Result += "\t ,{(SEL)\"";
1534 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001535 std::string MethodTypeString;
1536 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1537 Result += "\", \"";
1538 Result += MethodTypeString;
1539 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001540 }
1541 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001542 }
1543
1544 // Output class methods declared in this protocol.
1545 NumMethods = PDecl->getNumClassMethods();
1546 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001547 Result += "\nstatic struct _objc_protocol_method_list "
1548 "_OBJC_PROTOCOL_CLASS_METHODS_";
1549 Result += PDecl->getName();
1550 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1551 "{\n\t";
1552 Result += utostr(NumMethods);
1553 Result += "\n";
1554
Fariborz Jahanian04455192007-10-22 21:41:37 +00001555 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001556 Result += "\t,{{(SEL)\"";
1557 Result += Methods[0]->getSelector().getName().c_str();
1558 Result += "\", \"\"}\n";
1559
1560 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001561 Result += "\t ,{(SEL)\"";
1562 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001563 std::string MethodTypeString;
1564 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1565 Result += "\", \"";
1566 Result += MethodTypeString;
1567 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001568 }
1569 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001570 }
1571 // Output:
1572 /* struct _objc_protocol {
1573 // Objective-C 1.0 extensions
1574 struct _objc_protocol_extension *isa;
1575 char *protocol_name;
1576 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001577 struct _objc_protocol_method_list *instance_methods;
1578 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001579 };
1580 */
1581 static bool objc_protocol = false;
1582 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001583 Result += "\nstruct _objc_protocol {\n";
1584 Result += "\tstruct _objc_protocol_extension *isa;\n";
1585 Result += "\tchar *protocol_name;\n";
1586 Result += "\tstruct _objc_protocol **protocol_list;\n";
1587 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1588 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1589 Result += "};\n";
1590
1591 /* struct _objc_protocol_list {
1592 struct _objc_protocol_list *next;
1593 int protocol_count;
1594 struct _objc_protocol *class_protocols[];
1595 }
1596 */
1597 Result += "\nstruct _objc_protocol_list {\n";
1598 Result += "\tstruct _objc_protocol_list *next;\n";
1599 Result += "\tint protocol_count;\n";
1600 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1601 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001602 objc_protocol = true;
1603 }
1604
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001605 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1606 Result += PDecl->getName();
1607 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1608 "{\n\t0, \"";
1609 Result += PDecl->getName();
1610 Result += "\", 0, ";
1611 if (PDecl->getInstanceMethods() > 0) {
1612 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1613 Result += PDecl->getName();
1614 Result += ", ";
1615 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001616 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001617 Result += "0, ";
1618 if (PDecl->getClassMethods() > 0) {
1619 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1620 Result += PDecl->getName();
1621 Result += "\n";
1622 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001623 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001624 Result += "0\n";
1625 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001626 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001627 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001628 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1629 Result += prefix;
1630 Result += "_PROTOCOLS_";
1631 Result += ClassName;
1632 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1633 "{\n\t0, ";
1634 Result += utostr(NumProtocols);
1635 Result += "\n";
1636
1637 Result += "\t,{&_OBJC_PROTOCOL_";
1638 Result += Protocols[0]->getName();
1639 Result += " \n";
1640
1641 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001642 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001643 Result += "\t ,&_OBJC_PROTOCOL_";
1644 Result += PDecl->getName();
1645 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001646 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001647 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001648 }
1649}
1650
1651/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1652/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001653void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1654 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001655 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1656 // Find category declaration for this implementation.
1657 ObjcCategoryDecl *CDecl;
1658 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1659 CDecl = CDecl->getNextClassCategory())
1660 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1661 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001662
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001663 char *FullCategoryName = (char*)alloca(
1664 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1665 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1666
1667 // Build _objc_method_list for class's instance methods if needed
1668 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1669 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001670 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001671 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001672
1673 // Build _objc_method_list for class's class methods if needed
1674 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1675 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001676 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001677 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001678
1679 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001680 // Null CDecl is case of a category implementation with no category interface
1681 if (CDecl)
1682 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1683 CDecl->getNumReferencedProtocols(),
1684 "CATEGORY",
1685 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001686
1687 /* struct _objc_category {
1688 char *category_name;
1689 char *class_name;
1690 struct _objc_method_list *instance_methods;
1691 struct _objc_method_list *class_methods;
1692 struct _objc_protocol_list *protocols;
1693 // Objective-C 1.0 extensions
1694 uint32_t size; // sizeof (struct _objc_category)
1695 struct _objc_property_list *instance_properties; // category's own
1696 // @property decl.
1697 };
1698 */
1699
1700 static bool objc_category = false;
1701 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001702 Result += "\nstruct _objc_category {\n";
1703 Result += "\tchar *category_name;\n";
1704 Result += "\tchar *class_name;\n";
1705 Result += "\tstruct _objc_method_list *instance_methods;\n";
1706 Result += "\tstruct _objc_method_list *class_methods;\n";
1707 Result += "\tstruct _objc_protocol_list *protocols;\n";
1708 Result += "\tunsigned int size;\n";
1709 Result += "\tstruct _objc_property_list *instance_properties;\n";
1710 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001711 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001712 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001713 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1714 Result += FullCategoryName;
1715 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1716 Result += IDecl->getName();
1717 Result += "\"\n\t, \"";
1718 Result += ClassDecl->getName();
1719 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001720
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001721 if (IDecl->getNumInstanceMethods() > 0) {
1722 Result += "\t, (struct _objc_method_list *)"
1723 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1724 Result += FullCategoryName;
1725 Result += "\n";
1726 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001727 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001728 Result += "\t, 0\n";
1729 if (IDecl->getNumClassMethods() > 0) {
1730 Result += "\t, (struct _objc_method_list *)"
1731 "&_OBJC_CATEGORY_CLASS_METHODS_";
1732 Result += FullCategoryName;
1733 Result += "\n";
1734 }
1735 else
1736 Result += "\t, 0\n";
1737
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001738 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001739 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1740 Result += FullCategoryName;
1741 Result += "\n";
1742 }
1743 else
1744 Result += "\t, 0\n";
1745 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001746}
1747
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001748/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1749/// ivar offset.
1750void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1751 ObjcIvarDecl *ivar,
1752 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001753 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001754 Result += IDecl->getName();
1755 Result += ", ";
1756 Result += ivar->getName();
1757 Result += ")";
1758}
1759
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001760//===----------------------------------------------------------------------===//
1761// Meta Data Emission
1762//===----------------------------------------------------------------------===//
1763
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001764void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1765 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001766 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1767
1768 // Build _objc_ivar_list metadata for classes ivars if needed
1769 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1770 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001771 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00001772 // Explictly declared @interface's are already synthesized.
1773 if (CDecl->ImplicitInterfaceDecl()) {
1774 // FIXME: Implementation of a class with no @interface (legacy) doese not
1775 // produce correct synthesis as yet.
1776 SynthesizeObjcInternalStruct(CDecl, Result);
1777 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001778
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001779 if (NumIvars > 0) {
1780 static bool objc_ivar = false;
1781 if (!objc_ivar) {
1782 /* struct _objc_ivar {
1783 char *ivar_name;
1784 char *ivar_type;
1785 int ivar_offset;
1786 };
1787 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001788 Result += "\nstruct _objc_ivar {\n";
1789 Result += "\tchar *ivar_name;\n";
1790 Result += "\tchar *ivar_type;\n";
1791 Result += "\tint ivar_offset;\n";
1792 Result += "};\n";
1793
1794 /* struct _objc_ivar_list {
1795 int ivar_count;
1796 struct _objc_ivar ivar_list[];
1797 };
1798 */
1799 Result += "\nstruct _objc_ivar_list {\n";
1800 Result += "\tint ivar_count;\n";
1801 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001802 objc_ivar = true;
1803 }
1804
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001805 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1806 Result += IDecl->getName();
1807 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1808 "{\n\t";
1809 Result += utostr(NumIvars);
1810 Result += "\n";
1811
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001812 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1813 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001814 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001815 Result += "\t,{{\"";
1816 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001817 Result += "\", \"";
1818 std::string StrEncoding;
1819 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1820 Result += StrEncoding;
1821 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001822 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1823 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001824 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001825 Result += "\t ,{\"";
1826 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001827 Result += "\", \"";
1828 std::string StrEncoding;
1829 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1830 Result += StrEncoding;
1831 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001832 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1833 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001834 }
1835
1836 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001837 }
1838
1839 // Build _objc_method_list for class's instance methods if needed
1840 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1841 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001842 true,
1843 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001844
1845 // Build _objc_method_list for class's class methods if needed
1846 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001847 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001848 false,
1849 "", IDecl->getName(), Result);
1850
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001851 // Protocols referenced in class declaration?
1852 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1853 CDecl->getNumIntfRefProtocols(),
1854 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001855 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001856
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001857
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001858 // Declaration of class/meta-class metadata
1859 /* struct _objc_class {
1860 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001861 const char *super_class_name;
1862 char *name;
1863 long version;
1864 long info;
1865 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001866 struct _objc_ivar_list *ivars;
1867 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001868 struct objc_cache *cache;
1869 struct objc_protocol_list *protocols;
1870 const char *ivar_layout;
1871 struct _objc_class_ext *ext;
1872 };
1873 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001874 static bool objc_class = false;
1875 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001876 Result += "\nstruct _objc_class {\n";
1877 Result += "\tstruct _objc_class *isa;\n";
1878 Result += "\tconst char *super_class_name;\n";
1879 Result += "\tchar *name;\n";
1880 Result += "\tlong version;\n";
1881 Result += "\tlong info;\n";
1882 Result += "\tlong instance_size;\n";
1883 Result += "\tstruct _objc_ivar_list *ivars;\n";
1884 Result += "\tstruct _objc_method_list *methods;\n";
1885 Result += "\tstruct objc_cache *cache;\n";
1886 Result += "\tstruct _objc_protocol_list *protocols;\n";
1887 Result += "\tconst char *ivar_layout;\n";
1888 Result += "\tstruct _objc_class_ext *ext;\n";
1889 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001890 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001891 }
1892
1893 // Meta-class metadata generation.
1894 ObjcInterfaceDecl *RootClass = 0;
1895 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1896 while (SuperClass) {
1897 RootClass = SuperClass;
1898 SuperClass = SuperClass->getSuperClass();
1899 }
1900 SuperClass = CDecl->getSuperClass();
1901
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001902 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1903 Result += CDecl->getName();
1904 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1905 "{\n\t(struct _objc_class *)\"";
1906 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1907 Result += "\"";
1908
1909 if (SuperClass) {
1910 Result += ", \"";
1911 Result += SuperClass->getName();
1912 Result += "\", \"";
1913 Result += CDecl->getName();
1914 Result += "\"";
1915 }
1916 else {
1917 Result += ", 0, \"";
1918 Result += CDecl->getName();
1919 Result += "\"";
1920 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001921 // TODO: 'ivars' field for root class is currently set to 0.
1922 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001923 Result += ", 0,2, sizeof(struct _objc_class), 0";
1924 if (CDecl->getNumClassMethods() > 0) {
1925 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1926 Result += CDecl->getName();
1927 Result += "\n";
1928 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001929 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001930 Result += ", 0\n";
1931 if (CDecl->getNumIntfRefProtocols() > 0) {
1932 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1933 Result += CDecl->getName();
1934 Result += ",0,0\n";
1935 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001936 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001937 Result += "\t,0,0,0,0\n";
1938 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001939
1940 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001941 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1942 Result += CDecl->getName();
1943 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1944 "{\n\t&_OBJC_METACLASS_";
1945 Result += CDecl->getName();
1946 if (SuperClass) {
1947 Result += ", \"";
1948 Result += SuperClass->getName();
1949 Result += "\", \"";
1950 Result += CDecl->getName();
1951 Result += "\"";
1952 }
1953 else {
1954 Result += ", 0, \"";
1955 Result += CDecl->getName();
1956 Result += "\"";
1957 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001958 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001959 Result += ", 0,1";
1960 if (!ObjcSynthesizedStructs.count(CDecl))
1961 Result += ",0";
1962 else {
1963 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001964 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001965 Result += CDecl->getName();
1966 Result += ")";
1967 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001968 if (NumIvars > 0) {
1969 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1970 Result += CDecl->getName();
1971 Result += "\n\t";
1972 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001973 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001974 Result += ",0";
1975 if (IDecl->getNumInstanceMethods() > 0) {
1976 Result += ", &_OBJC_INSTANCE_METHODS_";
1977 Result += CDecl->getName();
1978 Result += ", 0\n\t";
1979 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001980 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001981 Result += ",0,0";
1982 if (CDecl->getNumIntfRefProtocols() > 0) {
1983 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1984 Result += CDecl->getName();
1985 Result += ", 0,0\n";
1986 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001987 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001988 Result += ",0,0,0\n";
1989 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001990}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001991
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001992/// RewriteImplementations - This routine rewrites all method implementations
1993/// and emits meta-data.
1994
1995void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001996 int ClsDefCount = ClassImplementation.size();
1997 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001998
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001999 if (ClsDefCount == 0 && CatDefCount == 0)
2000 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002001 // Rewrite implemented methods
2002 for (int i = 0; i < ClsDefCount; i++)
2003 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002004
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002005 for (int i = 0; i < CatDefCount; i++)
2006 RewriteImplementationDecl(CategoryImplementation[i]);
2007
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002008 // This is needed for use of offsetof
2009 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002010
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002011 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002012 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002013 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002014
2015 // For each implemented category, write out all its meta data.
2016 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002017 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002018
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002019 // Write objc_symtab metadata
2020 /*
2021 struct _objc_symtab
2022 {
2023 long sel_ref_cnt;
2024 SEL *refs;
2025 short cls_def_cnt;
2026 short cat_def_cnt;
2027 void *defs[cls_def_cnt + cat_def_cnt];
2028 };
2029 */
2030
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002031 Result += "\nstruct _objc_symtab {\n";
2032 Result += "\tlong sel_ref_cnt;\n";
2033 Result += "\tSEL *refs;\n";
2034 Result += "\tshort cls_def_cnt;\n";
2035 Result += "\tshort cat_def_cnt;\n";
2036 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2037 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002038
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002039 Result += "static struct _objc_symtab "
2040 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2041 Result += "\t0, 0, " + utostr(ClsDefCount)
2042 + ", " + utostr(CatDefCount) + "\n";
2043 for (int i = 0; i < ClsDefCount; i++) {
2044 Result += "\t,&_OBJC_CLASS_";
2045 Result += ClassImplementation[i]->getName();
2046 Result += "\n";
2047 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002048
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002049 for (int i = 0; i < CatDefCount; i++) {
2050 Result += "\t,&_OBJC_CATEGORY_";
2051 Result += CategoryImplementation[i]->getClassInterface()->getName();
2052 Result += "_";
2053 Result += CategoryImplementation[i]->getName();
2054 Result += "\n";
2055 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002056
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002057 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002058
2059 // Write objc_module metadata
2060
2061 /*
2062 struct _objc_module {
2063 long version;
2064 long size;
2065 const char *name;
2066 struct _objc_symtab *symtab;
2067 }
2068 */
2069
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002070 Result += "\nstruct _objc_module {\n";
2071 Result += "\tlong version;\n";
2072 Result += "\tlong size;\n";
2073 Result += "\tconst char *name;\n";
2074 Result += "\tstruct _objc_symtab *symtab;\n";
2075 Result += "};\n\n";
2076 Result += "static struct _objc_module "
2077 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002078 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2079 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002080 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002081
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002082}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002083