blob: dfe3d4e93b4774ce6ba7cab0689826b9be8ce7e0 [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 Naroffebf2b562007-10-23 23:50:29 +000041
Steve Naroffbeaf2992007-11-03 11:27:19 +000042 // ObjC string constant support.
43 FileVarDecl *ConstantStringClassReference;
44 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000045
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000046 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000047 public:
Chris Lattner01c57482007-10-17 22:35:30 +000048 void Initialize(ASTContext &context, unsigned mainFileID) {
49 Context = &context;
50 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000051 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000052 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000053 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000054 SelGetUidFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 ConstantStringClassReference = 0;
56 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000057 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffab972d32007-11-04 22:37:50 +000058 const char *s = "extern struct objc_object *objc_msgSend"
59 "(struct objc_object *, struct objc_selector *, ...);\n"
60 "extern struct objc_object *objc_getClass"
61 "(const char *);\n";
62 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
63 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 }
Chris Lattner8a12c272007-10-11 18:38:32 +000065
Chris Lattnerf04da132007-10-24 17:06:59 +000066 // Top Level Driver code.
67 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000069 ~RewriteTest();
70
71 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000072 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000073 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000074 void RewriteTabs();
75 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000076 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000077 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000078 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000079 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff09b266e2007-10-30 23:14:51 +000080 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000081 void RewriteObjcQualifiedInterfaceTypes(
82 const FunctionTypeProto *proto, FunctionDecl *FD);
83 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000084
Chris Lattnerf04da132007-10-24 17:06:59 +000085 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000086 Stmt *RewriteFunctionBody(Stmt *S);
87 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +000088 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +000089 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000090 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000091 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
92 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000093 void SynthMsgSendFunctionDecl();
94 void SynthGetClassFunctionDecl();
95
Chris Lattnerf04da132007-10-24 17:06:59 +000096 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000097 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
98 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000099
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000100 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
101 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000102
103 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
104 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000105 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000106 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000107 const char *ClassName,
108 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000109
110 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
111 int NumProtocols,
112 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000113 const char *ClassName,
114 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000115 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
116 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000117 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
118 ObjcIvarDecl *ivar,
119 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000121 };
122}
123
Chris Lattner8a12c272007-10-11 18:38:32 +0000124ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000125
Chris Lattnerf04da132007-10-24 17:06:59 +0000126//===----------------------------------------------------------------------===//
127// Top Level Driver Code
128//===----------------------------------------------------------------------===//
129
Chris Lattner8a12c272007-10-11 18:38:32 +0000130void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000131 // Two cases: either the decl could be in the main file, or it could be in a
132 // #included file. If the former, rewrite it now. If the later, check to see
133 // if we rewrote the #include/#import.
134 SourceLocation Loc = D->getLocation();
135 Loc = SM->getLogicalLoc(Loc);
136
137 // If this is for a builtin, ignore it.
138 if (Loc.isInvalid()) return;
139
Steve Naroffebf2b562007-10-23 23:50:29 +0000140 // Look for built-in declarations that we need to refer during the rewrite.
141 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000142 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000143 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
144 // declared in <Foundation/NSString.h>
145 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
146 ConstantStringClassReference = FVD;
147 return;
148 }
Steve Naroffbef11852007-10-26 20:53:56 +0000149 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
150 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000151 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
152 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000153 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
154 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000157 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
158 return HandleDeclInMainFile(D);
159
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 // Otherwise, see if there is a #import in the main file that should be
161 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000162 RewriteInclude(Loc);
163}
164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165/// HandleDeclInMainFile - This is called for each top-level decl defined in the
166/// main file of the input.
167void RewriteTest::HandleDeclInMainFile(Decl *D) {
168 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
169 if (Stmt *Body = FD->getBody())
170 FD->setBody(RewriteFunctionBody(Body));
171
172 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
173 ClassImplementation.push_back(CI);
174 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
175 CategoryImplementation.push_back(CI);
176 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
177 RewriteForwardClassDecl(CD);
178 // Nothing yet.
179}
180
181RewriteTest::~RewriteTest() {
182 // Get the top-level buffer that this corresponds to.
183 RewriteTabs();
184
185 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
186 // we are done.
187 if (const RewriteBuffer *RewriteBuf =
188 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000189 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 std::string S(RewriteBuf->begin(), RewriteBuf->end());
191 printf("%s\n", S.c_str());
192 } else {
193 printf("No changes\n");
194 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000195
196}
197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198//===----------------------------------------------------------------------===//
199// Syntactic (non-AST) Rewriting Code
200//===----------------------------------------------------------------------===//
201
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000202void RewriteTest::RewriteInclude(SourceLocation Loc) {
203 // Rip up the #include stack to the main file.
204 SourceLocation IncLoc = Loc, NextLoc = Loc;
205 do {
206 IncLoc = Loc;
207 Loc = SM->getLogicalLoc(NextLoc);
208 NextLoc = SM->getIncludeLoc(Loc);
209 } while (!NextLoc.isInvalid());
210
211 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
212 // IncLoc indicates the header that was included if it is useful.
213 IncLoc = SM->getLogicalLoc(IncLoc);
214 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
215 Loc == LastIncLoc)
216 return;
217 LastIncLoc = Loc;
218
219 unsigned IncCol = SM->getColumnNumber(Loc);
220 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
221
222 // Replace the #import with #include.
223 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
224}
225
Chris Lattnerf04da132007-10-24 17:06:59 +0000226void RewriteTest::RewriteTabs() {
227 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
228 const char *MainBufStart = MainBuf.first;
229 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000230
Chris Lattnerf04da132007-10-24 17:06:59 +0000231 // Loop over the whole file, looking for tabs.
232 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
233 if (*BufPtr != '\t')
234 continue;
235
236 // Okay, we found a tab. This tab will turn into at least one character,
237 // but it depends on which 'virtual column' it is in. Compute that now.
238 unsigned VCol = 0;
239 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
240 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
241 ++VCol;
242
243 // Okay, now that we know the virtual column, we know how many spaces to
244 // insert. We assume 8-character tab-stops.
245 unsigned Spaces = 8-(VCol & 7);
246
247 // Get the location of the tab.
248 SourceLocation TabLoc =
249 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
250
251 // Rewrite the single tab character into a sequence of spaces.
252 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
253 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000254}
255
256
Chris Lattnerf04da132007-10-24 17:06:59 +0000257void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
258 int numDecls = ClassDecl->getNumForwardDecls();
259 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
260
261 // Get the start location and compute the semi location.
262 SourceLocation startLoc = ClassDecl->getLocation();
263 const char *startBuf = SM->getCharacterData(startLoc);
264 const char *semiPtr = strchr(startBuf, ';');
265
266 // Translate to typedef's that forward reference structs with the same name
267 // as the class. As a convenience, we include the original declaration
268 // as a comment.
269 std::string typedefString;
270 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000271 typedefString.append(startBuf, semiPtr-startBuf+1);
272 typedefString += "\n";
273 for (int i = 0; i < numDecls; i++) {
274 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000275 if (ObjcForwardDecls.count(ForwardDecl))
276 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000277 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000278 typedefString += ForwardDecl->getName();
279 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000280
281 // Mark this typedef as having been generated.
282 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000283 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000284 }
285
286 // Replace the @class with typedefs corresponding to the classes.
287 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
288 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000289}
290
Steve Naroff423cb562007-10-30 13:30:57 +0000291void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
292 for (int i = 0; i < nMethods; i++) {
293 ObjcMethodDecl *Method = Methods[i];
294 SourceLocation Loc = Method->getLocStart();
295
296 Rewrite.ReplaceText(Loc, 0, "// ", 3);
297
298 // FIXME: handle methods that are declared across multiple lines.
299 }
300}
301
302void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
303 SourceLocation LocStart = CatDecl->getLocStart();
304
305 // FIXME: handle category headers that are declared across multiple lines.
306 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
307
308 RewriteMethods(CatDecl->getNumInstanceMethods(),
309 CatDecl->getInstanceMethods());
310 RewriteMethods(CatDecl->getNumClassMethods(),
311 CatDecl->getClassMethods());
312 // Lastly, comment out the @end.
313 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
314}
315
Steve Naroff752d6ef2007-10-30 16:42:30 +0000316void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
317 SourceLocation LocStart = PDecl->getLocStart();
318
319 // FIXME: handle protocol headers that are declared across multiple lines.
320 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
321
322 RewriteMethods(PDecl->getNumInstanceMethods(),
323 PDecl->getInstanceMethods());
324 RewriteMethods(PDecl->getNumClassMethods(),
325 PDecl->getClassMethods());
326 // Lastly, comment out the @end.
327 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
328}
329
Steve Naroffbef11852007-10-26 20:53:56 +0000330void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000331
332 SourceLocation LocStart = ClassDecl->getLocStart();
333 SourceLocation LocEnd = ClassDecl->getLocEnd();
334
335 const char *startBuf = SM->getCharacterData(LocStart);
336 const char *endBuf = SM->getCharacterData(LocEnd);
337
Steve Naroff2feac5e2007-10-30 03:43:13 +0000338 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000339
340 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000341 if (!ObjcForwardDecls.count(ClassDecl)) {
342 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000343 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000344 ResultStr += ClassDecl->getName();
345 ResultStr += ";";
346
347 // Mark this typedef as having been generated.
348 ObjcForwardDecls.insert(ClassDecl);
349 }
Steve Narofff908a872007-10-30 02:23:23 +0000350 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
351
Steve Naroff2feac5e2007-10-30 03:43:13 +0000352 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000353 ResultStr.c_str(), ResultStr.size());
354
Steve Naroff423cb562007-10-30 13:30:57 +0000355 RewriteMethods(ClassDecl->getNumInstanceMethods(),
356 ClassDecl->getInstanceMethods());
357 RewriteMethods(ClassDecl->getNumClassMethods(),
358 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000359
Steve Naroff2feac5e2007-10-30 03:43:13 +0000360 // Lastly, comment out the @end.
361 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000362}
363
Chris Lattnerf04da132007-10-24 17:06:59 +0000364//===----------------------------------------------------------------------===//
365// Function Body / Expression rewriting
366//===----------------------------------------------------------------------===//
367
Chris Lattnere64b7772007-10-24 16:57:36 +0000368Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000369 // Otherwise, just rewrite all children.
370 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
371 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000372 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000373 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000374
375 // Handle specific things.
376 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
377 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000378
379 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
380 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000381
382 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
383 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000384
Steve Naroff934f2762007-10-24 22:48:43 +0000385 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
386 // Before we rewrite it, put the original message expression in a comment.
387 SourceLocation startLoc = MessExpr->getLocStart();
388 SourceLocation endLoc = MessExpr->getLocEnd();
389
390 const char *startBuf = SM->getCharacterData(startLoc);
391 const char *endBuf = SM->getCharacterData(endLoc);
392
393 std::string messString;
394 messString += "// ";
395 messString.append(startBuf, endBuf-startBuf+1);
396 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000397
Steve Naroff934f2762007-10-24 22:48:43 +0000398 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
399 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
400 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000401 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000402 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000403 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000404 // Return this stmt unmodified.
405 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000406}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000407
Chris Lattnere64b7772007-10-24 16:57:36 +0000408Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000409 // Create a new string expression.
410 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000411 std::string StrEncoding;
412 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
413 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
414 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000415 SourceLocation(), SourceLocation());
416 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000417 delete Exp;
418 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000419}
420
Steve Naroffb42f8412007-11-05 14:50:49 +0000421Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
422 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
423 // Create a call to sel_registerName("selName").
424 llvm::SmallVector<Expr*, 8> SelExprs;
425 QualType argType = Context->getPointerType(Context->CharTy);
426 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
427 Exp->getSelector().getName().size(),
428 false, argType, SourceLocation(),
429 SourceLocation()));
430 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
431 &SelExprs[0], SelExprs.size());
432 Rewrite.ReplaceStmt(Exp, SelExp);
433 delete Exp;
434 return SelExp;
435}
436
Steve Naroff934f2762007-10-24 22:48:43 +0000437CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
438 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000439 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000440 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000441
442 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000443 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000444
445 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000446 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000447 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
448
449 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000450
Steve Naroff934f2762007-10-24 22:48:43 +0000451 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
452}
453
Steve Naroffd5255f52007-11-01 13:24:47 +0000454static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
455 const char *&startRef, const char *&endRef) {
456 while (startBuf < endBuf) {
457 if (*startBuf == '<')
458 startRef = startBuf; // mark the start.
459 if (*startBuf == '>') {
460 assert((startRef && *startRef == '<') && "rewrite scanning error");
461 endRef = startBuf; // mark the end.
462 return true;
463 }
464 startBuf++;
465 }
466 return false;
467}
468
469bool RewriteTest::needToScanForQualifiers(QualType T) {
470 // FIXME: we don't currently represent "id <Protocol>" in the type system.
471 if (T == Context->getObjcIdType())
472 return true;
473
474 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000475 Type *pointeeType = pType->getPointeeType().getTypePtr();
476 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
477 return true; // we have "Class <Protocol> *".
478 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000479 return false;
480}
481
482void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
483 const FunctionTypeProto *proto, FunctionDecl *FD) {
484
485 if (needToScanForQualifiers(proto->getResultType())) {
486 // Since types are unique, we need to scan the buffer.
487 SourceLocation Loc = FD->getLocation();
488
489 const char *endBuf = SM->getCharacterData(Loc);
490 const char *startBuf = endBuf;
491 while (*startBuf != ';')
492 startBuf--; // scan backward (from the decl location) for return type.
493 const char *startRef = 0, *endRef = 0;
494 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
495 // Get the locations of the startRef, endRef.
496 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
497 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
498 // Comment out the protocol references.
499 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
500 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000501 }
502 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000503 // Now check arguments.
504 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
505 if (needToScanForQualifiers(proto->getArgType(i))) {
506 // Since types are unique, we need to scan the buffer.
507 SourceLocation Loc = FD->getLocation();
508
509 const char *startBuf = SM->getCharacterData(Loc);
510 const char *endBuf = startBuf;
511 while (*endBuf != ';')
512 endBuf++; // scan forward (from the decl location) for argument types.
513 const char *startRef = 0, *endRef = 0;
514 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
515 // Get the locations of the startRef, endRef.
516 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
517 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
518 // Comment out the protocol references.
519 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
520 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
521 }
522 }
523 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000524}
525
Steve Naroff09b266e2007-10-30 23:14:51 +0000526void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
527 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000528 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000529 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000530 return;
531 }
532 // Check for ObjC 'id' and class types that have been adorned with protocol
533 // information (id<p>, C<p>*). The protocol references need to be rewritten!
534 const FunctionType *funcType = FD->getType()->getAsFunctionType();
535 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000536 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
537 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000538}
539
540// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
541void RewriteTest::SynthMsgSendFunctionDecl() {
542 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
543 llvm::SmallVector<QualType, 16> ArgTys;
544 QualType argT = Context->getObjcIdType();
545 assert(!argT.isNull() && "Can't find 'id' type");
546 ArgTys.push_back(argT);
547 argT = Context->getObjcSelType();
548 assert(!argT.isNull() && "Can't find 'SEL' type");
549 ArgTys.push_back(argT);
550 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
551 &ArgTys[0], ArgTys.size(),
552 true /*isVariadic*/);
553 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
554 msgSendIdent, msgSendType,
555 FunctionDecl::Extern, false, 0);
556}
557
558// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
559void RewriteTest::SynthGetClassFunctionDecl() {
560 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
561 llvm::SmallVector<QualType, 16> ArgTys;
562 ArgTys.push_back(Context->getPointerType(
563 Context->CharTy.getQualifiedType(QualType::Const)));
564 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
565 &ArgTys[0], ArgTys.size(),
566 false /*isVariadic*/);
567 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
568 getClassIdent, getClassType,
569 FunctionDecl::Extern, false, 0);
570}
571
Steve Naroffbeaf2992007-11-03 11:27:19 +0000572Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
573 assert(ConstantStringClassReference && "Can't find constant string reference");
574 llvm::SmallVector<Expr*, 4> InitExprs;
575
576 // Synthesize "(Class)&_NSConstantStringClassReference"
577 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
578 ConstantStringClassReference->getType(),
579 SourceLocation());
580 QualType expType = Context->getPointerType(ClsRef->getType());
581 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
582 expType, SourceLocation());
583 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
584 SourceLocation());
585 InitExprs.push_back(cast); // set the 'isa'.
586 InitExprs.push_back(Exp->getString()); // set "char *bytes".
587 unsigned IntSize = static_cast<unsigned>(
588 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
589 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
590 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
591 Exp->getLocStart());
592 InitExprs.push_back(len); // set "int numBytes".
593
594 // struct NSConstantString
595 QualType CFConstantStrType = Context->getCFConstantStringType();
596 // (struct NSConstantString) { <exprs from above> }
597 InitListExpr *ILE = new InitListExpr(SourceLocation(),
598 &InitExprs[0], InitExprs.size(),
599 SourceLocation());
600 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
601 // struct NSConstantString *
602 expType = Context->getPointerType(StrRep->getType());
603 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
604 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000605 // cast to NSConstantString *
606 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000607 Rewrite.ReplaceStmt(Exp, cast);
608 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000609 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000610}
611
Steve Naroff934f2762007-10-24 22:48:43 +0000612Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000613 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000614 if (!MsgSendFunctionDecl)
615 SynthMsgSendFunctionDecl();
616 if (!GetClassFunctionDecl)
617 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000618
619 // Synthesize a call to objc_msgSend().
620 llvm::SmallVector<Expr*, 8> MsgExprs;
621 IdentifierInfo *clsName = Exp->getClassName();
622
623 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
624 if (clsName) { // class message.
625 llvm::SmallVector<Expr*, 8> ClsExprs;
626 QualType argType = Context->getPointerType(Context->CharTy);
627 ClsExprs.push_back(new StringLiteral(clsName->getName(),
628 clsName->getLength(),
629 false, argType, SourceLocation(),
630 SourceLocation()));
631 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
632 &ClsExprs[0], ClsExprs.size());
633 MsgExprs.push_back(Cls);
634 } else // instance message.
635 MsgExprs.push_back(Exp->getReceiver());
636
Steve Naroffbeaf2992007-11-03 11:27:19 +0000637 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000638 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 MsgExprs.push_back(SelExp);
647
648 // Now push any user supplied arguments.
649 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
650 MsgExprs.push_back(Exp->getArg(i));
651 // We've transferred the ownership to MsgExprs. Null out the argument in
652 // the original expression, since we will delete it below.
653 Exp->setArg(i, 0);
654 }
Steve Naroffab972d32007-11-04 22:37:50 +0000655 // Generate the funky cast.
656 CastExpr *cast;
657 llvm::SmallVector<QualType, 8> ArgTypes;
658 QualType returnType;
659
660 // Push 'id' and 'SEL', the 2 implicit arguments.
661 ArgTypes.push_back(Context->getObjcIdType());
662 ArgTypes.push_back(Context->getObjcSelType());
663 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
664 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000665 for (int i = 0; i < mDecl->getNumParams(); i++) {
666 QualType t = mDecl->getParamDecl(i)->getType();
667 if (t == Context->getObjcClassType())
668 t = Context->getObjcIdType(); // Convert "Class"->"id"
669 ArgTypes.push_back(t);
670 }
Steve Naroffab972d32007-11-04 22:37:50 +0000671 returnType = mDecl->getResultType();
672 } else {
673 returnType = Context->getObjcIdType();
674 }
675 // Get the type, we will need to reference it in a couple spots.
676 QualType msgSendType = MsgSendFunctionDecl->getType();
677
678 // Create a reference to the objc_msgSend() declaration.
679 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
680
681 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
682 // If we don't do this cast, we get the following bizarre warning/note:
683 // xx.m:13: warning: function called through a non-compatible type
684 // xx.m:13: note: if this code is reached, the program will abort
685 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
686 SourceLocation());
687
688 // Now do the "normal" pointer to function cast.
689 QualType castType = Context->getFunctionType(returnType,
690 &ArgTypes[0], ArgTypes.size(),
691 false/*FIXME:variadic*/);
692 castType = Context->getPointerType(castType);
693 cast = new CastExpr(castType, cast, SourceLocation());
694
695 // Don't forget the parens to enforce the proper binding.
696 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
697
698 const FunctionType *FT = msgSendType->getAsFunctionType();
699 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
700 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000701 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000702 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000703
Chris Lattnere64b7772007-10-24 16:57:36 +0000704 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000705 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000706}
707
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000708/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
709/// an objective-c class with ivars.
710void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
711 std::string &Result) {
712 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
713 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000714 // Do not synthesize more than once.
715 if (ObjcSynthesizedStructs.count(CDecl))
716 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000717 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
718 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
719 // Do it for the root
720 SynthesizeObjcInternalStruct(RCDecl, Result);
721 }
722
723 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000724 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000725 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000726 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
727 return;
728
Steve Naroff04960052007-11-01 17:12:31 +0000729 Result += "\nstruct ";
730 Result += CDecl->getName();
731 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
732 Result += " {\n struct ";
733 Result += RCDecl->getName();
734 Result += " _";
735 Result += RCDecl->getName();
736 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000737 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000738 else
739 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000740
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000741 if (NumIvars > 0) {
742 SourceLocation LocStart = CDecl->getLocStart();
743 SourceLocation LocEnd = CDecl->getLocEnd();
744
745 const char *startBuf = SM->getCharacterData(LocStart);
746 const char *endBuf = SM->getCharacterData(LocEnd);
747 startBuf = strchr(startBuf, '{');
748 assert((startBuf && endBuf)
749 && "SynthesizeObjcInternalStruct - malformed @interface");
750 startBuf++; // past '{'
751 while (startBuf < endBuf) {
752 if (*startBuf == '@') {
753 startBuf = strchr(startBuf, 'p');
754 // FIXME: presence of @public, etc. inside comment results in
755 // this transformation as well, which is still correct c-code.
756 if (!strncmp(startBuf, "public", strlen("public"))) {
757 startBuf += strlen("public");
758 Result += "/* @public */";
759 }
760 else if (!strncmp(startBuf, "private", strlen("private"))) {
761 startBuf += strlen("private");
762 Result += "/* @private */";
763 }
764 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
765 startBuf += strlen("protected");
766 Result += "/* @protected */";
767 }
768 }
769 Result += *startBuf++;
770 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000771 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000772
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000773 Result += "};\n";
774 // Mark this struct as having been generated.
775 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000776 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000777}
778
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000779// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
780/// class methods.
781void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
782 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000783 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000784 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000785 const char *ClassName,
786 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000787 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000788 if (NumMethods > 0 && !objc_impl_method) {
789 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000790 SEL _cmd;
791 char *method_types;
792 void *_imp;
793 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000794 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000795 Result += "\nstruct _objc_method {\n";
796 Result += "\tSEL _cmd;\n";
797 Result += "\tchar *method_types;\n";
798 Result += "\tvoid *_imp;\n";
799 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000800
801 /* struct _objc_method_list {
802 struct _objc_method_list *next_method;
803 int method_count;
804 struct _objc_method method_list[];
805 }
806 */
807 Result += "\nstruct _objc_method_list {\n";
808 Result += "\tstruct _objc_method_list *next_method;\n";
809 Result += "\tint method_count;\n";
810 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000811 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000812 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000813 // Build _objc_method_list for class's methods if needed
814 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000815 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000816 Result += prefix;
817 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
818 Result += "_METHODS_";
819 Result += ClassName;
820 Result += " __attribute__ ((section (\"__OBJC, __";
821 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000822 Result += "_meth\")))= ";
823 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
824
825 Result += "\t,{{(SEL)\"";
826 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000827 std::string MethodTypeString;
828 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
829 Result += "\", \"";
830 Result += MethodTypeString;
831 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000832 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000833 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000834 Result += "\t ,{(SEL)\"";
835 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000836 std::string MethodTypeString;
837 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
838 Result += "\", \"";
839 Result += MethodTypeString;
840 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000841 }
842 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000843 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000844}
845
846/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
847void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
848 int NumProtocols,
849 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000850 const char *ClassName,
851 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000852 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000853 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000854 for (int i = 0; i < NumProtocols; i++) {
855 ObjcProtocolDecl *PDecl = Protocols[i];
856 // Output struct protocol_methods holder of method selector and type.
857 if (!objc_protocol_methods &&
858 (PDecl->getNumInstanceMethods() > 0
859 || PDecl->getNumClassMethods() > 0)) {
860 /* struct protocol_methods {
861 SEL _cmd;
862 char *method_types;
863 }
864 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000865 Result += "\nstruct protocol_methods {\n";
866 Result += "\tSEL _cmd;\n";
867 Result += "\tchar *method_types;\n";
868 Result += "};\n";
869
870 /* struct _objc_protocol_method_list {
871 int protocol_method_count;
872 struct protocol_methods protocols[];
873 }
874 */
875 Result += "\nstruct _objc_protocol_method_list {\n";
876 Result += "\tint protocol_method_count;\n";
877 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000878 objc_protocol_methods = true;
879 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000880
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000881 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000882 int NumMethods = PDecl->getNumInstanceMethods();
883 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000884 Result += "\nstatic struct _objc_protocol_method_list "
885 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
886 Result += PDecl->getName();
887 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
888 "{\n\t" + utostr(NumMethods) + "\n";
889
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000890 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000891 Result += "\t,{{(SEL)\"";
892 Result += Methods[0]->getSelector().getName().c_str();
893 Result += "\", \"\"}\n";
894
895 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000896 Result += "\t ,{(SEL)\"";
897 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000898 std::string MethodTypeString;
899 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
900 Result += "\", \"";
901 Result += MethodTypeString;
902 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000903 }
904 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000905 }
906
907 // Output class methods declared in this protocol.
908 NumMethods = PDecl->getNumClassMethods();
909 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000910 Result += "\nstatic struct _objc_protocol_method_list "
911 "_OBJC_PROTOCOL_CLASS_METHODS_";
912 Result += PDecl->getName();
913 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
914 "{\n\t";
915 Result += utostr(NumMethods);
916 Result += "\n";
917
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000918 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000919 Result += "\t,{{(SEL)\"";
920 Result += Methods[0]->getSelector().getName().c_str();
921 Result += "\", \"\"}\n";
922
923 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000924 Result += "\t ,{(SEL)\"";
925 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000926 std::string MethodTypeString;
927 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
928 Result += "\", \"";
929 Result += MethodTypeString;
930 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000931 }
932 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000933 }
934 // Output:
935 /* struct _objc_protocol {
936 // Objective-C 1.0 extensions
937 struct _objc_protocol_extension *isa;
938 char *protocol_name;
939 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000940 struct _objc_protocol_method_list *instance_methods;
941 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000942 };
943 */
944 static bool objc_protocol = false;
945 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000946 Result += "\nstruct _objc_protocol {\n";
947 Result += "\tstruct _objc_protocol_extension *isa;\n";
948 Result += "\tchar *protocol_name;\n";
949 Result += "\tstruct _objc_protocol **protocol_list;\n";
950 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
951 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
952 Result += "};\n";
953
954 /* struct _objc_protocol_list {
955 struct _objc_protocol_list *next;
956 int protocol_count;
957 struct _objc_protocol *class_protocols[];
958 }
959 */
960 Result += "\nstruct _objc_protocol_list {\n";
961 Result += "\tstruct _objc_protocol_list *next;\n";
962 Result += "\tint protocol_count;\n";
963 Result += "\tstruct _objc_protocol *class_protocols[];\n";
964 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000965 objc_protocol = true;
966 }
967
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000968 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
969 Result += PDecl->getName();
970 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
971 "{\n\t0, \"";
972 Result += PDecl->getName();
973 Result += "\", 0, ";
974 if (PDecl->getInstanceMethods() > 0) {
975 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
976 Result += PDecl->getName();
977 Result += ", ";
978 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000979 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000980 Result += "0, ";
981 if (PDecl->getClassMethods() > 0) {
982 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
983 Result += PDecl->getName();
984 Result += "\n";
985 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000986 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000987 Result += "0\n";
988 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000989 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000990 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000991 Result += "\nstatic struct _objc_protocol_list _OBJC_";
992 Result += prefix;
993 Result += "_PROTOCOLS_";
994 Result += ClassName;
995 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
996 "{\n\t0, ";
997 Result += utostr(NumProtocols);
998 Result += "\n";
999
1000 Result += "\t,{&_OBJC_PROTOCOL_";
1001 Result += Protocols[0]->getName();
1002 Result += " \n";
1003
1004 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001005 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001006 Result += "\t ,&_OBJC_PROTOCOL_";
1007 Result += PDecl->getName();
1008 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001009 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001010 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001011 }
1012}
1013
1014/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1015/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001016void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1017 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001018 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1019 // Find category declaration for this implementation.
1020 ObjcCategoryDecl *CDecl;
1021 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1022 CDecl = CDecl->getNextClassCategory())
1023 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1024 break;
1025 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1026
1027 char *FullCategoryName = (char*)alloca(
1028 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1029 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1030
1031 // Build _objc_method_list for class's instance methods if needed
1032 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1033 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001034 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001035 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001036
1037 // Build _objc_method_list for class's class methods if needed
1038 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1039 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001040 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001041 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001042
1043 // Protocols referenced in class declaration?
1044 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1045 CDecl->getNumReferencedProtocols(),
1046 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001047 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001048
1049 /* struct _objc_category {
1050 char *category_name;
1051 char *class_name;
1052 struct _objc_method_list *instance_methods;
1053 struct _objc_method_list *class_methods;
1054 struct _objc_protocol_list *protocols;
1055 // Objective-C 1.0 extensions
1056 uint32_t size; // sizeof (struct _objc_category)
1057 struct _objc_property_list *instance_properties; // category's own
1058 // @property decl.
1059 };
1060 */
1061
1062 static bool objc_category = false;
1063 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001064 Result += "\nstruct _objc_category {\n";
1065 Result += "\tchar *category_name;\n";
1066 Result += "\tchar *class_name;\n";
1067 Result += "\tstruct _objc_method_list *instance_methods;\n";
1068 Result += "\tstruct _objc_method_list *class_methods;\n";
1069 Result += "\tstruct _objc_protocol_list *protocols;\n";
1070 Result += "\tunsigned int size;\n";
1071 Result += "\tstruct _objc_property_list *instance_properties;\n";
1072 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001073 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001074 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001075 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1076 Result += FullCategoryName;
1077 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1078 Result += IDecl->getName();
1079 Result += "\"\n\t, \"";
1080 Result += ClassDecl->getName();
1081 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001082
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001083 if (IDecl->getNumInstanceMethods() > 0) {
1084 Result += "\t, (struct _objc_method_list *)"
1085 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1086 Result += FullCategoryName;
1087 Result += "\n";
1088 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001089 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001090 Result += "\t, 0\n";
1091 if (IDecl->getNumClassMethods() > 0) {
1092 Result += "\t, (struct _objc_method_list *)"
1093 "&_OBJC_CATEGORY_CLASS_METHODS_";
1094 Result += FullCategoryName;
1095 Result += "\n";
1096 }
1097 else
1098 Result += "\t, 0\n";
1099
1100 if (CDecl->getNumReferencedProtocols() > 0) {
1101 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1102 Result += FullCategoryName;
1103 Result += "\n";
1104 }
1105 else
1106 Result += "\t, 0\n";
1107 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001108}
1109
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001110/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1111/// ivar offset.
1112void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1113 ObjcIvarDecl *ivar,
1114 std::string &Result) {
1115 Result += "offsetof(struct _interface_";
1116 Result += IDecl->getName();
1117 Result += ", ";
1118 Result += ivar->getName();
1119 Result += ")";
1120}
1121
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001122//===----------------------------------------------------------------------===//
1123// Meta Data Emission
1124//===----------------------------------------------------------------------===//
1125
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001126void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1127 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001128 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1129
1130 // Build _objc_ivar_list metadata for classes ivars if needed
1131 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1132 ? IDecl->getImplDeclNumIvars()
1133 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1134
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001135 SynthesizeObjcInternalStruct(CDecl, Result);
1136
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001137 if (NumIvars > 0) {
1138 static bool objc_ivar = false;
1139 if (!objc_ivar) {
1140 /* struct _objc_ivar {
1141 char *ivar_name;
1142 char *ivar_type;
1143 int ivar_offset;
1144 };
1145 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001146 Result += "\nstruct _objc_ivar {\n";
1147 Result += "\tchar *ivar_name;\n";
1148 Result += "\tchar *ivar_type;\n";
1149 Result += "\tint ivar_offset;\n";
1150 Result += "};\n";
1151
1152 /* struct _objc_ivar_list {
1153 int ivar_count;
1154 struct _objc_ivar ivar_list[];
1155 };
1156 */
1157 Result += "\nstruct _objc_ivar_list {\n";
1158 Result += "\tint ivar_count;\n";
1159 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001160 objc_ivar = true;
1161 }
1162
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001163 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1164 Result += IDecl->getName();
1165 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1166 "{\n\t";
1167 Result += utostr(NumIvars);
1168 Result += "\n";
1169
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001170 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1171 ? IDecl->getImplDeclIVars()
1172 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001173 Result += "\t,{{\"";
1174 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001175 Result += "\", \"";
1176 std::string StrEncoding;
1177 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1178 Result += StrEncoding;
1179 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001180 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1181 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001182 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001183 Result += "\t ,{\"";
1184 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001185 Result += "\", \"";
1186 std::string StrEncoding;
1187 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1188 Result += StrEncoding;
1189 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001190 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1191 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001192 }
1193
1194 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001195 }
1196
1197 // Build _objc_method_list for class's instance methods if needed
1198 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1199 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001200 true,
1201 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001202
1203 // Build _objc_method_list for class's class methods if needed
1204 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001205 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001206 false,
1207 "", IDecl->getName(), Result);
1208
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001209 // Protocols referenced in class declaration?
1210 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1211 CDecl->getNumIntfRefProtocols(),
1212 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001213 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001214
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001215
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001216 // Declaration of class/meta-class metadata
1217 /* struct _objc_class {
1218 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001219 const char *super_class_name;
1220 char *name;
1221 long version;
1222 long info;
1223 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001224 struct _objc_ivar_list *ivars;
1225 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001226 struct objc_cache *cache;
1227 struct objc_protocol_list *protocols;
1228 const char *ivar_layout;
1229 struct _objc_class_ext *ext;
1230 };
1231 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001232 static bool objc_class = false;
1233 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001234 Result += "\nstruct _objc_class {\n";
1235 Result += "\tstruct _objc_class *isa;\n";
1236 Result += "\tconst char *super_class_name;\n";
1237 Result += "\tchar *name;\n";
1238 Result += "\tlong version;\n";
1239 Result += "\tlong info;\n";
1240 Result += "\tlong instance_size;\n";
1241 Result += "\tstruct _objc_ivar_list *ivars;\n";
1242 Result += "\tstruct _objc_method_list *methods;\n";
1243 Result += "\tstruct objc_cache *cache;\n";
1244 Result += "\tstruct _objc_protocol_list *protocols;\n";
1245 Result += "\tconst char *ivar_layout;\n";
1246 Result += "\tstruct _objc_class_ext *ext;\n";
1247 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001248 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001249 }
1250
1251 // Meta-class metadata generation.
1252 ObjcInterfaceDecl *RootClass = 0;
1253 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1254 while (SuperClass) {
1255 RootClass = SuperClass;
1256 SuperClass = SuperClass->getSuperClass();
1257 }
1258 SuperClass = CDecl->getSuperClass();
1259
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001260 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1261 Result += CDecl->getName();
1262 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1263 "{\n\t(struct _objc_class *)\"";
1264 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1265 Result += "\"";
1266
1267 if (SuperClass) {
1268 Result += ", \"";
1269 Result += SuperClass->getName();
1270 Result += "\", \"";
1271 Result += CDecl->getName();
1272 Result += "\"";
1273 }
1274 else {
1275 Result += ", 0, \"";
1276 Result += CDecl->getName();
1277 Result += "\"";
1278 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001279 // TODO: 'ivars' field for root class is currently set to 0.
1280 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001281 Result += ", 0,2, sizeof(struct _objc_class), 0";
1282 if (CDecl->getNumClassMethods() > 0) {
1283 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1284 Result += CDecl->getName();
1285 Result += "\n";
1286 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001287 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001288 Result += ", 0\n";
1289 if (CDecl->getNumIntfRefProtocols() > 0) {
1290 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1291 Result += CDecl->getName();
1292 Result += ",0,0\n";
1293 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001294 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001295 Result += "\t,0,0,0,0\n";
1296 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001297
1298 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001299 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1300 Result += CDecl->getName();
1301 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1302 "{\n\t&_OBJC_METACLASS_";
1303 Result += CDecl->getName();
1304 if (SuperClass) {
1305 Result += ", \"";
1306 Result += SuperClass->getName();
1307 Result += "\", \"";
1308 Result += CDecl->getName();
1309 Result += "\"";
1310 }
1311 else {
1312 Result += ", 0, \"";
1313 Result += CDecl->getName();
1314 Result += "\"";
1315 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001316 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001317 Result += ", 0,1";
1318 if (!ObjcSynthesizedStructs.count(CDecl))
1319 Result += ",0";
1320 else {
1321 // class has size. Must synthesize its size.
1322 Result += ",sizeof(struct _interface_";
1323 Result += CDecl->getName();
1324 Result += ")";
1325 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001326 if (NumIvars > 0) {
1327 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1328 Result += CDecl->getName();
1329 Result += "\n\t";
1330 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001331 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001332 Result += ",0";
1333 if (IDecl->getNumInstanceMethods() > 0) {
1334 Result += ", &_OBJC_INSTANCE_METHODS_";
1335 Result += CDecl->getName();
1336 Result += ", 0\n\t";
1337 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001338 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001339 Result += ",0,0";
1340 if (CDecl->getNumIntfRefProtocols() > 0) {
1341 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1342 Result += CDecl->getName();
1343 Result += ", 0,0\n";
1344 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001345 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001346 Result += ",0,0,0\n";
1347 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001348}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001349
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001350void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001351 int ClsDefCount = ClassImplementation.size();
1352 int CatDefCount = CategoryImplementation.size();
1353 if (ClsDefCount == 0 && CatDefCount == 0)
1354 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001355
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001356 // TODO: This is temporary until we decide how to access objc types in a
1357 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001358 Result += "#include <Objc/objc.h>\n";
1359 // This is needed for use of offsetof
1360 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001361
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001362 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001363 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001364 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001365
1366 // For each implemented category, write out all its meta data.
1367 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001368 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001369
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001370 // Write objc_symtab metadata
1371 /*
1372 struct _objc_symtab
1373 {
1374 long sel_ref_cnt;
1375 SEL *refs;
1376 short cls_def_cnt;
1377 short cat_def_cnt;
1378 void *defs[cls_def_cnt + cat_def_cnt];
1379 };
1380 */
1381
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001382 Result += "\nstruct _objc_symtab {\n";
1383 Result += "\tlong sel_ref_cnt;\n";
1384 Result += "\tSEL *refs;\n";
1385 Result += "\tshort cls_def_cnt;\n";
1386 Result += "\tshort cat_def_cnt;\n";
1387 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1388 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001389
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001390 Result += "static struct _objc_symtab "
1391 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1392 Result += "\t0, 0, " + utostr(ClsDefCount)
1393 + ", " + utostr(CatDefCount) + "\n";
1394 for (int i = 0; i < ClsDefCount; i++) {
1395 Result += "\t,&_OBJC_CLASS_";
1396 Result += ClassImplementation[i]->getName();
1397 Result += "\n";
1398 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001399
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001400 for (int i = 0; i < CatDefCount; i++) {
1401 Result += "\t,&_OBJC_CATEGORY_";
1402 Result += CategoryImplementation[i]->getClassInterface()->getName();
1403 Result += "_";
1404 Result += CategoryImplementation[i]->getName();
1405 Result += "\n";
1406 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001407
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001408 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001409
1410 // Write objc_module metadata
1411
1412 /*
1413 struct _objc_module {
1414 long version;
1415 long size;
1416 const char *name;
1417 struct _objc_symtab *symtab;
1418 }
1419 */
1420
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001421 Result += "\nstruct _objc_module {\n";
1422 Result += "\tlong version;\n";
1423 Result += "\tlong size;\n";
1424 Result += "\tconst char *name;\n";
1425 Result += "\tstruct _objc_symtab *symtab;\n";
1426 Result += "};\n\n";
1427 Result += "static struct _objc_module "
1428 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001429 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1430 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001431 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001432}
Chris Lattner311ff022007-10-16 22:36:42 +00001433