blob: b985e03cb5cbd9e4e023a14c0442827e878b50db [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 Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000041 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000042
Steve Naroffbeaf2992007-11-03 11:27:19 +000043 // ObjC string constant support.
44 FileVarDecl *ConstantStringClassReference;
45 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000046
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000047 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 public:
Chris Lattner01c57482007-10-17 22:35:30 +000049 void Initialize(ASTContext &context, unsigned mainFileID) {
50 Context = &context;
51 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000052 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000053 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000054 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000055 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000056 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 ConstantStringClassReference = 0;
58 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000059 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000060 // declaring objc_selector outside the parameter list removes a silly
61 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000062 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000063 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000064 "(struct objc_object *, struct objc_selector *, ...);\n"
65 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000066 "(const char *);\n"
67 "extern void objc_exception_throw(struct objc_object *);\n"
68 "extern void objc_exception_try_enter(void *);\n"
69 "extern void objc_exception_try_exit(void *);\n"
70 "extern struct objc_object *objc_exception_extract(void *);\n"
71 "extern int objc_exception_match"
72 "(struct objc_class *, struct objc_object *, ...);\n";
73
Steve Naroffab972d32007-11-04 22:37:50 +000074 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
75 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000076 }
Chris Lattner8a12c272007-10-11 18:38:32 +000077
Chris Lattnerf04da132007-10-24 17:06:59 +000078 // Top Level Driver code.
79 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000080 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000081 ~RewriteTest();
82
83 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000084 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000085 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000086 void RewriteTabs();
87 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000088 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000089 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000090 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000091 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000092 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000093 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000094 void RewriteObjcQualifiedInterfaceTypes(
95 const FunctionTypeProto *proto, FunctionDecl *FD);
96 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000097
Chris Lattnerf04da132007-10-24 17:06:59 +000098 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000099 Stmt *RewriteFunctionBody(Stmt *S);
100 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000101 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000102 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000103 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000104 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
105 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
106 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000107 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000108 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
109 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000110 void SynthMsgSendFunctionDecl();
111 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000112 void SynthCFStringFunctionDecl();
113
Chris Lattnerf04da132007-10-24 17:06:59 +0000114 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000115 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
116 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000117
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000118 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
119 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000120
121 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
122 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000123 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000125 const char *ClassName,
126 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000127
128 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
129 int NumProtocols,
130 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000131 const char *ClassName,
132 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000133 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
134 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000135 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
136 ObjcIvarDecl *ivar,
137 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000138 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000139 };
140}
141
Chris Lattner8a12c272007-10-11 18:38:32 +0000142ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144//===----------------------------------------------------------------------===//
145// Top Level Driver Code
146//===----------------------------------------------------------------------===//
147
Chris Lattner8a12c272007-10-11 18:38:32 +0000148void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000149 // Two cases: either the decl could be in the main file, or it could be in a
150 // #included file. If the former, rewrite it now. If the later, check to see
151 // if we rewrote the #include/#import.
152 SourceLocation Loc = D->getLocation();
153 Loc = SM->getLogicalLoc(Loc);
154
155 // If this is for a builtin, ignore it.
156 if (Loc.isInvalid()) return;
157
Steve Naroffebf2b562007-10-23 23:50:29 +0000158 // Look for built-in declarations that we need to refer during the rewrite.
159 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000160 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
162 // declared in <Foundation/NSString.h>
163 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
164 ConstantStringClassReference = FVD;
165 return;
166 }
Steve Naroffbef11852007-10-26 20:53:56 +0000167 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
168 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000169 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
170 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000171 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
172 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000173 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000174 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000175 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
176 return HandleDeclInMainFile(D);
177
Chris Lattnerf04da132007-10-24 17:06:59 +0000178 // Otherwise, see if there is a #import in the main file that should be
179 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000180 RewriteInclude(Loc);
181}
182
Chris Lattnerf04da132007-10-24 17:06:59 +0000183/// HandleDeclInMainFile - This is called for each top-level decl defined in the
184/// main file of the input.
185void RewriteTest::HandleDeclInMainFile(Decl *D) {
186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
187 if (Stmt *Body = FD->getBody())
188 FD->setBody(RewriteFunctionBody(Body));
189
190 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
191 ClassImplementation.push_back(CI);
192 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
193 CategoryImplementation.push_back(CI);
194 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
195 RewriteForwardClassDecl(CD);
196 // Nothing yet.
197}
198
199RewriteTest::~RewriteTest() {
200 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000201
202 // Rewrite tabs if we care.
203 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000204
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000205 // Rewrite Objective-c meta data*
206 std::string ResultStr;
207 WriteObjcMetaData(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000208
Chris Lattnerf04da132007-10-24 17:06:59 +0000209 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
210 // we are done.
211 if (const RewriteBuffer *RewriteBuf =
212 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000213 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000214 std::string S(RewriteBuf->begin(), RewriteBuf->end());
215 printf("%s\n", S.c_str());
216 } else {
217 printf("No changes\n");
218 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000219 // Emit metadata.
220 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000221}
222
Chris Lattnerf04da132007-10-24 17:06:59 +0000223//===----------------------------------------------------------------------===//
224// Syntactic (non-AST) Rewriting Code
225//===----------------------------------------------------------------------===//
226
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000227void RewriteTest::RewriteInclude(SourceLocation Loc) {
228 // Rip up the #include stack to the main file.
229 SourceLocation IncLoc = Loc, NextLoc = Loc;
230 do {
231 IncLoc = Loc;
232 Loc = SM->getLogicalLoc(NextLoc);
233 NextLoc = SM->getIncludeLoc(Loc);
234 } while (!NextLoc.isInvalid());
235
236 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
237 // IncLoc indicates the header that was included if it is useful.
238 IncLoc = SM->getLogicalLoc(IncLoc);
239 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
240 Loc == LastIncLoc)
241 return;
242 LastIncLoc = Loc;
243
244 unsigned IncCol = SM->getColumnNumber(Loc);
245 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
246
247 // Replace the #import with #include.
248 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
249}
250
Chris Lattnerf04da132007-10-24 17:06:59 +0000251void RewriteTest::RewriteTabs() {
252 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
253 const char *MainBufStart = MainBuf.first;
254 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000255
Chris Lattnerf04da132007-10-24 17:06:59 +0000256 // Loop over the whole file, looking for tabs.
257 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
258 if (*BufPtr != '\t')
259 continue;
260
261 // Okay, we found a tab. This tab will turn into at least one character,
262 // but it depends on which 'virtual column' it is in. Compute that now.
263 unsigned VCol = 0;
264 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
265 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
266 ++VCol;
267
268 // Okay, now that we know the virtual column, we know how many spaces to
269 // insert. We assume 8-character tab-stops.
270 unsigned Spaces = 8-(VCol & 7);
271
272 // Get the location of the tab.
273 SourceLocation TabLoc =
274 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
275
276 // Rewrite the single tab character into a sequence of spaces.
277 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
278 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000279}
280
281
Chris Lattnerf04da132007-10-24 17:06:59 +0000282void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
283 int numDecls = ClassDecl->getNumForwardDecls();
284 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
285
286 // Get the start location and compute the semi location.
287 SourceLocation startLoc = ClassDecl->getLocation();
288 const char *startBuf = SM->getCharacterData(startLoc);
289 const char *semiPtr = strchr(startBuf, ';');
290
291 // Translate to typedef's that forward reference structs with the same name
292 // as the class. As a convenience, we include the original declaration
293 // as a comment.
294 std::string typedefString;
295 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000296 typedefString.append(startBuf, semiPtr-startBuf+1);
297 typedefString += "\n";
298 for (int i = 0; i < numDecls; i++) {
299 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000300 if (ObjcForwardDecls.count(ForwardDecl))
301 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000302 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000303 typedefString += ForwardDecl->getName();
304 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000305
306 // Mark this typedef as having been generated.
307 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000308 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000309 }
310
311 // Replace the @class with typedefs corresponding to the classes.
312 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
313 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000314}
315
Steve Naroff423cb562007-10-30 13:30:57 +0000316void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
317 for (int i = 0; i < nMethods; i++) {
318 ObjcMethodDecl *Method = Methods[i];
319 SourceLocation Loc = Method->getLocStart();
320
Chris Lattner28d1fe82007-11-08 04:41:51 +0000321 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000322
323 // FIXME: handle methods that are declared across multiple lines.
324 }
325}
326
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000327void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
328{
329 for (int i = 0; i < nProperties; i++) {
330 ObjcPropertyDecl *Property = Properties[i];
331 SourceLocation Loc = Property->getLocation();
332
333 Rewrite.ReplaceText(Loc, 0, "// ", 3);
334
335 // FIXME: handle properties that are declared across multiple lines.
336 }
337}
338
Steve Naroff423cb562007-10-30 13:30:57 +0000339void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
340 SourceLocation LocStart = CatDecl->getLocStart();
341
342 // FIXME: handle category headers that are declared across multiple lines.
343 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
344
345 RewriteMethods(CatDecl->getNumInstanceMethods(),
346 CatDecl->getInstanceMethods());
347 RewriteMethods(CatDecl->getNumClassMethods(),
348 CatDecl->getClassMethods());
349 // Lastly, comment out the @end.
350 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
351}
352
Steve Naroff752d6ef2007-10-30 16:42:30 +0000353void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
354 SourceLocation LocStart = PDecl->getLocStart();
355
356 // FIXME: handle protocol headers that are declared across multiple lines.
357 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
358
359 RewriteMethods(PDecl->getNumInstanceMethods(),
360 PDecl->getInstanceMethods());
361 RewriteMethods(PDecl->getNumClassMethods(),
362 PDecl->getClassMethods());
363 // Lastly, comment out the @end.
364 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
365}
366
Steve Naroffbef11852007-10-26 20:53:56 +0000367void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000368
369 SourceLocation LocStart = ClassDecl->getLocStart();
370 SourceLocation LocEnd = ClassDecl->getLocEnd();
371
372 const char *startBuf = SM->getCharacterData(LocStart);
373 const char *endBuf = SM->getCharacterData(LocEnd);
374
Steve Naroff2feac5e2007-10-30 03:43:13 +0000375 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000376
377 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000378 if (!ObjcForwardDecls.count(ClassDecl)) {
379 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000380 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000381 ResultStr += ClassDecl->getName();
382 ResultStr += ";";
383
384 // Mark this typedef as having been generated.
385 ObjcForwardDecls.insert(ClassDecl);
386 }
Steve Narofff908a872007-10-30 02:23:23 +0000387 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
388
Steve Naroff2feac5e2007-10-30 03:43:13 +0000389 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000390 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000391 RewriteProperties(ClassDecl->getNumPropertyDecl(),
392 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000393 RewriteMethods(ClassDecl->getNumInstanceMethods(),
394 ClassDecl->getInstanceMethods());
395 RewriteMethods(ClassDecl->getNumClassMethods(),
396 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000397
Steve Naroff2feac5e2007-10-30 03:43:13 +0000398 // Lastly, comment out the @end.
399 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000400}
401
Chris Lattnerf04da132007-10-24 17:06:59 +0000402//===----------------------------------------------------------------------===//
403// Function Body / Expression rewriting
404//===----------------------------------------------------------------------===//
405
Chris Lattnere64b7772007-10-24 16:57:36 +0000406Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000407 // Otherwise, just rewrite all children.
408 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
409 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000410 if (*CI) {
411 Stmt *newStmt = RewriteFunctionBody(*CI);
412 if (newStmt)
413 *CI = newStmt;
414 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000415
416 // Handle specific things.
417 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
418 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000419
420 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
421 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000422
423 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
424 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000425
Steve Naroff934f2762007-10-24 22:48:43 +0000426 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
427 // Before we rewrite it, put the original message expression in a comment.
428 SourceLocation startLoc = MessExpr->getLocStart();
429 SourceLocation endLoc = MessExpr->getLocEnd();
430
431 const char *startBuf = SM->getCharacterData(startLoc);
432 const char *endBuf = SM->getCharacterData(endLoc);
433
434 std::string messString;
435 messString += "// ";
436 messString.append(startBuf, endBuf-startBuf+1);
437 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000438
Steve Naroff934f2762007-10-24 22:48:43 +0000439 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
440 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
441 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000442 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000443 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000444 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000445
446 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
447 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000448
449 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
450 return RewriteObjcThrowStmt(StmtThrow);
451
Chris Lattnere64b7772007-10-24 16:57:36 +0000452 // Return this stmt unmodified.
453 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000454}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000455
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000456Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000457 // Get the start location and compute the semi location.
458 SourceLocation startLoc = S->getLocStart();
459 const char *startBuf = SM->getCharacterData(startLoc);
460
461 assert((*startBuf == '@') && "bogus @try location");
462
463 std::string buf;
464 // declare a new scope with two variables, _stack and _rethrow.
465 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
466 buf += "int buf[18/*32-bit i386*/];\n";
467 buf += "char *pointers[4];} _stack;\n";
468 buf += "id volatile _rethrow = 0;\n";
469 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000470 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000471
472 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
473
474 startLoc = S->getTryBody()->getLocEnd();
475 startBuf = SM->getCharacterData(startLoc);
476
477 assert((*startBuf == '}') && "bogus @try block");
478
479 SourceLocation lastCurlyLoc = startLoc;
480
481 startLoc = startLoc.getFileLocWithOffset(1);
482 buf = " /* @catch begin */ else {\n";
483 buf += " id _caught = objc_exception_extract(&_stack);\n";
484 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000485 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000486 buf += " _rethrow = objc_exception_extract(&_stack);\n";
487 buf += " else { /* @catch continue */";
488
Chris Lattner28d1fe82007-11-08 04:41:51 +0000489 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000490
491 bool sawIdTypedCatch = false;
492 Stmt *lastCatchBody = 0;
493 ObjcAtCatchStmt *catchList = S->getCatchStmts();
494 while (catchList) {
495 Stmt *catchStmt = catchList->getCatchParamStmt();
496
497 if (catchList == S->getCatchStmts())
498 buf = "if ("; // we are generating code for the first catch clause
499 else
500 buf = "else if (";
501 startLoc = catchList->getLocStart();
502 startBuf = SM->getCharacterData(startLoc);
503
504 assert((*startBuf == '@') && "bogus @catch location");
505
506 const char *lParenLoc = strchr(startBuf, '(');
507
508 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
509 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
510 if (t == Context->getObjcIdType()) {
511 buf += "1) { ";
512 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
513 buf.c_str(), buf.size());
514 sawIdTypedCatch = true;
515 } else if (const PointerType *pType = t->getAsPointerType()) {
516 ObjcInterfaceType *cls; // Should be a pointer to a class.
517
518 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
519 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000520 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000521 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000522 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000523 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
524 buf.c_str(), buf.size());
525 }
526 }
527 // Now rewrite the body...
528 lastCatchBody = catchList->getCatchBody();
529 SourceLocation rParenLoc = catchList->getRParenLoc();
530 SourceLocation bodyLoc = lastCatchBody->getLocStart();
531 const char *bodyBuf = SM->getCharacterData(bodyLoc);
532 const char *rParenBuf = SM->getCharacterData(rParenLoc);
533 assert((*rParenBuf == ')') && "bogus @catch paren location");
534 assert((*bodyBuf == '{') && "bogus @catch body location");
535
536 buf = " = _caught;";
537 // Here we replace ") {" with "= _caught;" (which initializes and
538 // declares the @catch parameter).
539 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
540 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000541 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000542 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000543 }
Steve Naroff75730982007-11-07 04:08:17 +0000544 catchList = catchList->getNextCatchStmt();
545 }
546 // Complete the catch list...
547 if (lastCatchBody) {
548 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
549 const char *bodyBuf = SM->getCharacterData(bodyLoc);
550 assert((*bodyBuf == '}') && "bogus @catch body location");
551 bodyLoc = bodyLoc.getFileLocWithOffset(1);
552 buf = " } } /* @catch end */\n";
553
Chris Lattner28d1fe82007-11-08 04:41:51 +0000554 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000555
556 // Set lastCurlyLoc
557 lastCurlyLoc = lastCatchBody->getLocEnd();
558 }
559 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
560 startLoc = finalStmt->getLocStart();
561 startBuf = SM->getCharacterData(startLoc);
562 assert((*startBuf == '@') && "bogus @finally start");
563
564 buf = "/* @finally */";
565 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
566
567 Stmt *body = finalStmt->getFinallyBody();
568 SourceLocation startLoc = body->getLocStart();
569 SourceLocation endLoc = body->getLocEnd();
570 const char *startBuf = SM->getCharacterData(startLoc);
571 const char *endBuf = SM->getCharacterData(endLoc);
572 assert((*startBuf == '{') && "bogus @finally body location");
573 assert((*endBuf == '}') && "bogus @finally body location");
574
575 startLoc = startLoc.getFileLocWithOffset(1);
576 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000577 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000578 endLoc = endLoc.getFileLocWithOffset(-1);
579 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000580 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000581
582 // Set lastCurlyLoc
583 lastCurlyLoc = body->getLocEnd();
584 }
585 // Now emit the final closing curly brace...
586 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
587 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000588 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000589 return 0;
590}
591
592Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
593 return 0;
594}
595
596Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
597 return 0;
598}
599
Steve Naroff2bd03922007-11-07 15:32:26 +0000600// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
601// the throw expression is typically a message expression that's already
602// been rewritten! (which implies the SourceLocation's are invalid).
603Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
604 // Get the start location and compute the semi location.
605 SourceLocation startLoc = S->getLocStart();
606 const char *startBuf = SM->getCharacterData(startLoc);
607
608 assert((*startBuf == '@') && "bogus @throw location");
609
610 std::string buf;
611 /* void objc_exception_throw(id) __attribute__((noreturn)); */
612 buf = "objc_exception_throw(";
613 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
614 const char *semiBuf = strchr(startBuf, ';');
615 assert((*semiBuf == ';') && "@throw: can't find ';'");
616 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
617 buf = ");";
618 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
619 return 0;
620}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000621
Chris Lattnere64b7772007-10-24 16:57:36 +0000622Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000623 // Create a new string expression.
624 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000625 std::string StrEncoding;
626 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
627 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
628 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000629 SourceLocation(), SourceLocation());
630 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000631 delete Exp;
632 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000633}
634
Steve Naroffb42f8412007-11-05 14:50:49 +0000635Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
636 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
637 // Create a call to sel_registerName("selName").
638 llvm::SmallVector<Expr*, 8> SelExprs;
639 QualType argType = Context->getPointerType(Context->CharTy);
640 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
641 Exp->getSelector().getName().size(),
642 false, argType, SourceLocation(),
643 SourceLocation()));
644 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
645 &SelExprs[0], SelExprs.size());
646 Rewrite.ReplaceStmt(Exp, SelExp);
647 delete Exp;
648 return SelExp;
649}
650
Steve Naroff934f2762007-10-24 22:48:43 +0000651CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
652 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000653 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000654 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000655
656 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000657 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000658
659 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000660 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000661 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
662
663 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000664
Steve Naroff934f2762007-10-24 22:48:43 +0000665 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
666}
667
Steve Naroffd5255f52007-11-01 13:24:47 +0000668static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
669 const char *&startRef, const char *&endRef) {
670 while (startBuf < endBuf) {
671 if (*startBuf == '<')
672 startRef = startBuf; // mark the start.
673 if (*startBuf == '>') {
674 assert((startRef && *startRef == '<') && "rewrite scanning error");
675 endRef = startBuf; // mark the end.
676 return true;
677 }
678 startBuf++;
679 }
680 return false;
681}
682
683bool RewriteTest::needToScanForQualifiers(QualType T) {
684 // FIXME: we don't currently represent "id <Protocol>" in the type system.
685 if (T == Context->getObjcIdType())
686 return true;
687
688 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000689 Type *pointeeType = pType->getPointeeType().getTypePtr();
690 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
691 return true; // we have "Class <Protocol> *".
692 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000693 return false;
694}
695
696void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
697 const FunctionTypeProto *proto, FunctionDecl *FD) {
698
699 if (needToScanForQualifiers(proto->getResultType())) {
700 // Since types are unique, we need to scan the buffer.
701 SourceLocation Loc = FD->getLocation();
702
703 const char *endBuf = SM->getCharacterData(Loc);
704 const char *startBuf = endBuf;
705 while (*startBuf != ';')
706 startBuf--; // scan backward (from the decl location) for return type.
707 const char *startRef = 0, *endRef = 0;
708 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
709 // Get the locations of the startRef, endRef.
710 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
711 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
712 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000713 Rewrite.InsertText(LessLoc, "/*", 2);
714 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000715 }
716 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000717 // Now check arguments.
718 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
719 if (needToScanForQualifiers(proto->getArgType(i))) {
720 // Since types are unique, we need to scan the buffer.
721 SourceLocation Loc = FD->getLocation();
722
723 const char *startBuf = SM->getCharacterData(Loc);
724 const char *endBuf = startBuf;
725 while (*endBuf != ';')
726 endBuf++; // scan forward (from the decl location) for argument types.
727 const char *startRef = 0, *endRef = 0;
728 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
729 // Get the locations of the startRef, endRef.
730 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
731 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
732 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000733 Rewrite.InsertText(LessLoc, "/*", 2);
734 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000735 }
736 }
737 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000738}
739
Steve Naroff09b266e2007-10-30 23:14:51 +0000740void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
741 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000742 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000743 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000744 return;
745 }
746 // Check for ObjC 'id' and class types that have been adorned with protocol
747 // information (id<p>, C<p>*). The protocol references need to be rewritten!
748 const FunctionType *funcType = FD->getType()->getAsFunctionType();
749 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000750 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
751 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000752}
753
754// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
755void RewriteTest::SynthMsgSendFunctionDecl() {
756 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
757 llvm::SmallVector<QualType, 16> ArgTys;
758 QualType argT = Context->getObjcIdType();
759 assert(!argT.isNull() && "Can't find 'id' type");
760 ArgTys.push_back(argT);
761 argT = Context->getObjcSelType();
762 assert(!argT.isNull() && "Can't find 'SEL' type");
763 ArgTys.push_back(argT);
764 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
765 &ArgTys[0], ArgTys.size(),
766 true /*isVariadic*/);
767 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
768 msgSendIdent, msgSendType,
769 FunctionDecl::Extern, false, 0);
770}
771
772// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
773void RewriteTest::SynthGetClassFunctionDecl() {
774 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
775 llvm::SmallVector<QualType, 16> ArgTys;
776 ArgTys.push_back(Context->getPointerType(
777 Context->CharTy.getQualifiedType(QualType::Const)));
778 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
779 &ArgTys[0], ArgTys.size(),
780 false /*isVariadic*/);
781 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
782 getClassIdent, getClassType,
783 FunctionDecl::Extern, false, 0);
784}
785
Steve Naroff96984642007-11-08 14:30:50 +0000786// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
787void RewriteTest::SynthCFStringFunctionDecl() {
788 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
789 llvm::SmallVector<QualType, 16> ArgTys;
790 ArgTys.push_back(Context->getPointerType(
791 Context->CharTy.getQualifiedType(QualType::Const)));
792 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
793 &ArgTys[0], ArgTys.size(),
794 false /*isVariadic*/);
795 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
796 getClassIdent, getClassType,
797 FunctionDecl::Extern, false, 0);
798}
799
Steve Naroffbeaf2992007-11-03 11:27:19 +0000800Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000801#if 1
802 // This rewrite is specific to GCC, which has builtin support for CFString.
803 if (!CFStringFunctionDecl)
804 SynthCFStringFunctionDecl();
805 // Create a call to __builtin___CFStringMakeConstantString("cstr").
806 llvm::SmallVector<Expr*, 8> StrExpr;
807 StrExpr.push_back(Exp->getString());
808 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
809 &StrExpr[0], StrExpr.size());
810 // cast to NSConstantString *
811 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
812 Rewrite.ReplaceStmt(Exp, cast);
813 delete Exp;
814 return cast;
815#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000816 assert(ConstantStringClassReference && "Can't find constant string reference");
817 llvm::SmallVector<Expr*, 4> InitExprs;
818
819 // Synthesize "(Class)&_NSConstantStringClassReference"
820 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
821 ConstantStringClassReference->getType(),
822 SourceLocation());
823 QualType expType = Context->getPointerType(ClsRef->getType());
824 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
825 expType, SourceLocation());
826 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
827 SourceLocation());
828 InitExprs.push_back(cast); // set the 'isa'.
829 InitExprs.push_back(Exp->getString()); // set "char *bytes".
830 unsigned IntSize = static_cast<unsigned>(
831 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
832 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
833 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
834 Exp->getLocStart());
835 InitExprs.push_back(len); // set "int numBytes".
836
837 // struct NSConstantString
838 QualType CFConstantStrType = Context->getCFConstantStringType();
839 // (struct NSConstantString) { <exprs from above> }
840 InitListExpr *ILE = new InitListExpr(SourceLocation(),
841 &InitExprs[0], InitExprs.size(),
842 SourceLocation());
843 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
844 // struct NSConstantString *
845 expType = Context->getPointerType(StrRep->getType());
846 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
847 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000848 // cast to NSConstantString *
849 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000850 Rewrite.ReplaceStmt(Exp, cast);
851 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000852 return cast;
Steve Naroff96984642007-11-08 14:30:50 +0000853#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +0000854}
855
Steve Naroff934f2762007-10-24 22:48:43 +0000856Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000857 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000858 if (!MsgSendFunctionDecl)
859 SynthMsgSendFunctionDecl();
860 if (!GetClassFunctionDecl)
861 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000862
863 // Synthesize a call to objc_msgSend().
864 llvm::SmallVector<Expr*, 8> MsgExprs;
865 IdentifierInfo *clsName = Exp->getClassName();
866
867 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
868 if (clsName) { // class message.
869 llvm::SmallVector<Expr*, 8> ClsExprs;
870 QualType argType = Context->getPointerType(Context->CharTy);
871 ClsExprs.push_back(new StringLiteral(clsName->getName(),
872 clsName->getLength(),
873 false, argType, SourceLocation(),
874 SourceLocation()));
875 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
876 &ClsExprs[0], ClsExprs.size());
877 MsgExprs.push_back(Cls);
878 } else // instance message.
879 MsgExprs.push_back(Exp->getReceiver());
880
Steve Naroffbeaf2992007-11-03 11:27:19 +0000881 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000882 llvm::SmallVector<Expr*, 8> SelExprs;
883 QualType argType = Context->getPointerType(Context->CharTy);
884 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
885 Exp->getSelector().getName().size(),
886 false, argType, SourceLocation(),
887 SourceLocation()));
888 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
889 &SelExprs[0], SelExprs.size());
890 MsgExprs.push_back(SelExp);
891
892 // Now push any user supplied arguments.
893 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
894 MsgExprs.push_back(Exp->getArg(i));
895 // We've transferred the ownership to MsgExprs. Null out the argument in
896 // the original expression, since we will delete it below.
897 Exp->setArg(i, 0);
898 }
Steve Naroffab972d32007-11-04 22:37:50 +0000899 // Generate the funky cast.
900 CastExpr *cast;
901 llvm::SmallVector<QualType, 8> ArgTypes;
902 QualType returnType;
903
904 // Push 'id' and 'SEL', the 2 implicit arguments.
905 ArgTypes.push_back(Context->getObjcIdType());
906 ArgTypes.push_back(Context->getObjcSelType());
907 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
908 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000909 for (int i = 0; i < mDecl->getNumParams(); i++) {
910 QualType t = mDecl->getParamDecl(i)->getType();
911 if (t == Context->getObjcClassType())
912 t = Context->getObjcIdType(); // Convert "Class"->"id"
913 ArgTypes.push_back(t);
914 }
Steve Naroffab972d32007-11-04 22:37:50 +0000915 returnType = mDecl->getResultType();
916 } else {
917 returnType = Context->getObjcIdType();
918 }
919 // Get the type, we will need to reference it in a couple spots.
920 QualType msgSendType = MsgSendFunctionDecl->getType();
921
922 // Create a reference to the objc_msgSend() declaration.
923 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
924
925 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
926 // If we don't do this cast, we get the following bizarre warning/note:
927 // xx.m:13: warning: function called through a non-compatible type
928 // xx.m:13: note: if this code is reached, the program will abort
929 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
930 SourceLocation());
931
932 // Now do the "normal" pointer to function cast.
933 QualType castType = Context->getFunctionType(returnType,
934 &ArgTypes[0], ArgTypes.size(),
935 false/*FIXME:variadic*/);
936 castType = Context->getPointerType(castType);
937 cast = new CastExpr(castType, cast, SourceLocation());
938
939 // Don't forget the parens to enforce the proper binding.
940 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
941
942 const FunctionType *FT = msgSendType->getAsFunctionType();
943 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
944 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000945 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000946 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000947
Chris Lattnere64b7772007-10-24 16:57:36 +0000948 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000949 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000950}
951
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000952/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
953/// an objective-c class with ivars.
954void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
955 std::string &Result) {
956 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
957 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000958 // Do not synthesize more than once.
959 if (ObjcSynthesizedStructs.count(CDecl))
960 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000961 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
962 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
963 // Do it for the root
964 SynthesizeObjcInternalStruct(RCDecl, Result);
965 }
966
967 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000968 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000969 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000970 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
971 return;
972
Steve Naroff04960052007-11-01 17:12:31 +0000973 Result += "\nstruct ";
974 Result += CDecl->getName();
975 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
976 Result += " {\n struct ";
977 Result += RCDecl->getName();
978 Result += " _";
979 Result += RCDecl->getName();
980 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000981 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000982 else
983 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000984
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000985 if (NumIvars > 0) {
986 SourceLocation LocStart = CDecl->getLocStart();
987 SourceLocation LocEnd = CDecl->getLocEnd();
988
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 startBuf = strchr(startBuf, '{');
992 assert((startBuf && endBuf)
993 && "SynthesizeObjcInternalStruct - malformed @interface");
994 startBuf++; // past '{'
995 while (startBuf < endBuf) {
996 if (*startBuf == '@') {
997 startBuf = strchr(startBuf, 'p');
998 // FIXME: presence of @public, etc. inside comment results in
999 // this transformation as well, which is still correct c-code.
1000 if (!strncmp(startBuf, "public", strlen("public"))) {
1001 startBuf += strlen("public");
1002 Result += "/* @public */";
1003 }
1004 else if (!strncmp(startBuf, "private", strlen("private"))) {
1005 startBuf += strlen("private");
1006 Result += "/* @private */";
1007 }
1008 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1009 startBuf += strlen("protected");
1010 Result += "/* @protected */";
1011 }
1012 }
1013 Result += *startBuf++;
1014 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001015 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001016
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001017 Result += "};\n";
1018 // Mark this struct as having been generated.
1019 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001020 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001021}
1022
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001023// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1024/// class methods.
1025void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
1026 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001027 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001028 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001029 const char *ClassName,
1030 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001031 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001032 if (NumMethods > 0 && !objc_impl_method) {
1033 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001034 SEL _cmd;
1035 char *method_types;
1036 void *_imp;
1037 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001038 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001039 Result += "\nstruct _objc_method {\n";
1040 Result += "\tSEL _cmd;\n";
1041 Result += "\tchar *method_types;\n";
1042 Result += "\tvoid *_imp;\n";
1043 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001044
1045 /* struct _objc_method_list {
1046 struct _objc_method_list *next_method;
1047 int method_count;
1048 struct _objc_method method_list[];
1049 }
1050 */
1051 Result += "\nstruct _objc_method_list {\n";
1052 Result += "\tstruct _objc_method_list *next_method;\n";
1053 Result += "\tint method_count;\n";
1054 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001055 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001056 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001057 // Build _objc_method_list for class's methods if needed
1058 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001059 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001060 Result += prefix;
1061 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1062 Result += "_METHODS_";
1063 Result += ClassName;
1064 Result += " __attribute__ ((section (\"__OBJC, __";
1065 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001066 Result += "_meth\")))= ";
1067 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1068
1069 Result += "\t,{{(SEL)\"";
1070 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001071 std::string MethodTypeString;
1072 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1073 Result += "\", \"";
1074 Result += MethodTypeString;
1075 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001076 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001077 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001078 Result += "\t ,{(SEL)\"";
1079 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001080 std::string MethodTypeString;
1081 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1082 Result += "\", \"";
1083 Result += MethodTypeString;
1084 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001085 }
1086 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001087 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001088}
1089
1090/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1091void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1092 int NumProtocols,
1093 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001094 const char *ClassName,
1095 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001096 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001097 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001098 for (int i = 0; i < NumProtocols; i++) {
1099 ObjcProtocolDecl *PDecl = Protocols[i];
1100 // Output struct protocol_methods holder of method selector and type.
1101 if (!objc_protocol_methods &&
1102 (PDecl->getNumInstanceMethods() > 0
1103 || PDecl->getNumClassMethods() > 0)) {
1104 /* struct protocol_methods {
1105 SEL _cmd;
1106 char *method_types;
1107 }
1108 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001109 Result += "\nstruct protocol_methods {\n";
1110 Result += "\tSEL _cmd;\n";
1111 Result += "\tchar *method_types;\n";
1112 Result += "};\n";
1113
1114 /* struct _objc_protocol_method_list {
1115 int protocol_method_count;
1116 struct protocol_methods protocols[];
1117 }
1118 */
1119 Result += "\nstruct _objc_protocol_method_list {\n";
1120 Result += "\tint protocol_method_count;\n";
1121 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001122 objc_protocol_methods = true;
1123 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001124
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001125 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001126 int NumMethods = PDecl->getNumInstanceMethods();
1127 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001128 Result += "\nstatic struct _objc_protocol_method_list "
1129 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1130 Result += PDecl->getName();
1131 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1132 "{\n\t" + utostr(NumMethods) + "\n";
1133
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001134 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001135 Result += "\t,{{(SEL)\"";
1136 Result += Methods[0]->getSelector().getName().c_str();
1137 Result += "\", \"\"}\n";
1138
1139 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001140 Result += "\t ,{(SEL)\"";
1141 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001142 std::string MethodTypeString;
1143 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1144 Result += "\", \"";
1145 Result += MethodTypeString;
1146 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001147 }
1148 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001149 }
1150
1151 // Output class methods declared in this protocol.
1152 NumMethods = PDecl->getNumClassMethods();
1153 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001154 Result += "\nstatic struct _objc_protocol_method_list "
1155 "_OBJC_PROTOCOL_CLASS_METHODS_";
1156 Result += PDecl->getName();
1157 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1158 "{\n\t";
1159 Result += utostr(NumMethods);
1160 Result += "\n";
1161
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001162 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001163 Result += "\t,{{(SEL)\"";
1164 Result += Methods[0]->getSelector().getName().c_str();
1165 Result += "\", \"\"}\n";
1166
1167 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001168 Result += "\t ,{(SEL)\"";
1169 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001170 std::string MethodTypeString;
1171 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1172 Result += "\", \"";
1173 Result += MethodTypeString;
1174 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001175 }
1176 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001177 }
1178 // Output:
1179 /* struct _objc_protocol {
1180 // Objective-C 1.0 extensions
1181 struct _objc_protocol_extension *isa;
1182 char *protocol_name;
1183 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001184 struct _objc_protocol_method_list *instance_methods;
1185 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001186 };
1187 */
1188 static bool objc_protocol = false;
1189 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001190 Result += "\nstruct _objc_protocol {\n";
1191 Result += "\tstruct _objc_protocol_extension *isa;\n";
1192 Result += "\tchar *protocol_name;\n";
1193 Result += "\tstruct _objc_protocol **protocol_list;\n";
1194 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1195 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1196 Result += "};\n";
1197
1198 /* struct _objc_protocol_list {
1199 struct _objc_protocol_list *next;
1200 int protocol_count;
1201 struct _objc_protocol *class_protocols[];
1202 }
1203 */
1204 Result += "\nstruct _objc_protocol_list {\n";
1205 Result += "\tstruct _objc_protocol_list *next;\n";
1206 Result += "\tint protocol_count;\n";
1207 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1208 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001209 objc_protocol = true;
1210 }
1211
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001212 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1213 Result += PDecl->getName();
1214 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1215 "{\n\t0, \"";
1216 Result += PDecl->getName();
1217 Result += "\", 0, ";
1218 if (PDecl->getInstanceMethods() > 0) {
1219 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1220 Result += PDecl->getName();
1221 Result += ", ";
1222 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001223 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001224 Result += "0, ";
1225 if (PDecl->getClassMethods() > 0) {
1226 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1227 Result += PDecl->getName();
1228 Result += "\n";
1229 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001230 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001231 Result += "0\n";
1232 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001233 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001234 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001235 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1236 Result += prefix;
1237 Result += "_PROTOCOLS_";
1238 Result += ClassName;
1239 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1240 "{\n\t0, ";
1241 Result += utostr(NumProtocols);
1242 Result += "\n";
1243
1244 Result += "\t,{&_OBJC_PROTOCOL_";
1245 Result += Protocols[0]->getName();
1246 Result += " \n";
1247
1248 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001249 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001250 Result += "\t ,&_OBJC_PROTOCOL_";
1251 Result += PDecl->getName();
1252 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001253 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001254 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001255 }
1256}
1257
1258/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1259/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001260void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1261 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001262 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1263 // Find category declaration for this implementation.
1264 ObjcCategoryDecl *CDecl;
1265 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1266 CDecl = CDecl->getNextClassCategory())
1267 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1268 break;
1269 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1270
1271 char *FullCategoryName = (char*)alloca(
1272 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1273 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1274
1275 // Build _objc_method_list for class's instance methods if needed
1276 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1277 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001278 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001279 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001280
1281 // Build _objc_method_list for class's class methods if needed
1282 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1283 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001284 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001285 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001286
1287 // Protocols referenced in class declaration?
1288 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1289 CDecl->getNumReferencedProtocols(),
1290 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001291 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001292
1293 /* struct _objc_category {
1294 char *category_name;
1295 char *class_name;
1296 struct _objc_method_list *instance_methods;
1297 struct _objc_method_list *class_methods;
1298 struct _objc_protocol_list *protocols;
1299 // Objective-C 1.0 extensions
1300 uint32_t size; // sizeof (struct _objc_category)
1301 struct _objc_property_list *instance_properties; // category's own
1302 // @property decl.
1303 };
1304 */
1305
1306 static bool objc_category = false;
1307 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001308 Result += "\nstruct _objc_category {\n";
1309 Result += "\tchar *category_name;\n";
1310 Result += "\tchar *class_name;\n";
1311 Result += "\tstruct _objc_method_list *instance_methods;\n";
1312 Result += "\tstruct _objc_method_list *class_methods;\n";
1313 Result += "\tstruct _objc_protocol_list *protocols;\n";
1314 Result += "\tunsigned int size;\n";
1315 Result += "\tstruct _objc_property_list *instance_properties;\n";
1316 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001317 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001318 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001319 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1320 Result += FullCategoryName;
1321 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1322 Result += IDecl->getName();
1323 Result += "\"\n\t, \"";
1324 Result += ClassDecl->getName();
1325 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001326
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001327 if (IDecl->getNumInstanceMethods() > 0) {
1328 Result += "\t, (struct _objc_method_list *)"
1329 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1330 Result += FullCategoryName;
1331 Result += "\n";
1332 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001333 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001334 Result += "\t, 0\n";
1335 if (IDecl->getNumClassMethods() > 0) {
1336 Result += "\t, (struct _objc_method_list *)"
1337 "&_OBJC_CATEGORY_CLASS_METHODS_";
1338 Result += FullCategoryName;
1339 Result += "\n";
1340 }
1341 else
1342 Result += "\t, 0\n";
1343
1344 if (CDecl->getNumReferencedProtocols() > 0) {
1345 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1346 Result += FullCategoryName;
1347 Result += "\n";
1348 }
1349 else
1350 Result += "\t, 0\n";
1351 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001352}
1353
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001354/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1355/// ivar offset.
1356void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1357 ObjcIvarDecl *ivar,
1358 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001359 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001360 Result += IDecl->getName();
1361 Result += ", ";
1362 Result += ivar->getName();
1363 Result += ")";
1364}
1365
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001366//===----------------------------------------------------------------------===//
1367// Meta Data Emission
1368//===----------------------------------------------------------------------===//
1369
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001370void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1371 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001372 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1373
1374 // Build _objc_ivar_list metadata for classes ivars if needed
1375 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1376 ? IDecl->getImplDeclNumIvars()
1377 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1378
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001379 SynthesizeObjcInternalStruct(CDecl, Result);
1380
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001381 if (NumIvars > 0) {
1382 static bool objc_ivar = false;
1383 if (!objc_ivar) {
1384 /* struct _objc_ivar {
1385 char *ivar_name;
1386 char *ivar_type;
1387 int ivar_offset;
1388 };
1389 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001390 Result += "\nstruct _objc_ivar {\n";
1391 Result += "\tchar *ivar_name;\n";
1392 Result += "\tchar *ivar_type;\n";
1393 Result += "\tint ivar_offset;\n";
1394 Result += "};\n";
1395
1396 /* struct _objc_ivar_list {
1397 int ivar_count;
1398 struct _objc_ivar ivar_list[];
1399 };
1400 */
1401 Result += "\nstruct _objc_ivar_list {\n";
1402 Result += "\tint ivar_count;\n";
1403 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001404 objc_ivar = true;
1405 }
1406
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001407 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1408 Result += IDecl->getName();
1409 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1410 "{\n\t";
1411 Result += utostr(NumIvars);
1412 Result += "\n";
1413
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001414 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1415 ? IDecl->getImplDeclIVars()
1416 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001417 Result += "\t,{{\"";
1418 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001419 Result += "\", \"";
1420 std::string StrEncoding;
1421 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1422 Result += StrEncoding;
1423 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001424 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1425 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001426 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001427 Result += "\t ,{\"";
1428 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001429 Result += "\", \"";
1430 std::string StrEncoding;
1431 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1432 Result += StrEncoding;
1433 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001434 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1435 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001436 }
1437
1438 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001439 }
1440
1441 // Build _objc_method_list for class's instance methods if needed
1442 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1443 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001444 true,
1445 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001446
1447 // Build _objc_method_list for class's class methods if needed
1448 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001449 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001450 false,
1451 "", IDecl->getName(), Result);
1452
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001453 // Protocols referenced in class declaration?
1454 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1455 CDecl->getNumIntfRefProtocols(),
1456 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001457 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001458
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001459
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001460 // Declaration of class/meta-class metadata
1461 /* struct _objc_class {
1462 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001463 const char *super_class_name;
1464 char *name;
1465 long version;
1466 long info;
1467 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001468 struct _objc_ivar_list *ivars;
1469 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001470 struct objc_cache *cache;
1471 struct objc_protocol_list *protocols;
1472 const char *ivar_layout;
1473 struct _objc_class_ext *ext;
1474 };
1475 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001476 static bool objc_class = false;
1477 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001478 Result += "\nstruct _objc_class {\n";
1479 Result += "\tstruct _objc_class *isa;\n";
1480 Result += "\tconst char *super_class_name;\n";
1481 Result += "\tchar *name;\n";
1482 Result += "\tlong version;\n";
1483 Result += "\tlong info;\n";
1484 Result += "\tlong instance_size;\n";
1485 Result += "\tstruct _objc_ivar_list *ivars;\n";
1486 Result += "\tstruct _objc_method_list *methods;\n";
1487 Result += "\tstruct objc_cache *cache;\n";
1488 Result += "\tstruct _objc_protocol_list *protocols;\n";
1489 Result += "\tconst char *ivar_layout;\n";
1490 Result += "\tstruct _objc_class_ext *ext;\n";
1491 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001492 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001493 }
1494
1495 // Meta-class metadata generation.
1496 ObjcInterfaceDecl *RootClass = 0;
1497 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1498 while (SuperClass) {
1499 RootClass = SuperClass;
1500 SuperClass = SuperClass->getSuperClass();
1501 }
1502 SuperClass = CDecl->getSuperClass();
1503
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001504 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1505 Result += CDecl->getName();
1506 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1507 "{\n\t(struct _objc_class *)\"";
1508 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1509 Result += "\"";
1510
1511 if (SuperClass) {
1512 Result += ", \"";
1513 Result += SuperClass->getName();
1514 Result += "\", \"";
1515 Result += CDecl->getName();
1516 Result += "\"";
1517 }
1518 else {
1519 Result += ", 0, \"";
1520 Result += CDecl->getName();
1521 Result += "\"";
1522 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001523 // TODO: 'ivars' field for root class is currently set to 0.
1524 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001525 Result += ", 0,2, sizeof(struct _objc_class), 0";
1526 if (CDecl->getNumClassMethods() > 0) {
1527 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1528 Result += CDecl->getName();
1529 Result += "\n";
1530 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001531 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001532 Result += ", 0\n";
1533 if (CDecl->getNumIntfRefProtocols() > 0) {
1534 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1535 Result += CDecl->getName();
1536 Result += ",0,0\n";
1537 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001538 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001539 Result += "\t,0,0,0,0\n";
1540 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001541
1542 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001543 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1544 Result += CDecl->getName();
1545 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1546 "{\n\t&_OBJC_METACLASS_";
1547 Result += CDecl->getName();
1548 if (SuperClass) {
1549 Result += ", \"";
1550 Result += SuperClass->getName();
1551 Result += "\", \"";
1552 Result += CDecl->getName();
1553 Result += "\"";
1554 }
1555 else {
1556 Result += ", 0, \"";
1557 Result += CDecl->getName();
1558 Result += "\"";
1559 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001560 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001561 Result += ", 0,1";
1562 if (!ObjcSynthesizedStructs.count(CDecl))
1563 Result += ",0";
1564 else {
1565 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001566 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001567 Result += CDecl->getName();
1568 Result += ")";
1569 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001570 if (NumIvars > 0) {
1571 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1572 Result += CDecl->getName();
1573 Result += "\n\t";
1574 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001575 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001576 Result += ",0";
1577 if (IDecl->getNumInstanceMethods() > 0) {
1578 Result += ", &_OBJC_INSTANCE_METHODS_";
1579 Result += CDecl->getName();
1580 Result += ", 0\n\t";
1581 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001582 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001583 Result += ",0,0";
1584 if (CDecl->getNumIntfRefProtocols() > 0) {
1585 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1586 Result += CDecl->getName();
1587 Result += ", 0,0\n";
1588 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001589 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001590 Result += ",0,0,0\n";
1591 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001592}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001593
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001594void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001595 int ClsDefCount = ClassImplementation.size();
1596 int CatDefCount = CategoryImplementation.size();
1597 if (ClsDefCount == 0 && CatDefCount == 0)
1598 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001599
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001600 // TODO: This is temporary until we decide how to access objc types in a
1601 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001602 Result += "#include <Objc/objc.h>\n";
1603 // This is needed for use of offsetof
1604 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001605
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001606 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001607 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001608 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001609
1610 // For each implemented category, write out all its meta data.
1611 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001612 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001613
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001614 // Write objc_symtab metadata
1615 /*
1616 struct _objc_symtab
1617 {
1618 long sel_ref_cnt;
1619 SEL *refs;
1620 short cls_def_cnt;
1621 short cat_def_cnt;
1622 void *defs[cls_def_cnt + cat_def_cnt];
1623 };
1624 */
1625
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001626 Result += "\nstruct _objc_symtab {\n";
1627 Result += "\tlong sel_ref_cnt;\n";
1628 Result += "\tSEL *refs;\n";
1629 Result += "\tshort cls_def_cnt;\n";
1630 Result += "\tshort cat_def_cnt;\n";
1631 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1632 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001633
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001634 Result += "static struct _objc_symtab "
1635 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1636 Result += "\t0, 0, " + utostr(ClsDefCount)
1637 + ", " + utostr(CatDefCount) + "\n";
1638 for (int i = 0; i < ClsDefCount; i++) {
1639 Result += "\t,&_OBJC_CLASS_";
1640 Result += ClassImplementation[i]->getName();
1641 Result += "\n";
1642 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001643
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001644 for (int i = 0; i < CatDefCount; i++) {
1645 Result += "\t,&_OBJC_CATEGORY_";
1646 Result += CategoryImplementation[i]->getClassInterface()->getName();
1647 Result += "_";
1648 Result += CategoryImplementation[i]->getName();
1649 Result += "\n";
1650 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001651
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001652 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001653
1654 // Write objc_module metadata
1655
1656 /*
1657 struct _objc_module {
1658 long version;
1659 long size;
1660 const char *name;
1661 struct _objc_symtab *symtab;
1662 }
1663 */
1664
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001665 Result += "\nstruct _objc_module {\n";
1666 Result += "\tlong version;\n";
1667 Result += "\tlong size;\n";
1668 Result += "\tconst char *name;\n";
1669 Result += "\tstruct _objc_symtab *symtab;\n";
1670 Result += "};\n\n";
1671 Result += "static struct _objc_module "
1672 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001673 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1674 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001675 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001676}
Chris Lattner311ff022007-10-16 22:36:42 +00001677