blob: 7153420245d0bada9f47de3c7212db17ff74eb15 [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 Naroffe3abbf52007-11-05 14:55:35 +000058 // declaring objc_selector outside the parameter list removes a silly
59 // scope related warning...
60 const char *s = "struct objc_selector;\n"
61 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000062 "(struct objc_object *, struct objc_selector *, ...);\n"
63 "extern struct objc_object *objc_getClass"
64 "(const char *);\n";
65 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
66 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000067 }
Chris Lattner8a12c272007-10-11 18:38:32 +000068
Chris Lattnerf04da132007-10-24 17:06:59 +000069 // Top Level Driver code.
70 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000071 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000072 ~RewriteTest();
73
74 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000075 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000076 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000077 void RewriteTabs();
78 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000079 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000080 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000081 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000082 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000083 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000084 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000085 void RewriteObjcQualifiedInterfaceTypes(
86 const FunctionTypeProto *proto, FunctionDecl *FD);
87 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000088
Chris Lattnerf04da132007-10-24 17:06:59 +000089 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000090 Stmt *RewriteFunctionBody(Stmt *S);
91 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +000092 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +000093 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000094 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +000095 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
96 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
97 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +000098 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
99 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000100 void SynthMsgSendFunctionDecl();
101 void SynthGetClassFunctionDecl();
102
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000104 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
105 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000106
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000107 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
108 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000109
110 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
111 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000112 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000113 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000114 const char *ClassName,
115 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000116
117 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
118 int NumProtocols,
119 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 const char *ClassName,
121 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000122 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000124 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
125 ObjcIvarDecl *ivar,
126 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000127 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 };
129}
130
Chris Lattner8a12c272007-10-11 18:38:32 +0000131ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133//===----------------------------------------------------------------------===//
134// Top Level Driver Code
135//===----------------------------------------------------------------------===//
136
Chris Lattner8a12c272007-10-11 18:38:32 +0000137void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 // Two cases: either the decl could be in the main file, or it could be in a
139 // #included file. If the former, rewrite it now. If the later, check to see
140 // if we rewrote the #include/#import.
141 SourceLocation Loc = D->getLocation();
142 Loc = SM->getLogicalLoc(Loc);
143
144 // If this is for a builtin, ignore it.
145 if (Loc.isInvalid()) return;
146
Steve Naroffebf2b562007-10-23 23:50:29 +0000147 // Look for built-in declarations that we need to refer during the rewrite.
148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000150 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
151 // declared in <Foundation/NSString.h>
152 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
153 ConstantStringClassReference = FVD;
154 return;
155 }
Steve Naroffbef11852007-10-26 20:53:56 +0000156 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
157 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000158 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
159 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000160 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
161 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000162 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000163 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000164 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
165 return HandleDeclInMainFile(D);
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Otherwise, see if there is a #import in the main file that should be
168 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000169 RewriteInclude(Loc);
170}
171
Chris Lattnerf04da132007-10-24 17:06:59 +0000172/// HandleDeclInMainFile - This is called for each top-level decl defined in the
173/// main file of the input.
174void RewriteTest::HandleDeclInMainFile(Decl *D) {
175 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
176 if (Stmt *Body = FD->getBody())
177 FD->setBody(RewriteFunctionBody(Body));
178
179 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
180 ClassImplementation.push_back(CI);
181 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
182 CategoryImplementation.push_back(CI);
183 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
184 RewriteForwardClassDecl(CD);
185 // Nothing yet.
186}
187
188RewriteTest::~RewriteTest() {
189 // Get the top-level buffer that this corresponds to.
190 RewriteTabs();
191
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000192 // Rewrite Objective-c meta data*
193 std::string ResultStr;
194 WriteObjcMetaData(ResultStr);
195 // For now just print the string out.
196 printf("%s", ResultStr.c_str());
197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
199 // we are done.
200 if (const RewriteBuffer *RewriteBuf =
201 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000202 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000203 std::string S(RewriteBuf->begin(), RewriteBuf->end());
204 printf("%s\n", S.c_str());
205 } else {
206 printf("No changes\n");
207 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000208
209}
210
Chris Lattnerf04da132007-10-24 17:06:59 +0000211//===----------------------------------------------------------------------===//
212// Syntactic (non-AST) Rewriting Code
213//===----------------------------------------------------------------------===//
214
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000215void RewriteTest::RewriteInclude(SourceLocation Loc) {
216 // Rip up the #include stack to the main file.
217 SourceLocation IncLoc = Loc, NextLoc = Loc;
218 do {
219 IncLoc = Loc;
220 Loc = SM->getLogicalLoc(NextLoc);
221 NextLoc = SM->getIncludeLoc(Loc);
222 } while (!NextLoc.isInvalid());
223
224 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
225 // IncLoc indicates the header that was included if it is useful.
226 IncLoc = SM->getLogicalLoc(IncLoc);
227 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
228 Loc == LastIncLoc)
229 return;
230 LastIncLoc = Loc;
231
232 unsigned IncCol = SM->getColumnNumber(Loc);
233 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
234
235 // Replace the #import with #include.
236 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
237}
238
Chris Lattnerf04da132007-10-24 17:06:59 +0000239void RewriteTest::RewriteTabs() {
240 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
241 const char *MainBufStart = MainBuf.first;
242 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000243
Chris Lattnerf04da132007-10-24 17:06:59 +0000244 // Loop over the whole file, looking for tabs.
245 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
246 if (*BufPtr != '\t')
247 continue;
248
249 // Okay, we found a tab. This tab will turn into at least one character,
250 // but it depends on which 'virtual column' it is in. Compute that now.
251 unsigned VCol = 0;
252 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
253 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
254 ++VCol;
255
256 // Okay, now that we know the virtual column, we know how many spaces to
257 // insert. We assume 8-character tab-stops.
258 unsigned Spaces = 8-(VCol & 7);
259
260 // Get the location of the tab.
261 SourceLocation TabLoc =
262 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
263
264 // Rewrite the single tab character into a sequence of spaces.
265 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
266 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000267}
268
269
Chris Lattnerf04da132007-10-24 17:06:59 +0000270void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
271 int numDecls = ClassDecl->getNumForwardDecls();
272 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
273
274 // Get the start location and compute the semi location.
275 SourceLocation startLoc = ClassDecl->getLocation();
276 const char *startBuf = SM->getCharacterData(startLoc);
277 const char *semiPtr = strchr(startBuf, ';');
278
279 // Translate to typedef's that forward reference structs with the same name
280 // as the class. As a convenience, we include the original declaration
281 // as a comment.
282 std::string typedefString;
283 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000284 typedefString.append(startBuf, semiPtr-startBuf+1);
285 typedefString += "\n";
286 for (int i = 0; i < numDecls; i++) {
287 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000288 if (ObjcForwardDecls.count(ForwardDecl))
289 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000290 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000291 typedefString += ForwardDecl->getName();
292 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000293
294 // Mark this typedef as having been generated.
295 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000296 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000297 }
298
299 // Replace the @class with typedefs corresponding to the classes.
300 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
301 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000302}
303
Steve Naroff423cb562007-10-30 13:30:57 +0000304void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
305 for (int i = 0; i < nMethods; i++) {
306 ObjcMethodDecl *Method = Methods[i];
307 SourceLocation Loc = Method->getLocStart();
308
309 Rewrite.ReplaceText(Loc, 0, "// ", 3);
310
311 // FIXME: handle methods that are declared across multiple lines.
312 }
313}
314
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000315void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
316{
317 for (int i = 0; i < nProperties; i++) {
318 ObjcPropertyDecl *Property = Properties[i];
319 SourceLocation Loc = Property->getLocation();
320
321 Rewrite.ReplaceText(Loc, 0, "// ", 3);
322
323 // FIXME: handle properties that are declared across multiple lines.
324 }
325}
326
Steve Naroff423cb562007-10-30 13:30:57 +0000327void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
328 SourceLocation LocStart = CatDecl->getLocStart();
329
330 // FIXME: handle category headers that are declared across multiple lines.
331 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
332
333 RewriteMethods(CatDecl->getNumInstanceMethods(),
334 CatDecl->getInstanceMethods());
335 RewriteMethods(CatDecl->getNumClassMethods(),
336 CatDecl->getClassMethods());
337 // Lastly, comment out the @end.
338 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
339}
340
Steve Naroff752d6ef2007-10-30 16:42:30 +0000341void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
342 SourceLocation LocStart = PDecl->getLocStart();
343
344 // FIXME: handle protocol headers that are declared across multiple lines.
345 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
346
347 RewriteMethods(PDecl->getNumInstanceMethods(),
348 PDecl->getInstanceMethods());
349 RewriteMethods(PDecl->getNumClassMethods(),
350 PDecl->getClassMethods());
351 // Lastly, comment out the @end.
352 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
353}
354
Steve Naroffbef11852007-10-26 20:53:56 +0000355void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000356
357 SourceLocation LocStart = ClassDecl->getLocStart();
358 SourceLocation LocEnd = ClassDecl->getLocEnd();
359
360 const char *startBuf = SM->getCharacterData(LocStart);
361 const char *endBuf = SM->getCharacterData(LocEnd);
362
Steve Naroff2feac5e2007-10-30 03:43:13 +0000363 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000364
365 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000366 if (!ObjcForwardDecls.count(ClassDecl)) {
367 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000368 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000369 ResultStr += ClassDecl->getName();
370 ResultStr += ";";
371
372 // Mark this typedef as having been generated.
373 ObjcForwardDecls.insert(ClassDecl);
374 }
Steve Narofff908a872007-10-30 02:23:23 +0000375 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
376
Steve Naroff2feac5e2007-10-30 03:43:13 +0000377 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000378 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000379 RewriteProperties(ClassDecl->getNumPropertyDecl(),
380 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000381 RewriteMethods(ClassDecl->getNumInstanceMethods(),
382 ClassDecl->getInstanceMethods());
383 RewriteMethods(ClassDecl->getNumClassMethods(),
384 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000385
Steve Naroff2feac5e2007-10-30 03:43:13 +0000386 // Lastly, comment out the @end.
387 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000388}
389
Chris Lattnerf04da132007-10-24 17:06:59 +0000390//===----------------------------------------------------------------------===//
391// Function Body / Expression rewriting
392//===----------------------------------------------------------------------===//
393
Chris Lattnere64b7772007-10-24 16:57:36 +0000394Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000395 // Otherwise, just rewrite all children.
396 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
397 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000398 if (*CI) {
399 Stmt *newStmt = RewriteFunctionBody(*CI);
400 if (newStmt)
401 *CI = newStmt;
402 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000403
404 // Handle specific things.
405 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
406 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000407
408 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
409 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000410
411 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
412 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000413
Steve Naroff934f2762007-10-24 22:48:43 +0000414 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
415 // Before we rewrite it, put the original message expression in a comment.
416 SourceLocation startLoc = MessExpr->getLocStart();
417 SourceLocation endLoc = MessExpr->getLocEnd();
418
419 const char *startBuf = SM->getCharacterData(startLoc);
420 const char *endBuf = SM->getCharacterData(endLoc);
421
422 std::string messString;
423 messString += "// ";
424 messString.append(startBuf, endBuf-startBuf+1);
425 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000426
Steve Naroff934f2762007-10-24 22:48:43 +0000427 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
428 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
429 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000430 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000431 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000432 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000433
434 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
435 return RewriteObjcTryStmt(StmtTry);
436
437 if (ObjcAtCatchStmt *StmtCatch = dyn_cast<ObjcAtCatchStmt>(S))
438 return RewriteObjcCatchStmt(StmtCatch);
439
440 if (ObjcAtFinallyStmt *StmtFinally = dyn_cast<ObjcAtFinallyStmt>(S))
441 return RewriteObjcFinallyStmt(StmtFinally);
442
Chris Lattnere64b7772007-10-24 16:57:36 +0000443 // Return this stmt unmodified.
444 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000445}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000446
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000447Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000448 // Get the start location and compute the semi location.
449 SourceLocation startLoc = S->getLocStart();
450 const char *startBuf = SM->getCharacterData(startLoc);
451
452 assert((*startBuf == '@') && "bogus @try location");
453
454 std::string buf;
455 // declare a new scope with two variables, _stack and _rethrow.
456 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
457 buf += "int buf[18/*32-bit i386*/];\n";
458 buf += "char *pointers[4];} _stack;\n";
459 buf += "id volatile _rethrow = 0;\n";
460 buf += "objc_exception_try_enter(&_stack);\n";
461 buf += "if (!_setjmp(&_stack.buf)) /* @try block continue */\n";
462
463 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
464
465 startLoc = S->getTryBody()->getLocEnd();
466 startBuf = SM->getCharacterData(startLoc);
467
468 assert((*startBuf == '}') && "bogus @try block");
469
470 SourceLocation lastCurlyLoc = startLoc;
471
472 startLoc = startLoc.getFileLocWithOffset(1);
473 buf = " /* @catch begin */ else {\n";
474 buf += " id _caught = objc_exception_extract(&_stack);\n";
475 buf += " objc_exception_try_enter (&_stack);\n";
476 buf += " if (_setjmp(&_stack.buf))\n";
477 buf += " _rethrow = objc_exception_extract(&_stack);\n";
478 buf += " else { /* @catch continue */";
479
480 Rewrite.ReplaceText(startLoc, 0, buf.c_str(), buf.size());
481
482 bool sawIdTypedCatch = false;
483 Stmt *lastCatchBody = 0;
484 ObjcAtCatchStmt *catchList = S->getCatchStmts();
485 while (catchList) {
486 Stmt *catchStmt = catchList->getCatchParamStmt();
487
488 if (catchList == S->getCatchStmts())
489 buf = "if ("; // we are generating code for the first catch clause
490 else
491 buf = "else if (";
492 startLoc = catchList->getLocStart();
493 startBuf = SM->getCharacterData(startLoc);
494
495 assert((*startBuf == '@') && "bogus @catch location");
496
497 const char *lParenLoc = strchr(startBuf, '(');
498
499 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
500 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
501 if (t == Context->getObjcIdType()) {
502 buf += "1) { ";
503 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
504 buf.c_str(), buf.size());
505 sawIdTypedCatch = true;
506 } else if (const PointerType *pType = t->getAsPointerType()) {
507 ObjcInterfaceType *cls; // Should be a pointer to a class.
508
509 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
510 if (cls) {
511 buf += "objc_exception_match(objc_getClass(\"";
512 buf += cls->getDecl()->getName();
513 buf += "\"), _caught)) { ";
514 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
515 buf.c_str(), buf.size());
516 }
517 }
518 // Now rewrite the body...
519 lastCatchBody = catchList->getCatchBody();
520 SourceLocation rParenLoc = catchList->getRParenLoc();
521 SourceLocation bodyLoc = lastCatchBody->getLocStart();
522 const char *bodyBuf = SM->getCharacterData(bodyLoc);
523 const char *rParenBuf = SM->getCharacterData(rParenLoc);
524 assert((*rParenBuf == ')') && "bogus @catch paren location");
525 assert((*bodyBuf == '{') && "bogus @catch body location");
526
527 buf = " = _caught;";
528 // Here we replace ") {" with "= _caught;" (which initializes and
529 // declares the @catch parameter).
530 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
531 buf.c_str(), buf.size());
532 } else if (NullStmt *nullStmt = dyn_cast<NullStmt>(catchStmt)) {
533 } else
534 assert(false && "@catch rewrite bug");
535
536 catchList = catchList->getNextCatchStmt();
537 }
538 // Complete the catch list...
539 if (lastCatchBody) {
540 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
541 const char *bodyBuf = SM->getCharacterData(bodyLoc);
542 assert((*bodyBuf == '}') && "bogus @catch body location");
543 bodyLoc = bodyLoc.getFileLocWithOffset(1);
544 buf = " } } /* @catch end */\n";
545
546 Rewrite.ReplaceText(bodyLoc, 0, buf.c_str(), buf.size());
547
548 // Set lastCurlyLoc
549 lastCurlyLoc = lastCatchBody->getLocEnd();
550 }
551 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
552 startLoc = finalStmt->getLocStart();
553 startBuf = SM->getCharacterData(startLoc);
554 assert((*startBuf == '@') && "bogus @finally start");
555
556 buf = "/* @finally */";
557 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
558
559 Stmt *body = finalStmt->getFinallyBody();
560 SourceLocation startLoc = body->getLocStart();
561 SourceLocation endLoc = body->getLocEnd();
562 const char *startBuf = SM->getCharacterData(startLoc);
563 const char *endBuf = SM->getCharacterData(endLoc);
564 assert((*startBuf == '{') && "bogus @finally body location");
565 assert((*endBuf == '}') && "bogus @finally body location");
566
567 startLoc = startLoc.getFileLocWithOffset(1);
568 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
569 Rewrite.ReplaceText(startLoc, 0, buf.c_str(), buf.size());
570 endLoc = endLoc.getFileLocWithOffset(-1);
571 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
572 Rewrite.ReplaceText(endLoc, 0, buf.c_str(), buf.size());
573
574 // Set lastCurlyLoc
575 lastCurlyLoc = body->getLocEnd();
576 }
577 // Now emit the final closing curly brace...
578 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
579 buf = " } /* @try scope end */\n";
580 Rewrite.ReplaceText(lastCurlyLoc, 0, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000581 return 0;
582}
583
584Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
585 return 0;
586}
587
588Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
589 return 0;
590}
591
592
Chris Lattnere64b7772007-10-24 16:57:36 +0000593Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000594 // Create a new string expression.
595 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000596 std::string StrEncoding;
597 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
598 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
599 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000600 SourceLocation(), SourceLocation());
601 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000602 delete Exp;
603 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000604}
605
Steve Naroffb42f8412007-11-05 14:50:49 +0000606Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
607 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
608 // Create a call to sel_registerName("selName").
609 llvm::SmallVector<Expr*, 8> SelExprs;
610 QualType argType = Context->getPointerType(Context->CharTy);
611 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
612 Exp->getSelector().getName().size(),
613 false, argType, SourceLocation(),
614 SourceLocation()));
615 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
616 &SelExprs[0], SelExprs.size());
617 Rewrite.ReplaceStmt(Exp, SelExp);
618 delete Exp;
619 return SelExp;
620}
621
Steve Naroff934f2762007-10-24 22:48:43 +0000622CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
623 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000624 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000625 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000626
627 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000628 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000629
630 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000631 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000632 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
633
634 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000635
Steve Naroff934f2762007-10-24 22:48:43 +0000636 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
637}
638
Steve Naroffd5255f52007-11-01 13:24:47 +0000639static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
640 const char *&startRef, const char *&endRef) {
641 while (startBuf < endBuf) {
642 if (*startBuf == '<')
643 startRef = startBuf; // mark the start.
644 if (*startBuf == '>') {
645 assert((startRef && *startRef == '<') && "rewrite scanning error");
646 endRef = startBuf; // mark the end.
647 return true;
648 }
649 startBuf++;
650 }
651 return false;
652}
653
654bool RewriteTest::needToScanForQualifiers(QualType T) {
655 // FIXME: we don't currently represent "id <Protocol>" in the type system.
656 if (T == Context->getObjcIdType())
657 return true;
658
659 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000660 Type *pointeeType = pType->getPointeeType().getTypePtr();
661 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
662 return true; // we have "Class <Protocol> *".
663 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000664 return false;
665}
666
667void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
668 const FunctionTypeProto *proto, FunctionDecl *FD) {
669
670 if (needToScanForQualifiers(proto->getResultType())) {
671 // Since types are unique, we need to scan the buffer.
672 SourceLocation Loc = FD->getLocation();
673
674 const char *endBuf = SM->getCharacterData(Loc);
675 const char *startBuf = endBuf;
676 while (*startBuf != ';')
677 startBuf--; // scan backward (from the decl location) for return type.
678 const char *startRef = 0, *endRef = 0;
679 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
680 // Get the locations of the startRef, endRef.
681 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
682 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
683 // Comment out the protocol references.
684 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
685 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000686 }
687 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000688 // Now check arguments.
689 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
690 if (needToScanForQualifiers(proto->getArgType(i))) {
691 // Since types are unique, we need to scan the buffer.
692 SourceLocation Loc = FD->getLocation();
693
694 const char *startBuf = SM->getCharacterData(Loc);
695 const char *endBuf = startBuf;
696 while (*endBuf != ';')
697 endBuf++; // scan forward (from the decl location) for argument types.
698 const char *startRef = 0, *endRef = 0;
699 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
700 // Get the locations of the startRef, endRef.
701 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
702 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
703 // Comment out the protocol references.
704 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
705 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
706 }
707 }
708 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000709}
710
Steve Naroff09b266e2007-10-30 23:14:51 +0000711void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
712 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000713 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000714 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000715 return;
716 }
717 // Check for ObjC 'id' and class types that have been adorned with protocol
718 // information (id<p>, C<p>*). The protocol references need to be rewritten!
719 const FunctionType *funcType = FD->getType()->getAsFunctionType();
720 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000721 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
722 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000723}
724
725// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
726void RewriteTest::SynthMsgSendFunctionDecl() {
727 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
728 llvm::SmallVector<QualType, 16> ArgTys;
729 QualType argT = Context->getObjcIdType();
730 assert(!argT.isNull() && "Can't find 'id' type");
731 ArgTys.push_back(argT);
732 argT = Context->getObjcSelType();
733 assert(!argT.isNull() && "Can't find 'SEL' type");
734 ArgTys.push_back(argT);
735 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
736 &ArgTys[0], ArgTys.size(),
737 true /*isVariadic*/);
738 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
739 msgSendIdent, msgSendType,
740 FunctionDecl::Extern, false, 0);
741}
742
743// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
744void RewriteTest::SynthGetClassFunctionDecl() {
745 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
746 llvm::SmallVector<QualType, 16> ArgTys;
747 ArgTys.push_back(Context->getPointerType(
748 Context->CharTy.getQualifiedType(QualType::Const)));
749 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
750 &ArgTys[0], ArgTys.size(),
751 false /*isVariadic*/);
752 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
753 getClassIdent, getClassType,
754 FunctionDecl::Extern, false, 0);
755}
756
Steve Naroffbeaf2992007-11-03 11:27:19 +0000757Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
758 assert(ConstantStringClassReference && "Can't find constant string reference");
759 llvm::SmallVector<Expr*, 4> InitExprs;
760
761 // Synthesize "(Class)&_NSConstantStringClassReference"
762 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
763 ConstantStringClassReference->getType(),
764 SourceLocation());
765 QualType expType = Context->getPointerType(ClsRef->getType());
766 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
767 expType, SourceLocation());
768 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
769 SourceLocation());
770 InitExprs.push_back(cast); // set the 'isa'.
771 InitExprs.push_back(Exp->getString()); // set "char *bytes".
772 unsigned IntSize = static_cast<unsigned>(
773 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
774 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
775 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
776 Exp->getLocStart());
777 InitExprs.push_back(len); // set "int numBytes".
778
779 // struct NSConstantString
780 QualType CFConstantStrType = Context->getCFConstantStringType();
781 // (struct NSConstantString) { <exprs from above> }
782 InitListExpr *ILE = new InitListExpr(SourceLocation(),
783 &InitExprs[0], InitExprs.size(),
784 SourceLocation());
785 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
786 // struct NSConstantString *
787 expType = Context->getPointerType(StrRep->getType());
788 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
789 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000790 // cast to NSConstantString *
791 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000792 Rewrite.ReplaceStmt(Exp, cast);
793 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000794 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000795}
796
Steve Naroff934f2762007-10-24 22:48:43 +0000797Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000798 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000799 if (!MsgSendFunctionDecl)
800 SynthMsgSendFunctionDecl();
801 if (!GetClassFunctionDecl)
802 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000803
804 // Synthesize a call to objc_msgSend().
805 llvm::SmallVector<Expr*, 8> MsgExprs;
806 IdentifierInfo *clsName = Exp->getClassName();
807
808 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
809 if (clsName) { // class message.
810 llvm::SmallVector<Expr*, 8> ClsExprs;
811 QualType argType = Context->getPointerType(Context->CharTy);
812 ClsExprs.push_back(new StringLiteral(clsName->getName(),
813 clsName->getLength(),
814 false, argType, SourceLocation(),
815 SourceLocation()));
816 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
817 &ClsExprs[0], ClsExprs.size());
818 MsgExprs.push_back(Cls);
819 } else // instance message.
820 MsgExprs.push_back(Exp->getReceiver());
821
Steve Naroffbeaf2992007-11-03 11:27:19 +0000822 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000823 llvm::SmallVector<Expr*, 8> SelExprs;
824 QualType argType = Context->getPointerType(Context->CharTy);
825 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
826 Exp->getSelector().getName().size(),
827 false, argType, SourceLocation(),
828 SourceLocation()));
829 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
830 &SelExprs[0], SelExprs.size());
831 MsgExprs.push_back(SelExp);
832
833 // Now push any user supplied arguments.
834 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
835 MsgExprs.push_back(Exp->getArg(i));
836 // We've transferred the ownership to MsgExprs. Null out the argument in
837 // the original expression, since we will delete it below.
838 Exp->setArg(i, 0);
839 }
Steve Naroffab972d32007-11-04 22:37:50 +0000840 // Generate the funky cast.
841 CastExpr *cast;
842 llvm::SmallVector<QualType, 8> ArgTypes;
843 QualType returnType;
844
845 // Push 'id' and 'SEL', the 2 implicit arguments.
846 ArgTypes.push_back(Context->getObjcIdType());
847 ArgTypes.push_back(Context->getObjcSelType());
848 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
849 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000850 for (int i = 0; i < mDecl->getNumParams(); i++) {
851 QualType t = mDecl->getParamDecl(i)->getType();
852 if (t == Context->getObjcClassType())
853 t = Context->getObjcIdType(); // Convert "Class"->"id"
854 ArgTypes.push_back(t);
855 }
Steve Naroffab972d32007-11-04 22:37:50 +0000856 returnType = mDecl->getResultType();
857 } else {
858 returnType = Context->getObjcIdType();
859 }
860 // Get the type, we will need to reference it in a couple spots.
861 QualType msgSendType = MsgSendFunctionDecl->getType();
862
863 // Create a reference to the objc_msgSend() declaration.
864 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
865
866 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
867 // If we don't do this cast, we get the following bizarre warning/note:
868 // xx.m:13: warning: function called through a non-compatible type
869 // xx.m:13: note: if this code is reached, the program will abort
870 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
871 SourceLocation());
872
873 // Now do the "normal" pointer to function cast.
874 QualType castType = Context->getFunctionType(returnType,
875 &ArgTypes[0], ArgTypes.size(),
876 false/*FIXME:variadic*/);
877 castType = Context->getPointerType(castType);
878 cast = new CastExpr(castType, cast, SourceLocation());
879
880 // Don't forget the parens to enforce the proper binding.
881 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
882
883 const FunctionType *FT = msgSendType->getAsFunctionType();
884 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
885 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000886 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000887 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000888
Chris Lattnere64b7772007-10-24 16:57:36 +0000889 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000890 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000891}
892
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000893/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
894/// an objective-c class with ivars.
895void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
896 std::string &Result) {
897 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
898 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000899 // Do not synthesize more than once.
900 if (ObjcSynthesizedStructs.count(CDecl))
901 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000902 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
903 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
904 // Do it for the root
905 SynthesizeObjcInternalStruct(RCDecl, Result);
906 }
907
908 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000909 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000910 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000911 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
912 return;
913
Steve Naroff04960052007-11-01 17:12:31 +0000914 Result += "\nstruct ";
915 Result += CDecl->getName();
916 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
917 Result += " {\n struct ";
918 Result += RCDecl->getName();
919 Result += " _";
920 Result += RCDecl->getName();
921 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000922 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000923 else
924 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000925
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000926 if (NumIvars > 0) {
927 SourceLocation LocStart = CDecl->getLocStart();
928 SourceLocation LocEnd = CDecl->getLocEnd();
929
930 const char *startBuf = SM->getCharacterData(LocStart);
931 const char *endBuf = SM->getCharacterData(LocEnd);
932 startBuf = strchr(startBuf, '{');
933 assert((startBuf && endBuf)
934 && "SynthesizeObjcInternalStruct - malformed @interface");
935 startBuf++; // past '{'
936 while (startBuf < endBuf) {
937 if (*startBuf == '@') {
938 startBuf = strchr(startBuf, 'p');
939 // FIXME: presence of @public, etc. inside comment results in
940 // this transformation as well, which is still correct c-code.
941 if (!strncmp(startBuf, "public", strlen("public"))) {
942 startBuf += strlen("public");
943 Result += "/* @public */";
944 }
945 else if (!strncmp(startBuf, "private", strlen("private"))) {
946 startBuf += strlen("private");
947 Result += "/* @private */";
948 }
949 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
950 startBuf += strlen("protected");
951 Result += "/* @protected */";
952 }
953 }
954 Result += *startBuf++;
955 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000956 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000957
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000958 Result += "};\n";
959 // Mark this struct as having been generated.
960 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000961 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000962}
963
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000964// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
965/// class methods.
966void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
967 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000968 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000969 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000970 const char *ClassName,
971 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000972 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000973 if (NumMethods > 0 && !objc_impl_method) {
974 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000975 SEL _cmd;
976 char *method_types;
977 void *_imp;
978 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000979 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000980 Result += "\nstruct _objc_method {\n";
981 Result += "\tSEL _cmd;\n";
982 Result += "\tchar *method_types;\n";
983 Result += "\tvoid *_imp;\n";
984 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000985
986 /* struct _objc_method_list {
987 struct _objc_method_list *next_method;
988 int method_count;
989 struct _objc_method method_list[];
990 }
991 */
992 Result += "\nstruct _objc_method_list {\n";
993 Result += "\tstruct _objc_method_list *next_method;\n";
994 Result += "\tint method_count;\n";
995 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000996 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000997 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000998 // Build _objc_method_list for class's methods if needed
999 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001000 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001001 Result += prefix;
1002 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1003 Result += "_METHODS_";
1004 Result += ClassName;
1005 Result += " __attribute__ ((section (\"__OBJC, __";
1006 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001007 Result += "_meth\")))= ";
1008 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1009
1010 Result += "\t,{{(SEL)\"";
1011 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001012 std::string MethodTypeString;
1013 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1014 Result += "\", \"";
1015 Result += MethodTypeString;
1016 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001017 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001018 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001019 Result += "\t ,{(SEL)\"";
1020 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001021 std::string MethodTypeString;
1022 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1023 Result += "\", \"";
1024 Result += MethodTypeString;
1025 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001026 }
1027 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001028 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001029}
1030
1031/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1032void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1033 int NumProtocols,
1034 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001035 const char *ClassName,
1036 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001037 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001038 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001039 for (int i = 0; i < NumProtocols; i++) {
1040 ObjcProtocolDecl *PDecl = Protocols[i];
1041 // Output struct protocol_methods holder of method selector and type.
1042 if (!objc_protocol_methods &&
1043 (PDecl->getNumInstanceMethods() > 0
1044 || PDecl->getNumClassMethods() > 0)) {
1045 /* struct protocol_methods {
1046 SEL _cmd;
1047 char *method_types;
1048 }
1049 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001050 Result += "\nstruct protocol_methods {\n";
1051 Result += "\tSEL _cmd;\n";
1052 Result += "\tchar *method_types;\n";
1053 Result += "};\n";
1054
1055 /* struct _objc_protocol_method_list {
1056 int protocol_method_count;
1057 struct protocol_methods protocols[];
1058 }
1059 */
1060 Result += "\nstruct _objc_protocol_method_list {\n";
1061 Result += "\tint protocol_method_count;\n";
1062 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001063 objc_protocol_methods = true;
1064 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001065
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001066 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001067 int NumMethods = PDecl->getNumInstanceMethods();
1068 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001069 Result += "\nstatic struct _objc_protocol_method_list "
1070 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1071 Result += PDecl->getName();
1072 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1073 "{\n\t" + utostr(NumMethods) + "\n";
1074
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001075 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001076 Result += "\t,{{(SEL)\"";
1077 Result += Methods[0]->getSelector().getName().c_str();
1078 Result += "\", \"\"}\n";
1079
1080 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001081 Result += "\t ,{(SEL)\"";
1082 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001083 std::string MethodTypeString;
1084 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1085 Result += "\", \"";
1086 Result += MethodTypeString;
1087 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001088 }
1089 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001090 }
1091
1092 // Output class methods declared in this protocol.
1093 NumMethods = PDecl->getNumClassMethods();
1094 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001095 Result += "\nstatic struct _objc_protocol_method_list "
1096 "_OBJC_PROTOCOL_CLASS_METHODS_";
1097 Result += PDecl->getName();
1098 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1099 "{\n\t";
1100 Result += utostr(NumMethods);
1101 Result += "\n";
1102
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001103 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001104 Result += "\t,{{(SEL)\"";
1105 Result += Methods[0]->getSelector().getName().c_str();
1106 Result += "\", \"\"}\n";
1107
1108 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001109 Result += "\t ,{(SEL)\"";
1110 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001111 std::string MethodTypeString;
1112 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1113 Result += "\", \"";
1114 Result += MethodTypeString;
1115 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001116 }
1117 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001118 }
1119 // Output:
1120 /* struct _objc_protocol {
1121 // Objective-C 1.0 extensions
1122 struct _objc_protocol_extension *isa;
1123 char *protocol_name;
1124 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001125 struct _objc_protocol_method_list *instance_methods;
1126 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001127 };
1128 */
1129 static bool objc_protocol = false;
1130 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001131 Result += "\nstruct _objc_protocol {\n";
1132 Result += "\tstruct _objc_protocol_extension *isa;\n";
1133 Result += "\tchar *protocol_name;\n";
1134 Result += "\tstruct _objc_protocol **protocol_list;\n";
1135 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1136 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1137 Result += "};\n";
1138
1139 /* struct _objc_protocol_list {
1140 struct _objc_protocol_list *next;
1141 int protocol_count;
1142 struct _objc_protocol *class_protocols[];
1143 }
1144 */
1145 Result += "\nstruct _objc_protocol_list {\n";
1146 Result += "\tstruct _objc_protocol_list *next;\n";
1147 Result += "\tint protocol_count;\n";
1148 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1149 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001150 objc_protocol = true;
1151 }
1152
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001153 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1154 Result += PDecl->getName();
1155 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1156 "{\n\t0, \"";
1157 Result += PDecl->getName();
1158 Result += "\", 0, ";
1159 if (PDecl->getInstanceMethods() > 0) {
1160 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1161 Result += PDecl->getName();
1162 Result += ", ";
1163 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001164 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001165 Result += "0, ";
1166 if (PDecl->getClassMethods() > 0) {
1167 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1168 Result += PDecl->getName();
1169 Result += "\n";
1170 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001171 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001172 Result += "0\n";
1173 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001174 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001175 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001176 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1177 Result += prefix;
1178 Result += "_PROTOCOLS_";
1179 Result += ClassName;
1180 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1181 "{\n\t0, ";
1182 Result += utostr(NumProtocols);
1183 Result += "\n";
1184
1185 Result += "\t,{&_OBJC_PROTOCOL_";
1186 Result += Protocols[0]->getName();
1187 Result += " \n";
1188
1189 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001190 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001191 Result += "\t ,&_OBJC_PROTOCOL_";
1192 Result += PDecl->getName();
1193 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001194 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001195 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001196 }
1197}
1198
1199/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1200/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001201void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1202 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001203 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1204 // Find category declaration for this implementation.
1205 ObjcCategoryDecl *CDecl;
1206 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1207 CDecl = CDecl->getNextClassCategory())
1208 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1209 break;
1210 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1211
1212 char *FullCategoryName = (char*)alloca(
1213 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1214 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1215
1216 // Build _objc_method_list for class's instance methods if needed
1217 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1218 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001219 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001220 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001221
1222 // Build _objc_method_list for class's class methods if needed
1223 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1224 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001225 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001226 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001227
1228 // Protocols referenced in class declaration?
1229 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1230 CDecl->getNumReferencedProtocols(),
1231 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001232 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001233
1234 /* struct _objc_category {
1235 char *category_name;
1236 char *class_name;
1237 struct _objc_method_list *instance_methods;
1238 struct _objc_method_list *class_methods;
1239 struct _objc_protocol_list *protocols;
1240 // Objective-C 1.0 extensions
1241 uint32_t size; // sizeof (struct _objc_category)
1242 struct _objc_property_list *instance_properties; // category's own
1243 // @property decl.
1244 };
1245 */
1246
1247 static bool objc_category = false;
1248 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001249 Result += "\nstruct _objc_category {\n";
1250 Result += "\tchar *category_name;\n";
1251 Result += "\tchar *class_name;\n";
1252 Result += "\tstruct _objc_method_list *instance_methods;\n";
1253 Result += "\tstruct _objc_method_list *class_methods;\n";
1254 Result += "\tstruct _objc_protocol_list *protocols;\n";
1255 Result += "\tunsigned int size;\n";
1256 Result += "\tstruct _objc_property_list *instance_properties;\n";
1257 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001258 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001259 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001260 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1261 Result += FullCategoryName;
1262 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1263 Result += IDecl->getName();
1264 Result += "\"\n\t, \"";
1265 Result += ClassDecl->getName();
1266 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001267
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001268 if (IDecl->getNumInstanceMethods() > 0) {
1269 Result += "\t, (struct _objc_method_list *)"
1270 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1271 Result += FullCategoryName;
1272 Result += "\n";
1273 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001274 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001275 Result += "\t, 0\n";
1276 if (IDecl->getNumClassMethods() > 0) {
1277 Result += "\t, (struct _objc_method_list *)"
1278 "&_OBJC_CATEGORY_CLASS_METHODS_";
1279 Result += FullCategoryName;
1280 Result += "\n";
1281 }
1282 else
1283 Result += "\t, 0\n";
1284
1285 if (CDecl->getNumReferencedProtocols() > 0) {
1286 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1287 Result += FullCategoryName;
1288 Result += "\n";
1289 }
1290 else
1291 Result += "\t, 0\n";
1292 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001293}
1294
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001295/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1296/// ivar offset.
1297void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1298 ObjcIvarDecl *ivar,
1299 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001300 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001301 Result += IDecl->getName();
1302 Result += ", ";
1303 Result += ivar->getName();
1304 Result += ")";
1305}
1306
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001307//===----------------------------------------------------------------------===//
1308// Meta Data Emission
1309//===----------------------------------------------------------------------===//
1310
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001311void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1312 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001313 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1314
1315 // Build _objc_ivar_list metadata for classes ivars if needed
1316 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1317 ? IDecl->getImplDeclNumIvars()
1318 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1319
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001320 SynthesizeObjcInternalStruct(CDecl, Result);
1321
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001322 if (NumIvars > 0) {
1323 static bool objc_ivar = false;
1324 if (!objc_ivar) {
1325 /* struct _objc_ivar {
1326 char *ivar_name;
1327 char *ivar_type;
1328 int ivar_offset;
1329 };
1330 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001331 Result += "\nstruct _objc_ivar {\n";
1332 Result += "\tchar *ivar_name;\n";
1333 Result += "\tchar *ivar_type;\n";
1334 Result += "\tint ivar_offset;\n";
1335 Result += "};\n";
1336
1337 /* struct _objc_ivar_list {
1338 int ivar_count;
1339 struct _objc_ivar ivar_list[];
1340 };
1341 */
1342 Result += "\nstruct _objc_ivar_list {\n";
1343 Result += "\tint ivar_count;\n";
1344 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001345 objc_ivar = true;
1346 }
1347
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001348 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1349 Result += IDecl->getName();
1350 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1351 "{\n\t";
1352 Result += utostr(NumIvars);
1353 Result += "\n";
1354
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001355 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1356 ? IDecl->getImplDeclIVars()
1357 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001358 Result += "\t,{{\"";
1359 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001360 Result += "\", \"";
1361 std::string StrEncoding;
1362 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1363 Result += StrEncoding;
1364 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001365 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1366 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001367 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001368 Result += "\t ,{\"";
1369 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001370 Result += "\", \"";
1371 std::string StrEncoding;
1372 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1373 Result += StrEncoding;
1374 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001375 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1376 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001377 }
1378
1379 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001380 }
1381
1382 // Build _objc_method_list for class's instance methods if needed
1383 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1384 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001385 true,
1386 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001387
1388 // Build _objc_method_list for class's class methods if needed
1389 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001390 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001391 false,
1392 "", IDecl->getName(), Result);
1393
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001394 // Protocols referenced in class declaration?
1395 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1396 CDecl->getNumIntfRefProtocols(),
1397 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001398 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001399
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001400
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001401 // Declaration of class/meta-class metadata
1402 /* struct _objc_class {
1403 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001404 const char *super_class_name;
1405 char *name;
1406 long version;
1407 long info;
1408 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001409 struct _objc_ivar_list *ivars;
1410 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001411 struct objc_cache *cache;
1412 struct objc_protocol_list *protocols;
1413 const char *ivar_layout;
1414 struct _objc_class_ext *ext;
1415 };
1416 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001417 static bool objc_class = false;
1418 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001419 Result += "\nstruct _objc_class {\n";
1420 Result += "\tstruct _objc_class *isa;\n";
1421 Result += "\tconst char *super_class_name;\n";
1422 Result += "\tchar *name;\n";
1423 Result += "\tlong version;\n";
1424 Result += "\tlong info;\n";
1425 Result += "\tlong instance_size;\n";
1426 Result += "\tstruct _objc_ivar_list *ivars;\n";
1427 Result += "\tstruct _objc_method_list *methods;\n";
1428 Result += "\tstruct objc_cache *cache;\n";
1429 Result += "\tstruct _objc_protocol_list *protocols;\n";
1430 Result += "\tconst char *ivar_layout;\n";
1431 Result += "\tstruct _objc_class_ext *ext;\n";
1432 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001433 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001434 }
1435
1436 // Meta-class metadata generation.
1437 ObjcInterfaceDecl *RootClass = 0;
1438 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1439 while (SuperClass) {
1440 RootClass = SuperClass;
1441 SuperClass = SuperClass->getSuperClass();
1442 }
1443 SuperClass = CDecl->getSuperClass();
1444
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001445 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1446 Result += CDecl->getName();
1447 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1448 "{\n\t(struct _objc_class *)\"";
1449 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1450 Result += "\"";
1451
1452 if (SuperClass) {
1453 Result += ", \"";
1454 Result += SuperClass->getName();
1455 Result += "\", \"";
1456 Result += CDecl->getName();
1457 Result += "\"";
1458 }
1459 else {
1460 Result += ", 0, \"";
1461 Result += CDecl->getName();
1462 Result += "\"";
1463 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001464 // TODO: 'ivars' field for root class is currently set to 0.
1465 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001466 Result += ", 0,2, sizeof(struct _objc_class), 0";
1467 if (CDecl->getNumClassMethods() > 0) {
1468 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1469 Result += CDecl->getName();
1470 Result += "\n";
1471 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001472 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001473 Result += ", 0\n";
1474 if (CDecl->getNumIntfRefProtocols() > 0) {
1475 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1476 Result += CDecl->getName();
1477 Result += ",0,0\n";
1478 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001479 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001480 Result += "\t,0,0,0,0\n";
1481 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001482
1483 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001484 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1485 Result += CDecl->getName();
1486 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1487 "{\n\t&_OBJC_METACLASS_";
1488 Result += CDecl->getName();
1489 if (SuperClass) {
1490 Result += ", \"";
1491 Result += SuperClass->getName();
1492 Result += "\", \"";
1493 Result += CDecl->getName();
1494 Result += "\"";
1495 }
1496 else {
1497 Result += ", 0, \"";
1498 Result += CDecl->getName();
1499 Result += "\"";
1500 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001501 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001502 Result += ", 0,1";
1503 if (!ObjcSynthesizedStructs.count(CDecl))
1504 Result += ",0";
1505 else {
1506 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001507 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001508 Result += CDecl->getName();
1509 Result += ")";
1510 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001511 if (NumIvars > 0) {
1512 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1513 Result += CDecl->getName();
1514 Result += "\n\t";
1515 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001516 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001517 Result += ",0";
1518 if (IDecl->getNumInstanceMethods() > 0) {
1519 Result += ", &_OBJC_INSTANCE_METHODS_";
1520 Result += CDecl->getName();
1521 Result += ", 0\n\t";
1522 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001523 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001524 Result += ",0,0";
1525 if (CDecl->getNumIntfRefProtocols() > 0) {
1526 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1527 Result += CDecl->getName();
1528 Result += ", 0,0\n";
1529 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001530 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001531 Result += ",0,0,0\n";
1532 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001533}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001534
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001535void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001536 int ClsDefCount = ClassImplementation.size();
1537 int CatDefCount = CategoryImplementation.size();
1538 if (ClsDefCount == 0 && CatDefCount == 0)
1539 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001540
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001541 // TODO: This is temporary until we decide how to access objc types in a
1542 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001543 Result += "#include <Objc/objc.h>\n";
1544 // This is needed for use of offsetof
1545 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001546
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001547 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001548 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001549 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001550
1551 // For each implemented category, write out all its meta data.
1552 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001553 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001554
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001555 // Write objc_symtab metadata
1556 /*
1557 struct _objc_symtab
1558 {
1559 long sel_ref_cnt;
1560 SEL *refs;
1561 short cls_def_cnt;
1562 short cat_def_cnt;
1563 void *defs[cls_def_cnt + cat_def_cnt];
1564 };
1565 */
1566
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001567 Result += "\nstruct _objc_symtab {\n";
1568 Result += "\tlong sel_ref_cnt;\n";
1569 Result += "\tSEL *refs;\n";
1570 Result += "\tshort cls_def_cnt;\n";
1571 Result += "\tshort cat_def_cnt;\n";
1572 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1573 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001574
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001575 Result += "static struct _objc_symtab "
1576 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1577 Result += "\t0, 0, " + utostr(ClsDefCount)
1578 + ", " + utostr(CatDefCount) + "\n";
1579 for (int i = 0; i < ClsDefCount; i++) {
1580 Result += "\t,&_OBJC_CLASS_";
1581 Result += ClassImplementation[i]->getName();
1582 Result += "\n";
1583 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001584
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001585 for (int i = 0; i < CatDefCount; i++) {
1586 Result += "\t,&_OBJC_CATEGORY_";
1587 Result += CategoryImplementation[i]->getClassInterface()->getName();
1588 Result += "_";
1589 Result += CategoryImplementation[i]->getName();
1590 Result += "\n";
1591 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001592
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001593 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001594
1595 // Write objc_module metadata
1596
1597 /*
1598 struct _objc_module {
1599 long version;
1600 long size;
1601 const char *name;
1602 struct _objc_symtab *symtab;
1603 }
1604 */
1605
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001606 Result += "\nstruct _objc_module {\n";
1607 Result += "\tlong version;\n";
1608 Result += "\tlong size;\n";
1609 Result += "\tconst char *name;\n";
1610 Result += "\tstruct _objc_symtab *symtab;\n";
1611 Result += "};\n\n";
1612 Result += "static struct _objc_module "
1613 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001614 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1615 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001616 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001617}
Chris Lattner311ff022007-10-16 22:36:42 +00001618