blob: 788b522612801da1f1de8d2c699412a729c328f0 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroffebf2b562007-10-23 23:50:29 +000036
37 FunctionDecl *MsgSendFunctionDecl;
38 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000039 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000040
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000041 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000042 public:
Chris Lattner01c57482007-10-17 22:35:30 +000043 void Initialize(ASTContext &context, unsigned mainFileID) {
44 Context = &context;
45 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000046 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000047 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000048 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000049 SelGetUidFunctionDecl = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000050 Rewrite.setSourceMgr(Context->SourceMgr);
Chris Lattner77cd2a02007-10-11 00:43:27 +000051 }
Chris Lattner8a12c272007-10-11 18:38:32 +000052
Chris Lattnerf04da132007-10-24 17:06:59 +000053 // Top Level Driver code.
54 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000055 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000056 ~RewriteTest();
57
58 // Syntactic Rewriting.
Chris Lattner2c64b7b2007-10-16 21:07:07 +000059 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000060 void RewriteTabs();
61 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000062 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000063 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000064 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000065 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff09b266e2007-10-30 23:14:51 +000066 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroff9165ad32007-10-31 04:38:33 +000067 bool functionReferencesAnyObjcQualifiedInterfaceTypes(
68 const FunctionTypeProto *proto);
Chris Lattner311ff022007-10-16 22:36:42 +000069
Chris Lattnerf04da132007-10-24 17:06:59 +000070 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000071 Stmt *RewriteFunctionBody(Stmt *S);
72 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
73 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000074 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
75 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000076 void SynthMsgSendFunctionDecl();
77 void SynthGetClassFunctionDecl();
78
Chris Lattnerf04da132007-10-24 17:06:59 +000079 // Metadata emission.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000080 void HandleObjcMetaDataEmission();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000081 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
82 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000083
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000084 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
85 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000086
87 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
88 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +000089 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000090 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +000091 const char *ClassName,
92 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000093
94 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
95 int NumProtocols,
96 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000097 const char *ClassName,
98 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000099 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
100 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000101 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
102 ObjcIvarDecl *ivar,
103 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000104 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000105 };
106}
107
Chris Lattner8a12c272007-10-11 18:38:32 +0000108ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000109
Chris Lattnerf04da132007-10-24 17:06:59 +0000110//===----------------------------------------------------------------------===//
111// Top Level Driver Code
112//===----------------------------------------------------------------------===//
113
Chris Lattner8a12c272007-10-11 18:38:32 +0000114void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000115 // Two cases: either the decl could be in the main file, or it could be in a
116 // #included file. If the former, rewrite it now. If the later, check to see
117 // if we rewrote the #include/#import.
118 SourceLocation Loc = D->getLocation();
119 Loc = SM->getLogicalLoc(Loc);
120
121 // If this is for a builtin, ignore it.
122 if (Loc.isInvalid()) return;
123
Steve Naroffebf2b562007-10-23 23:50:29 +0000124 // Look for built-in declarations that we need to refer during the rewrite.
125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000126 RewriteFunctionDecl(FD);
Steve Naroffbef11852007-10-26 20:53:56 +0000127 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
128 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000129 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
130 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000131 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
132 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000133 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000135 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
136 return HandleDeclInMainFile(D);
137
Chris Lattnerf04da132007-10-24 17:06:59 +0000138 // Otherwise, see if there is a #import in the main file that should be
139 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000140 RewriteInclude(Loc);
141}
142
Chris Lattnerf04da132007-10-24 17:06:59 +0000143/// HandleDeclInMainFile - This is called for each top-level decl defined in the
144/// main file of the input.
145void RewriteTest::HandleDeclInMainFile(Decl *D) {
146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
147 if (Stmt *Body = FD->getBody())
148 FD->setBody(RewriteFunctionBody(Body));
149
150 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
151 ClassImplementation.push_back(CI);
152 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
153 CategoryImplementation.push_back(CI);
154 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
155 RewriteForwardClassDecl(CD);
156 // Nothing yet.
157}
158
159RewriteTest::~RewriteTest() {
160 // Get the top-level buffer that this corresponds to.
161 RewriteTabs();
162
163 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
164 // we are done.
165 if (const RewriteBuffer *RewriteBuf =
166 Rewrite.getRewriteBufferFor(MainFileID)) {
167 printf("Changed:\n");
168 std::string S(RewriteBuf->begin(), RewriteBuf->end());
169 printf("%s\n", S.c_str());
170 } else {
171 printf("No changes\n");
172 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000173
174}
175
176/// HandleObjcMetaDataEmission - main routine to generate objective-c's
177/// metadata.
178void RewriteTest::HandleObjcMetaDataEmission() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000179 // Rewrite Objective-c meta data*
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000180 std::string ResultStr;
181 WriteObjcMetaData(ResultStr);
182 // For now just print the string out.
183 printf("%s", ResultStr.c_str());
Chris Lattnerf04da132007-10-24 17:06:59 +0000184}
185
186//===----------------------------------------------------------------------===//
187// Syntactic (non-AST) Rewriting Code
188//===----------------------------------------------------------------------===//
189
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000190void RewriteTest::RewriteInclude(SourceLocation Loc) {
191 // Rip up the #include stack to the main file.
192 SourceLocation IncLoc = Loc, NextLoc = Loc;
193 do {
194 IncLoc = Loc;
195 Loc = SM->getLogicalLoc(NextLoc);
196 NextLoc = SM->getIncludeLoc(Loc);
197 } while (!NextLoc.isInvalid());
198
199 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
200 // IncLoc indicates the header that was included if it is useful.
201 IncLoc = SM->getLogicalLoc(IncLoc);
202 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
203 Loc == LastIncLoc)
204 return;
205 LastIncLoc = Loc;
206
207 unsigned IncCol = SM->getColumnNumber(Loc);
208 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
209
210 // Replace the #import with #include.
211 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
212}
213
Chris Lattnerf04da132007-10-24 17:06:59 +0000214void RewriteTest::RewriteTabs() {
215 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
216 const char *MainBufStart = MainBuf.first;
217 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000218
Chris Lattnerf04da132007-10-24 17:06:59 +0000219 // Loop over the whole file, looking for tabs.
220 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
221 if (*BufPtr != '\t')
222 continue;
223
224 // Okay, we found a tab. This tab will turn into at least one character,
225 // but it depends on which 'virtual column' it is in. Compute that now.
226 unsigned VCol = 0;
227 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
228 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
229 ++VCol;
230
231 // Okay, now that we know the virtual column, we know how many spaces to
232 // insert. We assume 8-character tab-stops.
233 unsigned Spaces = 8-(VCol & 7);
234
235 // Get the location of the tab.
236 SourceLocation TabLoc =
237 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
238
239 // Rewrite the single tab character into a sequence of spaces.
240 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
241 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000242}
243
244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
246 int numDecls = ClassDecl->getNumForwardDecls();
247 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
248
249 // Get the start location and compute the semi location.
250 SourceLocation startLoc = ClassDecl->getLocation();
251 const char *startBuf = SM->getCharacterData(startLoc);
252 const char *semiPtr = strchr(startBuf, ';');
253
254 // Translate to typedef's that forward reference structs with the same name
255 // as the class. As a convenience, we include the original declaration
256 // as a comment.
257 std::string typedefString;
258 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000259 typedefString.append(startBuf, semiPtr-startBuf+1);
260 typedefString += "\n";
261 for (int i = 0; i < numDecls; i++) {
262 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
263 typedefString += "typedef struct ";
264 typedefString += ForwardDecl->getName();
265 typedefString += " ";
266 typedefString += ForwardDecl->getName();
267 typedefString += ";\n";
268 }
269
270 // Replace the @class with typedefs corresponding to the classes.
271 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
272 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000273}
274
Steve Naroff423cb562007-10-30 13:30:57 +0000275void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
276 for (int i = 0; i < nMethods; i++) {
277 ObjcMethodDecl *Method = Methods[i];
278 SourceLocation Loc = Method->getLocStart();
279
280 Rewrite.ReplaceText(Loc, 0, "// ", 3);
281
282 // FIXME: handle methods that are declared across multiple lines.
283 }
284}
285
286void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
287 SourceLocation LocStart = CatDecl->getLocStart();
288
289 // FIXME: handle category headers that are declared across multiple lines.
290 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
291
292 RewriteMethods(CatDecl->getNumInstanceMethods(),
293 CatDecl->getInstanceMethods());
294 RewriteMethods(CatDecl->getNumClassMethods(),
295 CatDecl->getClassMethods());
296 // Lastly, comment out the @end.
297 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
298}
299
Steve Naroff752d6ef2007-10-30 16:42:30 +0000300void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
301 SourceLocation LocStart = PDecl->getLocStart();
302
303 // FIXME: handle protocol headers that are declared across multiple lines.
304 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
305
306 RewriteMethods(PDecl->getNumInstanceMethods(),
307 PDecl->getInstanceMethods());
308 RewriteMethods(PDecl->getNumClassMethods(),
309 PDecl->getClassMethods());
310 // Lastly, comment out the @end.
311 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
312}
313
Steve Naroffbef11852007-10-26 20:53:56 +0000314void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000315
316 SourceLocation LocStart = ClassDecl->getLocStart();
317 SourceLocation LocEnd = ClassDecl->getLocEnd();
318
319 const char *startBuf = SM->getCharacterData(LocStart);
320 const char *endBuf = SM->getCharacterData(LocEnd);
321
Steve Naroff2feac5e2007-10-30 03:43:13 +0000322 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000323
324 std::string ResultStr;
325 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
326
Steve Naroff2feac5e2007-10-30 03:43:13 +0000327 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000328 ResultStr.c_str(), ResultStr.size());
329
Steve Naroff423cb562007-10-30 13:30:57 +0000330 RewriteMethods(ClassDecl->getNumInstanceMethods(),
331 ClassDecl->getInstanceMethods());
332 RewriteMethods(ClassDecl->getNumClassMethods(),
333 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000334
Steve Naroff2feac5e2007-10-30 03:43:13 +0000335 // Lastly, comment out the @end.
336 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000337}
338
Chris Lattnerf04da132007-10-24 17:06:59 +0000339//===----------------------------------------------------------------------===//
340// Function Body / Expression rewriting
341//===----------------------------------------------------------------------===//
342
Chris Lattnere64b7772007-10-24 16:57:36 +0000343Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000344 // Otherwise, just rewrite all children.
345 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
346 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000347 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000348 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000349
350 // Handle specific things.
351 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
352 return RewriteAtEncode(AtEncode);
353
Steve Naroff934f2762007-10-24 22:48:43 +0000354 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
355 // Before we rewrite it, put the original message expression in a comment.
356 SourceLocation startLoc = MessExpr->getLocStart();
357 SourceLocation endLoc = MessExpr->getLocEnd();
358
359 const char *startBuf = SM->getCharacterData(startLoc);
360 const char *endBuf = SM->getCharacterData(endLoc);
361
362 std::string messString;
363 messString += "// ";
364 messString.append(startBuf, endBuf-startBuf+1);
365 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000366
Steve Naroff934f2762007-10-24 22:48:43 +0000367 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
368 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
369 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000370 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000371 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000372 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000373 // Return this stmt unmodified.
374 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000375}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000376
Chris Lattnere64b7772007-10-24 16:57:36 +0000377Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000378 // Create a new string expression.
379 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000380 std::string StrEncoding;
381 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
382 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
383 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000384 SourceLocation(), SourceLocation());
385 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000386 delete Exp;
387 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000388}
389
Steve Naroff934f2762007-10-24 22:48:43 +0000390CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
391 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000392 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000393 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000394
395 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000396 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000397
398 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000399 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000400 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
401
402 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000403
Steve Naroff934f2762007-10-24 22:48:43 +0000404 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
405}
406
Steve Naroff9165ad32007-10-31 04:38:33 +0000407bool RewriteTest::functionReferencesAnyObjcQualifiedInterfaceTypes(
408 const FunctionTypeProto *proto) {
409 const PointerType *pType = proto->getResultType()->getAsPointerType();
410 if (pType) {
411 Type *pointeeType = pType->getPointeeType().getTypePtr();
412 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
413 return true; // we have "Class <Protocol> *".
414 }
415 // Now check arguments.
416 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
417 pType = proto->getArgType(i)->getAsPointerType();
418 if (pType) {
419 Type *pointeeType = pType->getPointeeType().getTypePtr();
420 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
421 return true;
422 }
423 }
424 // FIXME: we don't currently represent "id <Protocol>" in the type system.
425 return false;
426}
427
Steve Naroff09b266e2007-10-30 23:14:51 +0000428void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
429 // declared in <objc/objc.h>
Steve Naroff9165ad32007-10-31 04:38:33 +0000430 if (strcmp(FD->getName(), "sel_getUid") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000431 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000432 return;
433 }
434 // Check for ObjC 'id' and class types that have been adorned with protocol
435 // information (id<p>, C<p>*). The protocol references need to be rewritten!
436 const FunctionType *funcType = FD->getType()->getAsFunctionType();
437 assert(funcType && "missing function type");
438 const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType);
439 if (proto && functionReferencesAnyObjcQualifiedInterfaceTypes(proto)) {
440 // FIXME: Rewrite function decl...
441 }
Steve Naroff09b266e2007-10-30 23:14:51 +0000442}
443
444// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
445void RewriteTest::SynthMsgSendFunctionDecl() {
446 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
447 llvm::SmallVector<QualType, 16> ArgTys;
448 QualType argT = Context->getObjcIdType();
449 assert(!argT.isNull() && "Can't find 'id' type");
450 ArgTys.push_back(argT);
451 argT = Context->getObjcSelType();
452 assert(!argT.isNull() && "Can't find 'SEL' type");
453 ArgTys.push_back(argT);
454 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
455 &ArgTys[0], ArgTys.size(),
456 true /*isVariadic*/);
457 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
458 msgSendIdent, msgSendType,
459 FunctionDecl::Extern, false, 0);
460}
461
462// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
463void RewriteTest::SynthGetClassFunctionDecl() {
464 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
465 llvm::SmallVector<QualType, 16> ArgTys;
466 ArgTys.push_back(Context->getPointerType(
467 Context->CharTy.getQualifiedType(QualType::Const)));
468 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
469 &ArgTys[0], ArgTys.size(),
470 false /*isVariadic*/);
471 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
472 getClassIdent, getClassType,
473 FunctionDecl::Extern, false, 0);
474}
475
Steve Naroff934f2762007-10-24 22:48:43 +0000476Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff934f2762007-10-24 22:48:43 +0000477 assert(SelGetUidFunctionDecl && "Can't find sel_getUid() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000478 if (!MsgSendFunctionDecl)
479 SynthMsgSendFunctionDecl();
480 if (!GetClassFunctionDecl)
481 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000482
483 // Synthesize a call to objc_msgSend().
484 llvm::SmallVector<Expr*, 8> MsgExprs;
485 IdentifierInfo *clsName = Exp->getClassName();
486
487 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
488 if (clsName) { // class message.
489 llvm::SmallVector<Expr*, 8> ClsExprs;
490 QualType argType = Context->getPointerType(Context->CharTy);
491 ClsExprs.push_back(new StringLiteral(clsName->getName(),
492 clsName->getLength(),
493 false, argType, SourceLocation(),
494 SourceLocation()));
495 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
496 &ClsExprs[0], ClsExprs.size());
497 MsgExprs.push_back(Cls);
498 } else // instance message.
499 MsgExprs.push_back(Exp->getReceiver());
500
501 // Create a call to sel_getUid("selName"), it will be the 2nd argument.
502 llvm::SmallVector<Expr*, 8> SelExprs;
503 QualType argType = Context->getPointerType(Context->CharTy);
504 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
505 Exp->getSelector().getName().size(),
506 false, argType, SourceLocation(),
507 SourceLocation()));
508 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
509 &SelExprs[0], SelExprs.size());
510 MsgExprs.push_back(SelExp);
511
512 // Now push any user supplied arguments.
513 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
514 MsgExprs.push_back(Exp->getArg(i));
515 // We've transferred the ownership to MsgExprs. Null out the argument in
516 // the original expression, since we will delete it below.
517 Exp->setArg(i, 0);
518 }
519 CallExpr *MessExp = SynthesizeCallToFunctionDecl(MsgSendFunctionDecl,
520 &MsgExprs[0], MsgExprs.size());
521 // Now do the actual rewrite.
522 Rewrite.ReplaceStmt(Exp, MessExp);
523
Chris Lattnere64b7772007-10-24 16:57:36 +0000524 delete Exp;
Steve Naroff934f2762007-10-24 22:48:43 +0000525 return MessExp;
Steve Naroffebf2b562007-10-23 23:50:29 +0000526}
527
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000528/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
529/// an objective-c class with ivars.
530void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
531 std::string &Result) {
532 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
533 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
534 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
535 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
536 // Do it for the root
537 SynthesizeObjcInternalStruct(RCDecl, Result);
538 }
539
540 int NumIvars = CDecl->getIntfDeclNumIvars();
541 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
542 return;
543
544 Result += "\nstruct _interface_";
545 Result += CDecl->getName();
546 Result += " {\n";
547 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
548 Result += "\tstruct _interface_";
549 Result += RCDecl->getName();
550 Result += " _";
551 Result += RCDecl->getName();
552 Result += ";\n";
553 }
554
555 ObjcIvarDecl **Ivars = CDecl->getIntfDeclIvars();
556 for (int i = 0; i < NumIvars; i++) {
557 Result += "\t";
558 std::string Name = Ivars[i]->getName();
559 Ivars[i]->getType().getAsStringInternal(Name);
560 Result += Name;
561 Result += ";\n";
562 }
563 Result += "};\n";
564 // Mark this struct as having been generated.
565 if (!ObjcSynthesizedStructs.insert(CDecl))
566 assert(true && "struct already synthesize- SynthesizeObjcInternalStruct");
567}
568
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000569// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
570/// class methods.
571void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
572 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000573 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000574 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000575 const char *ClassName,
576 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000577 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000578 if (NumMethods > 0 && !objc_impl_method) {
579 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000580 SEL _cmd;
581 char *method_types;
582 void *_imp;
583 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000584 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000585 Result += "\nstruct _objc_method {\n";
586 Result += "\tSEL _cmd;\n";
587 Result += "\tchar *method_types;\n";
588 Result += "\tvoid *_imp;\n";
589 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000590
591 /* struct _objc_method_list {
592 struct _objc_method_list *next_method;
593 int method_count;
594 struct _objc_method method_list[];
595 }
596 */
597 Result += "\nstruct _objc_method_list {\n";
598 Result += "\tstruct _objc_method_list *next_method;\n";
599 Result += "\tint method_count;\n";
600 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000601 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000602 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000603 // Build _objc_method_list for class's methods if needed
604 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000605 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000606 Result += prefix;
607 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
608 Result += "_METHODS_";
609 Result += ClassName;
610 Result += " __attribute__ ((section (\"__OBJC, __";
611 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000612 Result += "_meth\")))= ";
613 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
614
615 Result += "\t,{{(SEL)\"";
616 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000617 std::string MethodTypeString;
618 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
619 Result += "\", \"";
620 Result += MethodTypeString;
621 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000622 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000623 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000624 Result += "\t ,{(SEL)\"";
625 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000626 std::string MethodTypeString;
627 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
628 Result += "\", \"";
629 Result += MethodTypeString;
630 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000631 }
632 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000633 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000634}
635
636/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
637void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
638 int NumProtocols,
639 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000640 const char *ClassName,
641 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000642 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000643 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000644 for (int i = 0; i < NumProtocols; i++) {
645 ObjcProtocolDecl *PDecl = Protocols[i];
646 // Output struct protocol_methods holder of method selector and type.
647 if (!objc_protocol_methods &&
648 (PDecl->getNumInstanceMethods() > 0
649 || PDecl->getNumClassMethods() > 0)) {
650 /* struct protocol_methods {
651 SEL _cmd;
652 char *method_types;
653 }
654 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000655 Result += "\nstruct protocol_methods {\n";
656 Result += "\tSEL _cmd;\n";
657 Result += "\tchar *method_types;\n";
658 Result += "};\n";
659
660 /* struct _objc_protocol_method_list {
661 int protocol_method_count;
662 struct protocol_methods protocols[];
663 }
664 */
665 Result += "\nstruct _objc_protocol_method_list {\n";
666 Result += "\tint protocol_method_count;\n";
667 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000668 objc_protocol_methods = true;
669 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000670
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000671 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000672 int NumMethods = PDecl->getNumInstanceMethods();
673 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000674 Result += "\nstatic struct _objc_protocol_method_list "
675 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
676 Result += PDecl->getName();
677 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
678 "{\n\t" + utostr(NumMethods) + "\n";
679
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000680 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000681 Result += "\t,{{(SEL)\"";
682 Result += Methods[0]->getSelector().getName().c_str();
683 Result += "\", \"\"}\n";
684
685 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000686 Result += "\t ,{(SEL)\"";
687 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000688 std::string MethodTypeString;
689 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
690 Result += "\", \"";
691 Result += MethodTypeString;
692 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000693 }
694 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000695 }
696
697 // Output class methods declared in this protocol.
698 NumMethods = PDecl->getNumClassMethods();
699 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000700 Result += "\nstatic struct _objc_protocol_method_list "
701 "_OBJC_PROTOCOL_CLASS_METHODS_";
702 Result += PDecl->getName();
703 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
704 "{\n\t";
705 Result += utostr(NumMethods);
706 Result += "\n";
707
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000708 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000709 Result += "\t,{{(SEL)\"";
710 Result += Methods[0]->getSelector().getName().c_str();
711 Result += "\", \"\"}\n";
712
713 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000714 Result += "\t ,{(SEL)\"";
715 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000716 std::string MethodTypeString;
717 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
718 Result += "\", \"";
719 Result += MethodTypeString;
720 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000721 }
722 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000723 }
724 // Output:
725 /* struct _objc_protocol {
726 // Objective-C 1.0 extensions
727 struct _objc_protocol_extension *isa;
728 char *protocol_name;
729 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000730 struct _objc_protocol_method_list *instance_methods;
731 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000732 };
733 */
734 static bool objc_protocol = false;
735 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000736 Result += "\nstruct _objc_protocol {\n";
737 Result += "\tstruct _objc_protocol_extension *isa;\n";
738 Result += "\tchar *protocol_name;\n";
739 Result += "\tstruct _objc_protocol **protocol_list;\n";
740 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
741 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
742 Result += "};\n";
743
744 /* struct _objc_protocol_list {
745 struct _objc_protocol_list *next;
746 int protocol_count;
747 struct _objc_protocol *class_protocols[];
748 }
749 */
750 Result += "\nstruct _objc_protocol_list {\n";
751 Result += "\tstruct _objc_protocol_list *next;\n";
752 Result += "\tint protocol_count;\n";
753 Result += "\tstruct _objc_protocol *class_protocols[];\n";
754 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000755 objc_protocol = true;
756 }
757
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000758 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
759 Result += PDecl->getName();
760 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
761 "{\n\t0, \"";
762 Result += PDecl->getName();
763 Result += "\", 0, ";
764 if (PDecl->getInstanceMethods() > 0) {
765 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
766 Result += PDecl->getName();
767 Result += ", ";
768 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000769 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000770 Result += "0, ";
771 if (PDecl->getClassMethods() > 0) {
772 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
773 Result += PDecl->getName();
774 Result += "\n";
775 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000776 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000777 Result += "0\n";
778 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000779 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000780 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000781 Result += "\nstatic struct _objc_protocol_list _OBJC_";
782 Result += prefix;
783 Result += "_PROTOCOLS_";
784 Result += ClassName;
785 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
786 "{\n\t0, ";
787 Result += utostr(NumProtocols);
788 Result += "\n";
789
790 Result += "\t,{&_OBJC_PROTOCOL_";
791 Result += Protocols[0]->getName();
792 Result += " \n";
793
794 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000795 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000796 Result += "\t ,&_OBJC_PROTOCOL_";
797 Result += PDecl->getName();
798 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000799 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000800 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000801 }
802}
803
804/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
805/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000806void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
807 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000808 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
809 // Find category declaration for this implementation.
810 ObjcCategoryDecl *CDecl;
811 for (CDecl = ClassDecl->getCategoryList(); CDecl;
812 CDecl = CDecl->getNextClassCategory())
813 if (CDecl->getIdentifier() == IDecl->getIdentifier())
814 break;
815 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
816
817 char *FullCategoryName = (char*)alloca(
818 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
819 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
820
821 // Build _objc_method_list for class's instance methods if needed
822 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
823 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000824 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000825 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000826
827 // Build _objc_method_list for class's class methods if needed
828 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
829 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000830 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000831 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000832
833 // Protocols referenced in class declaration?
834 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
835 CDecl->getNumReferencedProtocols(),
836 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000837 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000838
839 /* struct _objc_category {
840 char *category_name;
841 char *class_name;
842 struct _objc_method_list *instance_methods;
843 struct _objc_method_list *class_methods;
844 struct _objc_protocol_list *protocols;
845 // Objective-C 1.0 extensions
846 uint32_t size; // sizeof (struct _objc_category)
847 struct _objc_property_list *instance_properties; // category's own
848 // @property decl.
849 };
850 */
851
852 static bool objc_category = false;
853 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000854 Result += "\nstruct _objc_category {\n";
855 Result += "\tchar *category_name;\n";
856 Result += "\tchar *class_name;\n";
857 Result += "\tstruct _objc_method_list *instance_methods;\n";
858 Result += "\tstruct _objc_method_list *class_methods;\n";
859 Result += "\tstruct _objc_protocol_list *protocols;\n";
860 Result += "\tunsigned int size;\n";
861 Result += "\tstruct _objc_property_list *instance_properties;\n";
862 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000863 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000864 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000865 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
866 Result += FullCategoryName;
867 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
868 Result += IDecl->getName();
869 Result += "\"\n\t, \"";
870 Result += ClassDecl->getName();
871 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000872
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000873 if (IDecl->getNumInstanceMethods() > 0) {
874 Result += "\t, (struct _objc_method_list *)"
875 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
876 Result += FullCategoryName;
877 Result += "\n";
878 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000879 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000880 Result += "\t, 0\n";
881 if (IDecl->getNumClassMethods() > 0) {
882 Result += "\t, (struct _objc_method_list *)"
883 "&_OBJC_CATEGORY_CLASS_METHODS_";
884 Result += FullCategoryName;
885 Result += "\n";
886 }
887 else
888 Result += "\t, 0\n";
889
890 if (CDecl->getNumReferencedProtocols() > 0) {
891 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
892 Result += FullCategoryName;
893 Result += "\n";
894 }
895 else
896 Result += "\t, 0\n";
897 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000898}
899
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000900/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
901/// ivar offset.
902void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
903 ObjcIvarDecl *ivar,
904 std::string &Result) {
905 Result += "offsetof(struct _interface_";
906 Result += IDecl->getName();
907 Result += ", ";
908 Result += ivar->getName();
909 Result += ")";
910}
911
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000912//===----------------------------------------------------------------------===//
913// Meta Data Emission
914//===----------------------------------------------------------------------===//
915
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000916void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
917 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000918 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
919
920 // Build _objc_ivar_list metadata for classes ivars if needed
921 int NumIvars = IDecl->getImplDeclNumIvars() > 0
922 ? IDecl->getImplDeclNumIvars()
923 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
924
Fariborz Jahanian4d733d32007-10-26 23:09:28 +0000925 SynthesizeObjcInternalStruct(CDecl, Result);
926
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000927 if (NumIvars > 0) {
928 static bool objc_ivar = false;
929 if (!objc_ivar) {
930 /* struct _objc_ivar {
931 char *ivar_name;
932 char *ivar_type;
933 int ivar_offset;
934 };
935 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000936 Result += "\nstruct _objc_ivar {\n";
937 Result += "\tchar *ivar_name;\n";
938 Result += "\tchar *ivar_type;\n";
939 Result += "\tint ivar_offset;\n";
940 Result += "};\n";
941
942 /* struct _objc_ivar_list {
943 int ivar_count;
944 struct _objc_ivar ivar_list[];
945 };
946 */
947 Result += "\nstruct _objc_ivar_list {\n";
948 Result += "\tint ivar_count;\n";
949 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000950 objc_ivar = true;
951 }
952
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000953 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
954 Result += IDecl->getName();
955 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
956 "{\n\t";
957 Result += utostr(NumIvars);
958 Result += "\n";
959
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000960 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
961 ? IDecl->getImplDeclIVars()
962 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000963 Result += "\t,{{\"";
964 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +0000965 Result += "\", \"";
966 std::string StrEncoding;
967 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
968 Result += StrEncoding;
969 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000970 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
971 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000972 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000973 Result += "\t ,{\"";
974 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +0000975 Result += "\", \"";
976 std::string StrEncoding;
977 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
978 Result += StrEncoding;
979 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000980 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
981 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000982 }
983
984 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000985 }
986
987 // Build _objc_method_list for class's instance methods if needed
988 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
989 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000990 true,
991 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000992
993 // Build _objc_method_list for class's class methods if needed
994 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000995 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000996 false,
997 "", IDecl->getName(), Result);
998
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000999 // Protocols referenced in class declaration?
1000 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1001 CDecl->getNumIntfRefProtocols(),
1002 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001003 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001004
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001005
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001006 // Declaration of class/meta-class metadata
1007 /* struct _objc_class {
1008 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001009 const char *super_class_name;
1010 char *name;
1011 long version;
1012 long info;
1013 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001014 struct _objc_ivar_list *ivars;
1015 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001016 struct objc_cache *cache;
1017 struct objc_protocol_list *protocols;
1018 const char *ivar_layout;
1019 struct _objc_class_ext *ext;
1020 };
1021 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001022 static bool objc_class = false;
1023 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001024 Result += "\nstruct _objc_class {\n";
1025 Result += "\tstruct _objc_class *isa;\n";
1026 Result += "\tconst char *super_class_name;\n";
1027 Result += "\tchar *name;\n";
1028 Result += "\tlong version;\n";
1029 Result += "\tlong info;\n";
1030 Result += "\tlong instance_size;\n";
1031 Result += "\tstruct _objc_ivar_list *ivars;\n";
1032 Result += "\tstruct _objc_method_list *methods;\n";
1033 Result += "\tstruct objc_cache *cache;\n";
1034 Result += "\tstruct _objc_protocol_list *protocols;\n";
1035 Result += "\tconst char *ivar_layout;\n";
1036 Result += "\tstruct _objc_class_ext *ext;\n";
1037 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001038 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001039 }
1040
1041 // Meta-class metadata generation.
1042 ObjcInterfaceDecl *RootClass = 0;
1043 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1044 while (SuperClass) {
1045 RootClass = SuperClass;
1046 SuperClass = SuperClass->getSuperClass();
1047 }
1048 SuperClass = CDecl->getSuperClass();
1049
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001050 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1051 Result += CDecl->getName();
1052 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1053 "{\n\t(struct _objc_class *)\"";
1054 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1055 Result += "\"";
1056
1057 if (SuperClass) {
1058 Result += ", \"";
1059 Result += SuperClass->getName();
1060 Result += "\", \"";
1061 Result += CDecl->getName();
1062 Result += "\"";
1063 }
1064 else {
1065 Result += ", 0, \"";
1066 Result += CDecl->getName();
1067 Result += "\"";
1068 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001069 // TODO: 'ivars' field for root class is currently set to 0.
1070 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001071 Result += ", 0,2, sizeof(struct _objc_class), 0";
1072 if (CDecl->getNumClassMethods() > 0) {
1073 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1074 Result += CDecl->getName();
1075 Result += "\n";
1076 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001077 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001078 Result += ", 0\n";
1079 if (CDecl->getNumIntfRefProtocols() > 0) {
1080 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1081 Result += CDecl->getName();
1082 Result += ",0,0\n";
1083 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001085 Result += "\t,0,0,0,0\n";
1086 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001087
1088 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001089 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1090 Result += CDecl->getName();
1091 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1092 "{\n\t&_OBJC_METACLASS_";
1093 Result += CDecl->getName();
1094 if (SuperClass) {
1095 Result += ", \"";
1096 Result += SuperClass->getName();
1097 Result += "\", \"";
1098 Result += CDecl->getName();
1099 Result += "\"";
1100 }
1101 else {
1102 Result += ", 0, \"";
1103 Result += CDecl->getName();
1104 Result += "\"";
1105 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001106 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001107 Result += ", 0,1";
1108 if (!ObjcSynthesizedStructs.count(CDecl))
1109 Result += ",0";
1110 else {
1111 // class has size. Must synthesize its size.
1112 Result += ",sizeof(struct _interface_";
1113 Result += CDecl->getName();
1114 Result += ")";
1115 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001116 if (NumIvars > 0) {
1117 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1118 Result += CDecl->getName();
1119 Result += "\n\t";
1120 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001121 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001122 Result += ",0";
1123 if (IDecl->getNumInstanceMethods() > 0) {
1124 Result += ", &_OBJC_INSTANCE_METHODS_";
1125 Result += CDecl->getName();
1126 Result += ", 0\n\t";
1127 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001128 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001129 Result += ",0,0";
1130 if (CDecl->getNumIntfRefProtocols() > 0) {
1131 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1132 Result += CDecl->getName();
1133 Result += ", 0,0\n";
1134 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001135 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001136 Result += ",0,0,0\n";
1137 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001138}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001140void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001141 int ClsDefCount = ClassImplementation.size();
1142 int CatDefCount = CategoryImplementation.size();
1143 if (ClsDefCount == 0 && CatDefCount == 0)
1144 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001145
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001146 // TODO: This is temporary until we decide how to access objc types in a
1147 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001148 Result += "#include <Objc/objc.h>\n";
1149 // This is needed for use of offsetof
1150 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001151
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001152 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001153 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001154 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001155
1156 // For each implemented category, write out all its meta data.
1157 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001158 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001159
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001160 // Write objc_symtab metadata
1161 /*
1162 struct _objc_symtab
1163 {
1164 long sel_ref_cnt;
1165 SEL *refs;
1166 short cls_def_cnt;
1167 short cat_def_cnt;
1168 void *defs[cls_def_cnt + cat_def_cnt];
1169 };
1170 */
1171
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001172 Result += "\nstruct _objc_symtab {\n";
1173 Result += "\tlong sel_ref_cnt;\n";
1174 Result += "\tSEL *refs;\n";
1175 Result += "\tshort cls_def_cnt;\n";
1176 Result += "\tshort cat_def_cnt;\n";
1177 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1178 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001179
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001180 Result += "static struct _objc_symtab "
1181 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1182 Result += "\t0, 0, " + utostr(ClsDefCount)
1183 + ", " + utostr(CatDefCount) + "\n";
1184 for (int i = 0; i < ClsDefCount; i++) {
1185 Result += "\t,&_OBJC_CLASS_";
1186 Result += ClassImplementation[i]->getName();
1187 Result += "\n";
1188 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001189
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001190 for (int i = 0; i < CatDefCount; i++) {
1191 Result += "\t,&_OBJC_CATEGORY_";
1192 Result += CategoryImplementation[i]->getClassInterface()->getName();
1193 Result += "_";
1194 Result += CategoryImplementation[i]->getName();
1195 Result += "\n";
1196 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001197
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001198 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001199
1200 // Write objc_module metadata
1201
1202 /*
1203 struct _objc_module {
1204 long version;
1205 long size;
1206 const char *name;
1207 struct _objc_symtab *symtab;
1208 }
1209 */
1210
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001211 Result += "\nstruct _objc_module {\n";
1212 Result += "\tlong version;\n";
1213 Result += "\tlong size;\n";
1214 Result += "\tconst char *name;\n";
1215 Result += "\tstruct _objc_symtab *symtab;\n";
1216 Result += "};\n\n";
1217 Result += "static struct _objc_module "
1218 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001219 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1220 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001221 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001222}
Chris Lattner311ff022007-10-16 22:36:42 +00001223