blob: 66e22037260d795c1cb239aa27d906402efe45f9 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000020using namespace clang;
21
Chris Lattner77cd2a02007-10-11 00:43:27 +000022namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000023 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000024 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000025 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000026 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000027 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000029 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
30 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Steve Naroffebf2b562007-10-23 23:50:29 +000031
32 FunctionDecl *MsgSendFunctionDecl;
33 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000034 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000035
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000036 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000037 public:
Chris Lattner01c57482007-10-17 22:35:30 +000038 void Initialize(ASTContext &context, unsigned mainFileID) {
39 Context = &context;
40 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000041 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000042 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000043 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000044 SelGetUidFunctionDecl = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000045 Rewrite.setSourceMgr(Context->SourceMgr);
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 }
Chris Lattner8a12c272007-10-11 18:38:32 +000047
Chris Lattnerf04da132007-10-24 17:06:59 +000048 // Top Level Driver code.
49 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000051 ~RewriteTest();
52
53 // Syntactic Rewriting.
Chris Lattner2c64b7b2007-10-16 21:07:07 +000054 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000055 void RewriteTabs();
56 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Chris Lattner311ff022007-10-16 22:36:42 +000057
Chris Lattnerf04da132007-10-24 17:06:59 +000058 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000059 Stmt *RewriteFunctionBody(Stmt *S);
60 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
61 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000062 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
63 Expr **args, unsigned nargs);
Chris Lattnerf04da132007-10-24 17:06:59 +000064 // Metadata emission.
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000065 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl);
66
67 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl);
68
69 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
70 int NumMethods,
71 const char *prefix,
72 const char *MethodKind,
73 const char *ClassName);
74
75 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
76 int NumProtocols,
77 const char *prefix,
78 const char *ClassName);
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000079 void WriteObjcMetaData();
Chris Lattner77cd2a02007-10-11 00:43:27 +000080 };
81}
82
Chris Lattner8a12c272007-10-11 18:38:32 +000083ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +000084
Chris Lattnerf04da132007-10-24 17:06:59 +000085//===----------------------------------------------------------------------===//
86// Top Level Driver Code
87//===----------------------------------------------------------------------===//
88
Chris Lattner8a12c272007-10-11 18:38:32 +000089void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000090 // Two cases: either the decl could be in the main file, or it could be in a
91 // #included file. If the former, rewrite it now. If the later, check to see
92 // if we rewrote the #include/#import.
93 SourceLocation Loc = D->getLocation();
94 Loc = SM->getLogicalLoc(Loc);
95
96 // If this is for a builtin, ignore it.
97 if (Loc.isInvalid()) return;
98
Steve Naroffebf2b562007-10-23 23:50:29 +000099 // Look for built-in declarations that we need to refer during the rewrite.
100 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffc0006092007-10-24 01:09:48 +0000101 if (strcmp(FD->getName(), "objc_msgSend") == 0)
Steve Naroffebf2b562007-10-23 23:50:29 +0000102 MsgSendFunctionDecl = FD;
Steve Naroffc0006092007-10-24 01:09:48 +0000103 else if (strcmp(FD->getName(), "objc_getClass") == 0)
Steve Naroffebf2b562007-10-23 23:50:29 +0000104 GetClassFunctionDecl = FD;
Steve Naroff934f2762007-10-24 22:48:43 +0000105 else if (strcmp(FD->getName(), "sel_getUid") == 0)
106 SelGetUidFunctionDecl = FD;
Steve Naroffebf2b562007-10-23 23:50:29 +0000107 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000108
109 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000110 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
111 return HandleDeclInMainFile(D);
112
Chris Lattnerf04da132007-10-24 17:06:59 +0000113 // Otherwise, see if there is a #import in the main file that should be
114 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000115 RewriteInclude(Loc);
116}
117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118/// HandleDeclInMainFile - This is called for each top-level decl defined in the
119/// main file of the input.
120void RewriteTest::HandleDeclInMainFile(Decl *D) {
121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
122 if (Stmt *Body = FD->getBody())
123 FD->setBody(RewriteFunctionBody(Body));
124
125 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
126 ClassImplementation.push_back(CI);
127 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
128 CategoryImplementation.push_back(CI);
129 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
130 RewriteForwardClassDecl(CD);
131 // Nothing yet.
132}
133
134RewriteTest::~RewriteTest() {
135 // Get the top-level buffer that this corresponds to.
136 RewriteTabs();
137
138 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
139 // we are done.
140 if (const RewriteBuffer *RewriteBuf =
141 Rewrite.getRewriteBufferFor(MainFileID)) {
142 printf("Changed:\n");
143 std::string S(RewriteBuf->begin(), RewriteBuf->end());
144 printf("%s\n", S.c_str());
145 } else {
146 printf("No changes\n");
147 }
148
149 // Rewrite Objective-c meta data*
150 WriteObjcMetaData();
151}
152
153//===----------------------------------------------------------------------===//
154// Syntactic (non-AST) Rewriting Code
155//===----------------------------------------------------------------------===//
156
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000157void RewriteTest::RewriteInclude(SourceLocation Loc) {
158 // Rip up the #include stack to the main file.
159 SourceLocation IncLoc = Loc, NextLoc = Loc;
160 do {
161 IncLoc = Loc;
162 Loc = SM->getLogicalLoc(NextLoc);
163 NextLoc = SM->getIncludeLoc(Loc);
164 } while (!NextLoc.isInvalid());
165
166 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
167 // IncLoc indicates the header that was included if it is useful.
168 IncLoc = SM->getLogicalLoc(IncLoc);
169 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
170 Loc == LastIncLoc)
171 return;
172 LastIncLoc = Loc;
173
174 unsigned IncCol = SM->getColumnNumber(Loc);
175 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
176
177 // Replace the #import with #include.
178 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
179}
180
Chris Lattnerf04da132007-10-24 17:06:59 +0000181void RewriteTest::RewriteTabs() {
182 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
183 const char *MainBufStart = MainBuf.first;
184 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000185
Chris Lattnerf04da132007-10-24 17:06:59 +0000186 // Loop over the whole file, looking for tabs.
187 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
188 if (*BufPtr != '\t')
189 continue;
190
191 // Okay, we found a tab. This tab will turn into at least one character,
192 // but it depends on which 'virtual column' it is in. Compute that now.
193 unsigned VCol = 0;
194 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
195 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
196 ++VCol;
197
198 // Okay, now that we know the virtual column, we know how many spaces to
199 // insert. We assume 8-character tab-stops.
200 unsigned Spaces = 8-(VCol & 7);
201
202 // Get the location of the tab.
203 SourceLocation TabLoc =
204 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
205
206 // Rewrite the single tab character into a sequence of spaces.
207 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
208 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000209}
210
211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
213 int numDecls = ClassDecl->getNumForwardDecls();
214 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
215
216 // Get the start location and compute the semi location.
217 SourceLocation startLoc = ClassDecl->getLocation();
218 const char *startBuf = SM->getCharacterData(startLoc);
219 const char *semiPtr = strchr(startBuf, ';');
220
221 // Translate to typedef's that forward reference structs with the same name
222 // as the class. As a convenience, we include the original declaration
223 // as a comment.
224 std::string typedefString;
225 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000226 typedefString.append(startBuf, semiPtr-startBuf+1);
227 typedefString += "\n";
228 for (int i = 0; i < numDecls; i++) {
229 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
230 typedefString += "typedef struct ";
231 typedefString += ForwardDecl->getName();
232 typedefString += " ";
233 typedefString += ForwardDecl->getName();
234 typedefString += ";\n";
235 }
236
237 // Replace the @class with typedefs corresponding to the classes.
238 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
239 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000240}
241
242//===----------------------------------------------------------------------===//
243// Function Body / Expression rewriting
244//===----------------------------------------------------------------------===//
245
Chris Lattnere64b7772007-10-24 16:57:36 +0000246Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000247 // Otherwise, just rewrite all children.
248 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
249 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000250 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000251 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000252
253 // Handle specific things.
254 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
255 return RewriteAtEncode(AtEncode);
256
Steve Naroff934f2762007-10-24 22:48:43 +0000257 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
258 // Before we rewrite it, put the original message expression in a comment.
259 SourceLocation startLoc = MessExpr->getLocStart();
260 SourceLocation endLoc = MessExpr->getLocEnd();
261
262 const char *startBuf = SM->getCharacterData(startLoc);
263 const char *endBuf = SM->getCharacterData(endLoc);
264
265 std::string messString;
266 messString += "// ";
267 messString.append(startBuf, endBuf-startBuf+1);
268 messString += "\n";
269
270 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
271 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
272 // Tried this, but it didn't work either...
273 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000274 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000275 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000276 // Return this stmt unmodified.
277 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000278}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000281 // Create a new string expression.
282 QualType StrType = Context->getPointerType(Context->CharTy);
283 Expr *Replacement = new StringLiteral("foo", 3, false, StrType,
284 SourceLocation(), SourceLocation());
285 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000286 delete Exp;
287 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000288}
289
Steve Naroff934f2762007-10-24 22:48:43 +0000290CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
291 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000292 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000293 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000294
295 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000296 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000297
298 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000300 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
301
302 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000303
Steve Naroff934f2762007-10-24 22:48:43 +0000304 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
305}
306
307Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
308 assert(MsgSendFunctionDecl && "Can't find objc_msgSend() decl");
309 assert(SelGetUidFunctionDecl && "Can't find sel_getUid() decl");
310 assert(GetClassFunctionDecl && "Can't find objc_getClass() decl");
311
312 // Synthesize a call to objc_msgSend().
313 llvm::SmallVector<Expr*, 8> MsgExprs;
314 IdentifierInfo *clsName = Exp->getClassName();
315
316 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
317 if (clsName) { // class message.
318 llvm::SmallVector<Expr*, 8> ClsExprs;
319 QualType argType = Context->getPointerType(Context->CharTy);
320 ClsExprs.push_back(new StringLiteral(clsName->getName(),
321 clsName->getLength(),
322 false, argType, SourceLocation(),
323 SourceLocation()));
324 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
325 &ClsExprs[0], ClsExprs.size());
326 MsgExprs.push_back(Cls);
327 } else // instance message.
328 MsgExprs.push_back(Exp->getReceiver());
329
330 // Create a call to sel_getUid("selName"), it will be the 2nd argument.
331 llvm::SmallVector<Expr*, 8> SelExprs;
332 QualType argType = Context->getPointerType(Context->CharTy);
333 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
334 Exp->getSelector().getName().size(),
335 false, argType, SourceLocation(),
336 SourceLocation()));
337 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
338 &SelExprs[0], SelExprs.size());
339 MsgExprs.push_back(SelExp);
340
341 // Now push any user supplied arguments.
342 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
343 MsgExprs.push_back(Exp->getArg(i));
344 // We've transferred the ownership to MsgExprs. Null out the argument in
345 // the original expression, since we will delete it below.
346 Exp->setArg(i, 0);
347 }
348 CallExpr *MessExp = SynthesizeCallToFunctionDecl(MsgSendFunctionDecl,
349 &MsgExprs[0], MsgExprs.size());
350 // Now do the actual rewrite.
351 Rewrite.ReplaceStmt(Exp, MessExp);
352
Chris Lattnere64b7772007-10-24 16:57:36 +0000353 delete Exp;
Steve Naroff934f2762007-10-24 22:48:43 +0000354 return MessExp;
Steve Naroffebf2b562007-10-23 23:50:29 +0000355}
356
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000357// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
358/// class methods.
359void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
360 int NumMethods,
361 const char *prefix,
362 const char *MethodKind,
363 const char *ClassName) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000364 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000365 if (NumMethods > 0 && !objc_impl_method) {
366 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000367 SEL _cmd;
368 char *method_types;
369 void *_imp;
370 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000371 */
372 printf("\nstruct _objc_method {\n");
373 printf("\tSEL _cmd;\n");
374 printf("\tchar *method_types;\n");
375 printf("\tvoid *_imp;\n");
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000376 printf("};\n");
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000377 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000378 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000379 // Build _objc_method_list for class's methods if needed
380 if (NumMethods > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000381 /* struct _objc_method_list {
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000382 struct _objc_method_list *next_method;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000383 int method_count;
384 struct _objc_method method_list[method_count];
385 }
386 */
387 printf("\nstatic struct {\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000388 printf("\tstruct _objc_method_list *next_method;\n");
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000389 printf("\tint method_count;\n");
390 printf("\tstruct _objc_method method_list[%d];\n", NumMethods);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000391 printf("} _OBJC_%s%s_METHODS_%s "
392 "__attribute__ ((section (\"__OBJC, __inst_meth\")))= "
393 "{\n\t0, %d\n", prefix, MethodKind, ClassName, NumMethods);
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000394 for (int i = 0; i < NumMethods; i++)
395 // TODO: 1) method selector name may hav to go into their own section
396 // 2) encode method types for use here (which may have to go into
397 // __meth_var_types section, 3) Need method address as 3rd initializer.
398 printf("\t,(SEL)\"%s\", \"\", 0\n",
399 Methods[i]->getSelector().getName().c_str());
400 printf("};\n");
401 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000402}
403
404/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
405void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
406 int NumProtocols,
407 const char *prefix,
408 const char *ClassName) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000409 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000410 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000411 for (int i = 0; i < NumProtocols; i++) {
412 ObjcProtocolDecl *PDecl = Protocols[i];
413 // Output struct protocol_methods holder of method selector and type.
414 if (!objc_protocol_methods &&
415 (PDecl->getNumInstanceMethods() > 0
416 || PDecl->getNumClassMethods() > 0)) {
417 /* struct protocol_methods {
418 SEL _cmd;
419 char *method_types;
420 }
421 */
422 printf("\nstruct protocol_methods {\n");
423 printf("\tSEL _cmd;\n");
424 printf("\tchar *method_types;\n");
425 printf("};\n");
426 objc_protocol_methods = true;
427 }
428 // Output instance methods declared in this protocol.
429 /* struct _objc_protocol_method_list {
430 int protocol_method_count;
431 struct protocol_methods protocols[protocol_method_count];
432 }
433 */
434 int NumMethods = PDecl->getNumInstanceMethods();
435 if (NumMethods > 0) {
436 printf("\nstatic struct {\n");
437 printf("\tint protocol_method_count;\n");
438 printf("\tstruct protocol_methods protocols[%d];\n", NumMethods);
439 printf("} _OBJC_PROTOCOL_INSTANCE_METHODS_%s "
440 "__attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
441 "{\n\t%d\n",PDecl->getName(), NumMethods);
442 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
443 for (int i = 0; i < NumMethods; i++)
444 // TODO: 1) method selector name may hav to go into their own section
445 // 2) encode method types for use here (which may have to go into
446 // __meth_var_types section.
447 printf("\t,(SEL)\"%s\", \"\"\n",
448 Methods[i]->getSelector().getName().c_str());
449 printf("};\n");
450 }
451
452 // Output class methods declared in this protocol.
453 NumMethods = PDecl->getNumClassMethods();
454 if (NumMethods > 0) {
455 printf("\nstatic struct {\n");
456 printf("\tint protocol_method_count;\n");
457 printf("\tstruct protocol_methods protocols[%d];\n", NumMethods);
458 printf("} _OBJC_PROTOCOL_CLASS_METHODS_%s "
459 "__attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
460 "{\n\t%d\n",PDecl->getName(), NumMethods);
461 ObjcMethodDecl **Methods = PDecl->getClassMethods();
462 for (int i = 0; i < NumMethods; i++)
463 // TODO: 1) method selector name may hav to go into their own section
464 // 2) encode method types for use here (which may have to go into
465 // __meth_var_types section.
466 printf("\t,(SEL)\"%s\", \"\"\n",
467 Methods[i]->getSelector().getName().c_str());
468 printf("};\n");
469 }
470 // Output:
471 /* struct _objc_protocol {
472 // Objective-C 1.0 extensions
473 struct _objc_protocol_extension *isa;
474 char *protocol_name;
475 struct _objc_protocol **protocol_list;
476 struct _objc__method_prototype_list *instance_methods;
477 struct _objc__method_prototype_list *class_methods;
478 };
479 */
480 static bool objc_protocol = false;
481 if (!objc_protocol) {
482 printf("\nstruct _objc_protocol {\n");
483 printf("\tstruct _objc_protocol_extension *isa;\n");
484 printf("\tchar *protocol_name;\n");
485 printf("\tstruct _objc_protocol **protocol_list;\n");
486 printf("\tstruct _objc__method_prototype_list *instance_methods;\n");
487 printf("\tstruct _objc__method_prototype_list *class_methods;\n");
488 printf("};\n");
489 objc_protocol = true;
490 }
491
492 printf("\nstatic struct _objc_protocol _OBJC_PROTOCOL_%s "
493 "__attribute__ ((section (\"__OBJC, __protocol\")))= "
494 "{\n\t0, \"%s\", 0, ", PDecl->getName(), PDecl->getName());
495 if (PDecl->getInstanceMethods() > 0)
496 printf("(struct _objc__method_prototype_list *)"
497 "&_OBJC_PROTOCOL_INSTANCE_METHODS_%s, ", PDecl->getName());
498 else
499 printf("0, ");
500 if (PDecl->getClassMethods() > 0)
501 printf("(struct _objc__method_prototype_list *)"
502 "&_OBJC_PROTOCOL_CLASS_METHODS_%s\n", PDecl->getName());
503 else
504 printf("0\n");
505 printf("};\n");
506 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000507 // Output the top lovel protocol meta-data for the class.
508 /* struct _objc_protocol_list {
509 struct _objc_protocol_list *next;
510 int protocol_count;
511 struct _objc_protocol *class_protocols[protocol_count];
512 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000513 */
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000514 printf("\nstatic struct {\n");
515 printf("\tstruct _objc_protocol_list *next;\n");
516 printf("\tint protocol_count;\n");
517 printf("\tstruct _objc_protocol *class_protocols[%d];\n"
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000518 "} _OBJC_%s_PROTOCOLS_%s "
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000519 "__attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000520 "{\n\t0, %d\n",NumProtocols, prefix,
521 ClassName, NumProtocols);
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000522 for (int i = 0; i < NumProtocols; i++) {
523 ObjcProtocolDecl *PDecl = Protocols[i];
524 printf("\t,&_OBJC_PROTOCOL_%s \n",
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000525 PDecl->getName());
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000526 }
527 printf("};\n");
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000528 }
529}
530
531/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
532/// implementation.
533void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl) {
534 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
535 // Find category declaration for this implementation.
536 ObjcCategoryDecl *CDecl;
537 for (CDecl = ClassDecl->getCategoryList(); CDecl;
538 CDecl = CDecl->getNextClassCategory())
539 if (CDecl->getIdentifier() == IDecl->getIdentifier())
540 break;
541 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
542
543 char *FullCategoryName = (char*)alloca(
544 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
545 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
546
547 // Build _objc_method_list for class's instance methods if needed
548 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
549 IDecl->getNumInstanceMethods(),
550 "CATEGORY_", "INSTANCE", FullCategoryName);
551
552 // Build _objc_method_list for class's class methods if needed
553 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
554 IDecl->getNumClassMethods(),
555 "CATEGORY_", "CLASS", FullCategoryName);
556
557 // Protocols referenced in class declaration?
558 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
559 CDecl->getNumReferencedProtocols(),
560 "CATEGORY",
561 FullCategoryName);
562
563 /* struct _objc_category {
564 char *category_name;
565 char *class_name;
566 struct _objc_method_list *instance_methods;
567 struct _objc_method_list *class_methods;
568 struct _objc_protocol_list *protocols;
569 // Objective-C 1.0 extensions
570 uint32_t size; // sizeof (struct _objc_category)
571 struct _objc_property_list *instance_properties; // category's own
572 // @property decl.
573 };
574 */
575
576 static bool objc_category = false;
577 if (!objc_category) {
578 printf("\nstruct _objc_category {\n");
579 printf("\tchar *category_name;\n");
580 printf("\tchar *class_name;\n");
581 printf("\tstruct _objc_method_list *instance_methods;\n");
582 printf("\tstruct _objc_method_list *class_methods;\n");
583 printf("\tstruct _objc_protocol_list *protocols;\n");
584 printf("\tunsigned int size;\n");
585 printf("\tstruct _objc_property_list *instance_properties;\n");
586 printf("};\n");
587 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000588 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000589 printf("\nstatic struct _objc_category _OBJC_CATEGORY_%s "
590 "__attribute__ ((section (\"__OBJC, __category\")))= {\n"
591 "\t\"%s\"\n\t, \"%s\"\n",FullCategoryName,
592 IDecl->getName(),
593 ClassDecl->getName());
594 if (IDecl->getNumInstanceMethods() > 0)
595 printf("\t, (struct _objc_method_list *)"
596 "&_OBJC_CATEGORY_INSTANCE_METHODS_%s\n",
597 FullCategoryName);
598 else
599 printf("\t, 0\n");
600 if (IDecl->getNumClassMethods() > 0)
601 printf("\t, (struct _objc_method_list *)"
602 "&_OBJC_CATEGORY_CLASS_METHODS_%s\n",
603 FullCategoryName);
604 else
605 printf("\t, 0\n");
606
607 if (CDecl->getNumReferencedProtocols() > 0)
608 printf("\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_%s\n",
609 FullCategoryName);
610 else
611 printf("\t, 0\n");
Fariborz Jahanian1a0965e2007-10-24 21:25:12 +0000612 printf("\t, sizeof(struct _objc_category), 0\n};\n");
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000613}
614
615//===----------------------------------------------------------------------===//
616// Meta Data Emission
617//===----------------------------------------------------------------------===//
618
619void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl) {
620 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
621
622 // Build _objc_ivar_list metadata for classes ivars if needed
623 int NumIvars = IDecl->getImplDeclNumIvars() > 0
624 ? IDecl->getImplDeclNumIvars()
625 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
626
627 if (NumIvars > 0) {
628 static bool objc_ivar = false;
629 if (!objc_ivar) {
630 /* struct _objc_ivar {
631 char *ivar_name;
632 char *ivar_type;
633 int ivar_offset;
634 };
635 */
636 printf("\nstruct _objc_ivar {\n");
637 printf("\tchar *ivar_name;\n");
638 printf("\tchar *ivar_type;\n");
639 printf("\tint ivar_offset;\n");
640 printf("};\n");
641 objc_ivar = true;
642 }
643
644 /* struct _objc_ivar_list {
645 int ivar_count;
646 struct _objc_ivar ivar_list[ivar_count];
647 };
648 */
649 printf("\nstatic struct {\n");
650 printf("\tint ivar_count;\n");
651 printf("\tstruct _objc_ivar ivar_list[%d];\n", NumIvars);
652 printf("} _OBJC_INSTANCE_VARIABLES_%s "
653 "__attribute__ ((section (\"__OBJC, __instance_vars\")))= "
654 "{\n\t%d\n",IDecl->getName(),
655 NumIvars);
656 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
657 ? IDecl->getImplDeclIVars()
658 : CDecl->getIntfDeclIvars();
659 for (int i = 0; i < NumIvars; i++)
660 // TODO: 1) ivar names may have to go to another section. 2) encode
661 // ivar_type type of each ivar . 3) compute and add ivar offset.
662 printf("\t,\"%s\", \"\", 0\n", Ivars[i]->getName());
663 printf("};\n");
664 }
665
666 // Build _objc_method_list for class's instance methods if needed
667 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
668 IDecl->getNumInstanceMethods(),
669 "", "INSTANCE", IDecl->getName());
670
671 // Build _objc_method_list for class's class methods if needed
672 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
673 IDecl->getNumClassMethods(),
674 "", "CLASS", IDecl->getName());
675
676 // Protocols referenced in class declaration?
677 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
678 CDecl->getNumIntfRefProtocols(),
679 "CLASS",
680 CDecl->getName());
681
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000682
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000683 // Declaration of class/meta-class metadata
684 /* struct _objc_class {
685 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000686 const char *super_class_name;
687 char *name;
688 long version;
689 long info;
690 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000691 struct _objc_ivar_list *ivars;
692 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000693 struct objc_cache *cache;
694 struct objc_protocol_list *protocols;
695 const char *ivar_layout;
696 struct _objc_class_ext *ext;
697 };
698 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000699 static bool objc_class = false;
700 if (!objc_class) {
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000701 printf("\nstruct _objc_class {\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000702 printf("\tstruct _objc_class *isa;\n");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000703 printf("\tconst char *super_class_name;\n");
704 printf("\tchar *name;\n");
705 printf("\tlong version;\n");
706 printf("\tlong info;\n");
707 printf("\tlong instance_size;\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000708 printf("\tstruct _objc_ivar_list *ivars;\n");
709 printf("\tstruct _objc_method_list *methods;\n");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000710 printf("\tstruct objc_cache *cache;\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000711 printf("\tstruct _objc_protocol_list *protocols;\n");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000712 printf("\tconst char *ivar_layout;\n");
713 printf("\tstruct _objc_class_ext *ext;\n");
714 printf("};\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000715 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000716 }
717
718 // Meta-class metadata generation.
719 ObjcInterfaceDecl *RootClass = 0;
720 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
721 while (SuperClass) {
722 RootClass = SuperClass;
723 SuperClass = SuperClass->getSuperClass();
724 }
725 SuperClass = CDecl->getSuperClass();
726
727 printf("\nstatic struct _objc_class _OBJC_METACLASS_%s "
728 "__attribute__ ((section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000729 "{\n\t(struct _objc_class *)\"%s\"",
730 CDecl->getName(), RootClass ? RootClass->getName()
731 : CDecl->getName());
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000732 if (SuperClass)
733 printf(", \"%s\", \"%s\"", SuperClass->getName(), CDecl->getName());
734 else
735 printf(", 0, \"%s\"", CDecl->getName());
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000736 // TODO: 'ivars' field for root class is currently set to 0.
737 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian1a0965e2007-10-24 21:25:12 +0000738 printf(", 0,2, sizeof(struct _objc_class), 0");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000739 if (CDecl->getNumClassMethods() > 0)
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000740 printf("\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_%s\n",
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000741 CDecl->getName());
742 else
743 printf(", 0\n");
Fariborz Jahanian454cb012007-10-24 20:54:23 +0000744 if (CDecl->getNumIntfRefProtocols() > 0)
745 printf("\t,0,(struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_%s,0,0\n",
746 CDecl->getName());
747 else
748 printf("\t,0,0,0,0\n");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000749 printf("};\n");
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000750
751 // class metadata generation.
752 printf("\nstatic struct _objc_class _OBJC_CLASS_%s "
753 "__attribute__ ((section (\"__OBJC, __class\")))= "
754 "{\n\t&_OBJC_METACLASS_%s", CDecl->getName(), CDecl->getName());
755 if (SuperClass)
756 printf(", \"%s\", \"%s\"", SuperClass->getName(), CDecl->getName());
757 else
758 printf(", 0, \"%s\"", CDecl->getName());
759 // 'info' field is initialized to CLS_CLASS(1) for class
760 // TODO: instance_size is curently set to 0.
761 printf(", 0,1,0");
762 if (NumIvars > 0)
763 printf(", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_%s\n\t",
764 CDecl->getName());
765 else
766 printf(",0");
767 if (IDecl->getNumInstanceMethods() > 0)
768 printf(", (struct _objc_method_list*)&_OBJC_INSTANCE_METHODS_%s, 0\n\t",
769 CDecl->getName());
770 else
771 printf(",0,0");
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000772 if (CDecl->getNumIntfRefProtocols() > 0)
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000773 printf(", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_%s, 0,0\n",
774 CDecl->getName());
775 else
776 printf(",0,0,0\n");
777 printf("};\n");
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +0000778}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000779
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000780void RewriteTest::WriteObjcMetaData() {
781 int ClsDefCount = ClassImplementation.size();
782 int CatDefCount = CategoryImplementation.size();
783 if (ClsDefCount == 0 && CatDefCount == 0)
784 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000785
Fariborz Jahanian454cb012007-10-24 20:54:23 +0000786 // TODO: This is temporary until we decide how to access objc types in a
787 // c program
788 printf("\n#include <Objc/objc.h>\n");
789
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000790 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000791 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000792 RewriteObjcClassMetaData(ClassImplementation[i]);
793
794 // For each implemented category, write out all its meta data.
795 for (int i = 0; i < CatDefCount; i++)
796 RewriteObjcCategoryImplDecl(CategoryImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000797
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000798 // Write objc_symtab metadata
799 /*
800 struct _objc_symtab
801 {
802 long sel_ref_cnt;
803 SEL *refs;
804 short cls_def_cnt;
805 short cat_def_cnt;
806 void *defs[cls_def_cnt + cat_def_cnt];
807 };
808 */
809
810 printf("\nstruct _objc_symtab {\n");
811 printf("\tlong sel_ref_cnt;\n");
812 printf("\tSEL *refs;\n");
813 printf("\tshort cls_def_cnt;\n");
814 printf("\tshort cat_def_cnt;\n");
815 printf("\tvoid *defs[%d];\n", ClsDefCount + CatDefCount);
816 printf("};\n\n");
817
818 printf("static struct _objc_symtab "
Chris Lattnerf04da132007-10-24 17:06:59 +0000819 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n");
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000820 printf("\t0, 0, %d, %d\n", ClsDefCount, CatDefCount);
821 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000822 printf("\t,&_OBJC_CLASS_%s\n", ClassImplementation[i]->getName());
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000823
824 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniandeef5182007-10-23 18:53:48 +0000825 printf("\t,&_OBJC_CATEGORY_%s_%s\n",
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000826 CategoryImplementation[i]->getClassInterface()->getName(),
827 CategoryImplementation[i]->getName());
828
829 printf("};\n\n");
830
831 // Write objc_module metadata
832
833 /*
834 struct _objc_module {
835 long version;
836 long size;
837 const char *name;
838 struct _objc_symtab *symtab;
839 }
840 */
841
842 printf("\nstruct _objc_module {\n");
843 printf("\tlong version;\n");
844 printf("\tlong size;\n");
845 printf("\tconst char *name;\n");
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000846 printf("\tstruct _objc_symtab *symtab;\n");
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000847 printf("};\n\n");
848 printf("static struct _objc_module "
849 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n");
Fariborz Jahanian1a0965e2007-10-24 21:25:12 +0000850 printf("\t%d, sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n", OBJC_ABI_VERSION);
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000851 printf("};\n\n");
852}
Chris Lattner311ff022007-10-16 22:36:42 +0000853