blob: 7392016021e1dc681d9c793d9316868fb6ce24b7 [file] [log] [blame]
Chris Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000054
Steve Naroff0add5d22007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000058
Steve Naroff764c1ae2007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattnerae43eb72007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenekb3ee1932007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000125
Steve Naroff0744c472007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000128 }
Chris Lattner569faa62007-10-11 18:38:32 +0000129
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +0000147 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000154
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000179
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000183
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000186
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000187 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
189 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000194
195 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
196 int NumProtocols,
197 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000200 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
201 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000202 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
203 ObjcIvarDecl *ivar,
204 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattner258f26c2007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000212
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner569faa62007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffe9780582007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000236 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
237 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000238 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
239 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000240 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
241 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000242 } else if (ObjcForwardProtocolDecl *FP =
243 dyn_cast<ObjcForwardProtocolDecl>(D)){
244 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000245 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000253}
254
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000261
262 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff18c83382007-11-13 23:01:27 +0000269 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000270 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
271 ClassImplementation.push_back(CI);
272 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
273 CategoryImplementation.push_back(CI);
274 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
275 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000277 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000289
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000293
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000306}
307
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner74db1682007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000340
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner569faa62007-10-11 18:38:32 +0000364}
365
366
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
368 int numDecls = ClassDecl->getNumForwardDecls();
369 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
384 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000399}
400
Steve Naroff18c83382007-11-13 23:01:27 +0000401void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000402 for (int i = 0; i < nMethods; i++) {
403 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000404 SourceLocation LocStart = Method->getLocStart();
405 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000406
Steve Narofffbfb46d2007-11-14 14:34:23 +0000407 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
408 Rewrite.InsertText(LocStart, "/* ", 3);
409 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
410 } else {
411 Rewrite.InsertText(LocStart, "// ", 3);
412 }
Steve Naroff667f1682007-10-30 13:30:57 +0000413 }
414}
415
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000416void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
417{
418 for (int i = 0; i < nProperties; i++) {
419 ObjcPropertyDecl *Property = Properties[i];
420 SourceLocation Loc = Property->getLocation();
421
422 Rewrite.ReplaceText(Loc, 0, "// ", 3);
423
424 // FIXME: handle properties that are declared across multiple lines.
425 }
426}
427
Steve Naroff667f1682007-10-30 13:30:57 +0000428void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
429 SourceLocation LocStart = CatDecl->getLocStart();
430
431 // FIXME: handle category headers that are declared across multiple lines.
432 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
433
Steve Naroff18c83382007-11-13 23:01:27 +0000434 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
435 CatDecl->getInstanceMethods());
436 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
437 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000442void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000444
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Steve Naroff18c83382007-11-13 23:01:27 +0000450 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
451 PDecl->getInstanceMethods());
452 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
453 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000454 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000455 SourceLocation LocEnd = PDecl->getAtEndLoc();
456 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000457
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000458 // Must comment out @optional/@required
459 const char *startBuf = SM->getCharacterData(LocStart);
460 const char *endBuf = SM->getCharacterData(LocEnd);
461 for (const char *p = startBuf; p < endBuf; p++) {
462 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
463 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000464 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000465 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
466 CommentedOptional.c_str(), CommentedOptional.size());
467
468 }
469 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
470 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000471 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000472 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
473 CommentedRequired.c_str(), CommentedRequired.size());
474
475 }
476 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000477}
478
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000479void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
480 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000481 if (LocStart.isInvalid())
482 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000483 // FIXME: handle forward protocol that are declared across multiple lines.
484 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
485}
486
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000487void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
488 std::string &ResultStr) {
489 ResultStr += "\nstatic ";
490 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000491 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000492
493 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000494 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000495
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000496 if (OMD->isInstance())
497 NameStr += "_I_";
498 else
499 NameStr += "_C_";
500
501 NameStr += OMD->getClassInterface()->getName();
502 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000503
504 NamedDecl *MethodContext = OMD->getMethodContext();
505 if (ObjcCategoryImplDecl *CID =
506 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000507 NameStr += CID->getName();
508 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000509 }
510 // Append selector names, replacing ':' with '_'
511 const char *selName = OMD->getSelector().getName().c_str();
512 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000513 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000514 else {
515 std::string selString = OMD->getSelector().getName();
516 int len = selString.size();
517 for (int i = 0; i < len; i++)
518 if (selString[i] == ':')
519 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000520 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000521 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000522 // Remember this name for metadata emission
523 MethodInternalNames[OMD] = NameStr;
524 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000525
526 // Rewrite arguments
527 ResultStr += "(";
528
529 // invisible arguments
530 if (OMD->isInstance()) {
531 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
532 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000533 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
534 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000535 ResultStr += selfTy.getAsString();
536 }
537 else
538 ResultStr += Context->getObjcIdType().getAsString();
539
540 ResultStr += " self, ";
541 ResultStr += Context->getObjcSelType().getAsString();
542 ResultStr += " _cmd";
543
544 // Method arguments.
545 for (int i = 0; i < OMD->getNumParams(); i++) {
546 ParmVarDecl *PDecl = OMD->getParamDecl(i);
547 ResultStr += ", ";
548 ResultStr += PDecl->getType().getAsString();
549 ResultStr += " ";
550 ResultStr += PDecl->getName();
551 }
552 ResultStr += ")";
553
554}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000555void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
556 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
557 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000558
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000559 if (IMD)
560 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
561 else
562 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000563
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000564 for (ObjcCategoryImplDecl::instmeth_iterator
565 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
566 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000567 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000568 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000569 RewriteObjcMethodDecl(OMD, ResultStr);
570 SourceLocation LocStart = OMD->getLocStart();
571 SourceLocation LocEnd = OMD->getBody()->getLocStart();
572
573 const char *startBuf = SM->getCharacterData(LocStart);
574 const char *endBuf = SM->getCharacterData(LocEnd);
575 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
576 ResultStr.c_str(), ResultStr.size());
577 }
578
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000579 for (ObjcCategoryImplDecl::classmeth_iterator
580 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
581 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000582 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000583 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000584 RewriteObjcMethodDecl(OMD, ResultStr);
585 SourceLocation LocStart = OMD->getLocStart();
586 SourceLocation LocEnd = OMD->getBody()->getLocStart();
587
588 const char *startBuf = SM->getCharacterData(LocStart);
589 const char *endBuf = SM->getCharacterData(LocEnd);
590 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
591 ResultStr.c_str(), ResultStr.size());
592 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000593 if (IMD)
594 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
595 else
596 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000597}
598
Steve Naroff3774dd92007-10-26 20:53:56 +0000599void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000600 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000601 if (!ObjcForwardDecls.count(ClassDecl)) {
602 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000603 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000604 ResultStr += ClassDecl->getName();
605 ResultStr += "\n";
606 ResultStr += "#define _REWRITER_typedef_";
607 ResultStr += ClassDecl->getName();
608 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000609 ResultStr += "typedef struct ";
610 ResultStr += ClassDecl->getName();
611 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000612 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000613 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000614
615 // Mark this typedef as having been generated.
616 ObjcForwardDecls.insert(ClassDecl);
617 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000618 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
619
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000620 RewriteProperties(ClassDecl->getNumPropertyDecl(),
621 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000622 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
623 ClassDecl->getInstanceMethods());
624 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
625 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000626
Steve Naroff1ccf4632007-10-30 03:43:13 +0000627 // Lastly, comment out the @end.
628 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000629}
630
Steve Naroff6b759ce2007-11-15 02:58:25 +0000631Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
632 ObjcIvarDecl *D = IV->getDecl();
633 if (IV->isFreeIvar()) {
634 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
635 IV->getLocation());
636 Rewrite.ReplaceStmt(IV, Replacement);
637 delete IV;
638 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000639 } else {
640 if (CurMethodDecl) {
641 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
642 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
643 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
644 IdentifierInfo *II = intT->getDecl()->getIdentifier();
645 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
646 II, 0);
647 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
648
649 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
650 // Don't forget the parens to enforce the proper binding.
651 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
652 Rewrite.ReplaceStmt(IV->getBase(), PE);
653 delete IV->getBase();
654 return PE;
655 }
656 }
657 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000658 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000659 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000660}
661
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000662//===----------------------------------------------------------------------===//
663// Function Body / Expression rewriting
664//===----------------------------------------------------------------------===//
665
Steve Naroff334fbc22007-11-09 15:20:18 +0000666Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000667 // Otherwise, just rewrite all children.
668 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
669 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000670 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000671 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000672 if (newStmt)
673 *CI = newStmt;
674 }
Steve Naroffe9780582007-10-23 23:50:29 +0000675
676 // Handle specific things.
677 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
678 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000679
680 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
681 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000682
683 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
684 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000685
686 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
687 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000688
Steve Naroff71226032007-10-24 22:48:43 +0000689 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
690 // Before we rewrite it, put the original message expression in a comment.
691 SourceLocation startLoc = MessExpr->getLocStart();
692 SourceLocation endLoc = MessExpr->getLocEnd();
693
694 const char *startBuf = SM->getCharacterData(startLoc);
695 const char *endBuf = SM->getCharacterData(endLoc);
696
697 std::string messString;
698 messString += "// ";
699 messString.append(startBuf, endBuf-startBuf+1);
700 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000701
Steve Naroff71226032007-10-24 22:48:43 +0000702 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
703 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
704 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000705 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000706 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000707 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000708
709 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
710 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000711
712 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
713 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000714
715 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
716 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000717#if 0
718 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
719 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
720 // Get the new text.
721 std::ostringstream Buf;
722 Replacement->printPretty(Buf);
723 const std::string &Str = Buf.str();
724
725 printf("CAST = %s\n", &Str[0]);
726 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
727 delete S;
728 return Replacement;
729 }
730#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000731 // Return this stmt unmodified.
732 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000733}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000734
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000735Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000736 // Get the start location and compute the semi location.
737 SourceLocation startLoc = S->getLocStart();
738 const char *startBuf = SM->getCharacterData(startLoc);
739
740 assert((*startBuf == '@') && "bogus @try location");
741
742 std::string buf;
743 // declare a new scope with two variables, _stack and _rethrow.
744 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
745 buf += "int buf[18/*32-bit i386*/];\n";
746 buf += "char *pointers[4];} _stack;\n";
747 buf += "id volatile _rethrow = 0;\n";
748 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000749 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000750
751 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
752
753 startLoc = S->getTryBody()->getLocEnd();
754 startBuf = SM->getCharacterData(startLoc);
755
756 assert((*startBuf == '}') && "bogus @try block");
757
758 SourceLocation lastCurlyLoc = startLoc;
759
760 startLoc = startLoc.getFileLocWithOffset(1);
761 buf = " /* @catch begin */ else {\n";
762 buf += " id _caught = objc_exception_extract(&_stack);\n";
763 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000764 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000765 buf += " _rethrow = objc_exception_extract(&_stack);\n";
766 buf += " else { /* @catch continue */";
767
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000768 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000769
770 bool sawIdTypedCatch = false;
771 Stmt *lastCatchBody = 0;
772 ObjcAtCatchStmt *catchList = S->getCatchStmts();
773 while (catchList) {
774 Stmt *catchStmt = catchList->getCatchParamStmt();
775
776 if (catchList == S->getCatchStmts())
777 buf = "if ("; // we are generating code for the first catch clause
778 else
779 buf = "else if (";
780 startLoc = catchList->getLocStart();
781 startBuf = SM->getCharacterData(startLoc);
782
783 assert((*startBuf == '@') && "bogus @catch location");
784
785 const char *lParenLoc = strchr(startBuf, '(');
786
787 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
788 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
789 if (t == Context->getObjcIdType()) {
790 buf += "1) { ";
791 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
792 buf.c_str(), buf.size());
793 sawIdTypedCatch = true;
794 } else if (const PointerType *pType = t->getAsPointerType()) {
795 ObjcInterfaceType *cls; // Should be a pointer to a class.
796
797 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
798 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000799 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000800 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000801 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000802 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
803 buf.c_str(), buf.size());
804 }
805 }
806 // Now rewrite the body...
807 lastCatchBody = catchList->getCatchBody();
808 SourceLocation rParenLoc = catchList->getRParenLoc();
809 SourceLocation bodyLoc = lastCatchBody->getLocStart();
810 const char *bodyBuf = SM->getCharacterData(bodyLoc);
811 const char *rParenBuf = SM->getCharacterData(rParenLoc);
812 assert((*rParenBuf == ')') && "bogus @catch paren location");
813 assert((*bodyBuf == '{') && "bogus @catch body location");
814
815 buf = " = _caught;";
816 // Here we replace ") {" with "= _caught;" (which initializes and
817 // declares the @catch parameter).
818 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
819 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000820 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000821 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000822 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000823 catchList = catchList->getNextCatchStmt();
824 }
825 // Complete the catch list...
826 if (lastCatchBody) {
827 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
828 const char *bodyBuf = SM->getCharacterData(bodyLoc);
829 assert((*bodyBuf == '}') && "bogus @catch body location");
830 bodyLoc = bodyLoc.getFileLocWithOffset(1);
831 buf = " } } /* @catch end */\n";
832
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000833 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000834
835 // Set lastCurlyLoc
836 lastCurlyLoc = lastCatchBody->getLocEnd();
837 }
838 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
839 startLoc = finalStmt->getLocStart();
840 startBuf = SM->getCharacterData(startLoc);
841 assert((*startBuf == '@') && "bogus @finally start");
842
843 buf = "/* @finally */";
844 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
845
846 Stmt *body = finalStmt->getFinallyBody();
847 SourceLocation startLoc = body->getLocStart();
848 SourceLocation endLoc = body->getLocEnd();
849 const char *startBuf = SM->getCharacterData(startLoc);
850 const char *endBuf = SM->getCharacterData(endLoc);
851 assert((*startBuf == '{') && "bogus @finally body location");
852 assert((*endBuf == '}') && "bogus @finally body location");
853
854 startLoc = startLoc.getFileLocWithOffset(1);
855 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000856 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000857 endLoc = endLoc.getFileLocWithOffset(-1);
858 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000859 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000860
861 // Set lastCurlyLoc
862 lastCurlyLoc = body->getLocEnd();
863 }
864 // Now emit the final closing curly brace...
865 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
866 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000867 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000868 return 0;
869}
870
871Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
872 return 0;
873}
874
875Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
876 return 0;
877}
878
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000879// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
880// the throw expression is typically a message expression that's already
881// been rewritten! (which implies the SourceLocation's are invalid).
882Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
883 // Get the start location and compute the semi location.
884 SourceLocation startLoc = S->getLocStart();
885 const char *startBuf = SM->getCharacterData(startLoc);
886
887 assert((*startBuf == '@') && "bogus @throw location");
888
889 std::string buf;
890 /* void objc_exception_throw(id) __attribute__((noreturn)); */
891 buf = "objc_exception_throw(";
892 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
893 const char *semiBuf = strchr(startBuf, ';');
894 assert((*semiBuf == ';') && "@throw: can't find ';'");
895 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
896 buf = ");";
897 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
898 return 0;
899}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000900
Chris Lattner0021f452007-10-24 16:57:36 +0000901Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000902 // Create a new string expression.
903 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000904 std::string StrEncoding;
905 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
906 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
907 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000908 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000909 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
910 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000911 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
912 "rewriter could not replace sub-expression due to macros");
913 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000914 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner217df512007-12-02 01:09:57 +0000915 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000916 return Exp;
917 }
918
Chris Lattner4478db92007-11-30 22:53:43 +0000919 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000920 delete Exp;
921 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000922}
923
Steve Naroff296b74f2007-11-05 14:50:49 +0000924Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
925 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
926 // Create a call to sel_registerName("selName").
927 llvm::SmallVector<Expr*, 8> SelExprs;
928 QualType argType = Context->getPointerType(Context->CharTy);
929 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
930 Exp->getSelector().getName().size(),
931 false, argType, SourceLocation(),
932 SourceLocation()));
933 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
934 &SelExprs[0], SelExprs.size());
935 Rewrite.ReplaceStmt(Exp, SelExp);
936 delete Exp;
937 return SelExp;
938}
939
Steve Naroff71226032007-10-24 22:48:43 +0000940CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
941 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000942 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000943 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000944
945 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000946 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000947
948 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000949 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000950 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
951
952 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000953
Steve Naroff71226032007-10-24 22:48:43 +0000954 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
955}
956
Steve Naroffc8a92d12007-11-01 13:24:47 +0000957static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
958 const char *&startRef, const char *&endRef) {
959 while (startBuf < endBuf) {
960 if (*startBuf == '<')
961 startRef = startBuf; // mark the start.
962 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000963 if (startRef && *startRef == '<') {
964 endRef = startBuf; // mark the end.
965 return true;
966 }
967 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000968 }
969 startBuf++;
970 }
971 return false;
972}
973
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000974static void scanToNextArgument(const char *&argRef) {
975 int angle = 0;
976 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
977 if (*argRef == '<')
978 angle++;
979 else if (*argRef == '>')
980 angle--;
981 argRef++;
982 }
983 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
984}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +0000985
Steve Naroffc8a92d12007-11-01 13:24:47 +0000986bool RewriteTest::needToScanForQualifiers(QualType T) {
987 // FIXME: we don't currently represent "id <Protocol>" in the type system.
988 if (T == Context->getObjcIdType())
989 return true;
990
991 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000992 Type *pointeeType = pType->getPointeeType().getTypePtr();
993 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
994 return true; // we have "Class <Protocol> *".
995 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000996 return false;
997}
998
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000999void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001000 SourceLocation Loc;
1001 QualType Type;
1002 const FunctionTypeProto *proto = 0;
1003 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1004 Loc = VD->getLocation();
1005 Type = VD->getType();
1006 }
1007 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1008 Loc = FD->getLocation();
1009 // Check for ObjC 'id' and class types that have been adorned with protocol
1010 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1011 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1012 assert(funcType && "missing function type");
1013 proto = dyn_cast<FunctionTypeProto>(funcType);
1014 if (!proto)
1015 return;
1016 Type = proto->getResultType();
1017 }
1018 else
1019 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001020
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001021 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001022 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001023
1024 const char *endBuf = SM->getCharacterData(Loc);
1025 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001026 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001027 startBuf--; // scan backward (from the decl location) for return type.
1028 const char *startRef = 0, *endRef = 0;
1029 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1030 // Get the locations of the startRef, endRef.
1031 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1032 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1033 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001034 Rewrite.InsertText(LessLoc, "/*", 2);
1035 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001036 }
1037 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001038 if (!proto)
1039 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001040 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001041 const char *startBuf = SM->getCharacterData(Loc);
1042 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001043 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1044 if (needToScanForQualifiers(proto->getArgType(i))) {
1045 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001046
Steve Naroffc8a92d12007-11-01 13:24:47 +00001047 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001048 // scan forward (from the decl location) for argument types.
1049 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001050 const char *startRef = 0, *endRef = 0;
1051 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1052 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001053 SourceLocation LessLoc =
1054 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1055 SourceLocation GreaterLoc =
1056 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001057 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001058 Rewrite.InsertText(LessLoc, "/*", 2);
1059 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001060 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001061 startBuf = ++endBuf;
1062 }
1063 else {
1064 while (*startBuf != ')' && *startBuf != ',')
1065 startBuf++; // scan forward (from the decl location) for argument types.
1066 startBuf++;
1067 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001068 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001069}
1070
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001071// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1072void RewriteTest::SynthSelGetUidFunctionDecl() {
1073 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1074 llvm::SmallVector<QualType, 16> ArgTys;
1075 ArgTys.push_back(Context->getPointerType(
1076 Context->CharTy.getQualifiedType(QualType::Const)));
1077 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1078 &ArgTys[0], ArgTys.size(),
1079 false /*isVariadic*/);
1080 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1081 SelGetUidIdent, getFuncType,
1082 FunctionDecl::Extern, false, 0);
1083}
1084
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001085// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1086void RewriteTest::SynthGetProtocolFunctionDecl() {
1087 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1088 llvm::SmallVector<QualType, 16> ArgTys;
1089 ArgTys.push_back(Context->getPointerType(
1090 Context->CharTy.getQualifiedType(QualType::Const)));
1091 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1092 &ArgTys[0], ArgTys.size(),
1093 false /*isVariadic*/);
1094 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1095 SelGetProtoIdent, getFuncType,
1096 FunctionDecl::Extern, false, 0);
1097}
1098
Steve Naroff02a82aa2007-10-30 23:14:51 +00001099void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1100 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001101 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001102 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001103 return;
1104 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001105 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001106}
1107
1108// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1109void RewriteTest::SynthMsgSendFunctionDecl() {
1110 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1111 llvm::SmallVector<QualType, 16> ArgTys;
1112 QualType argT = Context->getObjcIdType();
1113 assert(!argT.isNull() && "Can't find 'id' type");
1114 ArgTys.push_back(argT);
1115 argT = Context->getObjcSelType();
1116 assert(!argT.isNull() && "Can't find 'SEL' type");
1117 ArgTys.push_back(argT);
1118 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1119 &ArgTys[0], ArgTys.size(),
1120 true /*isVariadic*/);
1121 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1122 msgSendIdent, msgSendType,
1123 FunctionDecl::Extern, false, 0);
1124}
1125
Steve Naroff764c1ae2007-11-15 10:28:18 +00001126// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1127void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1128 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1129 llvm::SmallVector<QualType, 16> ArgTys;
1130 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1131 &Context->Idents.get("objc_super"), 0);
1132 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1133 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1134 ArgTys.push_back(argT);
1135 argT = Context->getObjcSelType();
1136 assert(!argT.isNull() && "Can't find 'SEL' type");
1137 ArgTys.push_back(argT);
1138 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1139 &ArgTys[0], ArgTys.size(),
1140 true /*isVariadic*/);
1141 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1142 msgSendIdent, msgSendType,
1143 FunctionDecl::Extern, false, 0);
1144}
1145
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001146// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1147void RewriteTest::SynthMsgSendStretFunctionDecl() {
1148 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1149 llvm::SmallVector<QualType, 16> ArgTys;
1150 QualType argT = Context->getObjcIdType();
1151 assert(!argT.isNull() && "Can't find 'id' type");
1152 ArgTys.push_back(argT);
1153 argT = Context->getObjcSelType();
1154 assert(!argT.isNull() && "Can't find 'SEL' type");
1155 ArgTys.push_back(argT);
1156 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1157 &ArgTys[0], ArgTys.size(),
1158 true /*isVariadic*/);
1159 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1160 msgSendIdent, msgSendType,
1161 FunctionDecl::Extern, false, 0);
1162}
1163
1164// SynthMsgSendSuperStretFunctionDecl -
1165// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1166void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1167 IdentifierInfo *msgSendIdent =
1168 &Context->Idents.get("objc_msgSendSuper_stret");
1169 llvm::SmallVector<QualType, 16> ArgTys;
1170 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1171 &Context->Idents.get("objc_super"), 0);
1172 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1173 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1174 ArgTys.push_back(argT);
1175 argT = Context->getObjcSelType();
1176 assert(!argT.isNull() && "Can't find 'SEL' type");
1177 ArgTys.push_back(argT);
1178 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1179 &ArgTys[0], ArgTys.size(),
1180 true /*isVariadic*/);
1181 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1182 msgSendIdent, msgSendType,
1183 FunctionDecl::Extern, false, 0);
1184}
1185
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001186// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1187void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1188 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1189 llvm::SmallVector<QualType, 16> ArgTys;
1190 QualType argT = Context->getObjcIdType();
1191 assert(!argT.isNull() && "Can't find 'id' type");
1192 ArgTys.push_back(argT);
1193 argT = Context->getObjcSelType();
1194 assert(!argT.isNull() && "Can't find 'SEL' type");
1195 ArgTys.push_back(argT);
1196 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1197 &ArgTys[0], ArgTys.size(),
1198 true /*isVariadic*/);
1199 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1200 msgSendIdent, msgSendType,
1201 FunctionDecl::Extern, false, 0);
1202}
1203
Steve Naroff02a82aa2007-10-30 23:14:51 +00001204// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1205void RewriteTest::SynthGetClassFunctionDecl() {
1206 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1207 llvm::SmallVector<QualType, 16> ArgTys;
1208 ArgTys.push_back(Context->getPointerType(
1209 Context->CharTy.getQualifiedType(QualType::Const)));
1210 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1211 &ArgTys[0], ArgTys.size(),
1212 false /*isVariadic*/);
1213 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1214 getClassIdent, getClassType,
1215 FunctionDecl::Extern, false, 0);
1216}
1217
Steve Naroff3b1caac2007-12-07 03:50:46 +00001218// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1219void RewriteTest::SynthGetMetaClassFunctionDecl() {
1220 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1221 llvm::SmallVector<QualType, 16> ArgTys;
1222 ArgTys.push_back(Context->getPointerType(
1223 Context->CharTy.getQualifiedType(QualType::Const)));
1224 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1225 &ArgTys[0], ArgTys.size(),
1226 false /*isVariadic*/);
1227 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1228 getClassIdent, getClassType,
1229 FunctionDecl::Extern, false, 0);
1230}
1231
Steve Naroffabb96362007-11-08 14:30:50 +00001232// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1233void RewriteTest::SynthCFStringFunctionDecl() {
1234 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1235 llvm::SmallVector<QualType, 16> ArgTys;
1236 ArgTys.push_back(Context->getPointerType(
1237 Context->CharTy.getQualifiedType(QualType::Const)));
1238 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1239 &ArgTys[0], ArgTys.size(),
1240 false /*isVariadic*/);
1241 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1242 getClassIdent, getClassType,
1243 FunctionDecl::Extern, false, 0);
1244}
1245
Steve Naroff0add5d22007-11-03 11:27:19 +00001246Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001247#if 1
1248 // This rewrite is specific to GCC, which has builtin support for CFString.
1249 if (!CFStringFunctionDecl)
1250 SynthCFStringFunctionDecl();
1251 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1252 llvm::SmallVector<Expr*, 8> StrExpr;
1253 StrExpr.push_back(Exp->getString());
1254 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1255 &StrExpr[0], StrExpr.size());
1256 // cast to NSConstantString *
1257 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1258 Rewrite.ReplaceStmt(Exp, cast);
1259 delete Exp;
1260 return cast;
1261#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001262 assert(ConstantStringClassReference && "Can't find constant string reference");
1263 llvm::SmallVector<Expr*, 4> InitExprs;
1264
1265 // Synthesize "(Class)&_NSConstantStringClassReference"
1266 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1267 ConstantStringClassReference->getType(),
1268 SourceLocation());
1269 QualType expType = Context->getPointerType(ClsRef->getType());
1270 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1271 expType, SourceLocation());
1272 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1273 SourceLocation());
1274 InitExprs.push_back(cast); // set the 'isa'.
1275 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1276 unsigned IntSize = static_cast<unsigned>(
1277 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1278 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1279 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1280 Exp->getLocStart());
1281 InitExprs.push_back(len); // set "int numBytes".
1282
1283 // struct NSConstantString
1284 QualType CFConstantStrType = Context->getCFConstantStringType();
1285 // (struct NSConstantString) { <exprs from above> }
1286 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1287 &InitExprs[0], InitExprs.size(),
1288 SourceLocation());
1289 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1290 // struct NSConstantString *
1291 expType = Context->getPointerType(StrRep->getType());
1292 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1293 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001294 // cast to NSConstantString *
1295 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001296 Rewrite.ReplaceStmt(Exp, cast);
1297 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001298 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001299#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001300}
1301
Steve Naroff764c1ae2007-11-15 10:28:18 +00001302ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001303 // check if we are sending a message to 'super'
1304 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001305 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1306 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1307 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1308 if (!strcmp(PVD->getName(), "self")) {
1309 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1310 if (ObjcInterfaceType *IT =
1311 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1312 if (IT->getDecl() ==
1313 CurMethodDecl->getClassInterface()->getSuperClass())
1314 return IT->getDecl();
1315 }
1316 }
1317 }
1318 }
1319 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001320 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001321 }
1322 return 0;
1323}
1324
1325// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1326QualType RewriteTest::getSuperStructType() {
1327 if (!SuperStructDecl) {
1328 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1329 &Context->Idents.get("objc_super"), 0);
1330 QualType FieldTypes[2];
1331
1332 // struct objc_object *receiver;
1333 FieldTypes[0] = Context->getObjcIdType();
1334 // struct objc_class *super;
1335 FieldTypes[1] = Context->getObjcClassType();
1336 // Create fields
1337 FieldDecl *FieldDecls[2];
1338
1339 for (unsigned i = 0; i < 2; ++i)
1340 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1341
1342 SuperStructDecl->defineBody(FieldDecls, 4);
1343 }
1344 return Context->getTagDeclType(SuperStructDecl);
1345}
1346
Steve Naroff71226032007-10-24 22:48:43 +00001347Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001348 if (!SelGetUidFunctionDecl)
1349 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001350 if (!MsgSendFunctionDecl)
1351 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001352 if (!MsgSendSuperFunctionDecl)
1353 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001354 if (!MsgSendStretFunctionDecl)
1355 SynthMsgSendStretFunctionDecl();
1356 if (!MsgSendSuperStretFunctionDecl)
1357 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001358 if (!MsgSendFpretFunctionDecl)
1359 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001360 if (!GetClassFunctionDecl)
1361 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001362 if (!GetMetaClassFunctionDecl)
1363 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001364
Steve Naroff764c1ae2007-11-15 10:28:18 +00001365 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001366 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1367 // May need to use objc_msgSend_stret() as well.
1368 FunctionDecl *MsgSendStretFlavor = 0;
1369 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1370 QualType resultType = mDecl->getResultType();
1371 if (resultType.getCanonicalType()->isStructureType()
1372 || resultType.getCanonicalType()->isUnionType())
1373 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001374 else if (resultType.getCanonicalType()->isRealFloatingType())
1375 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001376 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001377
Steve Naroff71226032007-10-24 22:48:43 +00001378 // Synthesize a call to objc_msgSend().
1379 llvm::SmallVector<Expr*, 8> MsgExprs;
1380 IdentifierInfo *clsName = Exp->getClassName();
1381
1382 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1383 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001384 if (!strcmp(clsName->getName(), "super")) {
1385 MsgSendFlavor = MsgSendSuperFunctionDecl;
1386 if (MsgSendStretFlavor)
1387 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1388 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1389
1390 ObjcInterfaceDecl *SuperDecl =
1391 CurMethodDecl->getClassInterface()->getSuperClass();
1392
1393 llvm::SmallVector<Expr*, 4> InitExprs;
1394
1395 // set the receiver to self, the first argument to all methods.
1396 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1397 Context->getObjcIdType(),
1398 SourceLocation()));
1399 llvm::SmallVector<Expr*, 8> ClsExprs;
1400 QualType argType = Context->getPointerType(Context->CharTy);
1401 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1402 SuperDecl->getIdentifier()->getLength(),
1403 false, argType, SourceLocation(),
1404 SourceLocation()));
1405 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1406 &ClsExprs[0],
1407 ClsExprs.size());
1408 // To turn off a warning, type-cast to 'id'
1409 InitExprs.push_back(
1410 new CastExpr(Context->getObjcIdType(),
1411 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1412 // struct objc_super
1413 QualType superType = getSuperStructType();
1414 // (struct objc_super) { <exprs from above> }
1415 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1416 &InitExprs[0], InitExprs.size(),
1417 SourceLocation());
1418 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1419 // struct objc_super *
1420 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1421 Context->getPointerType(SuperRep->getType()),
1422 SourceLocation());
1423 MsgExprs.push_back(Unop);
1424 } else {
1425 llvm::SmallVector<Expr*, 8> ClsExprs;
1426 QualType argType = Context->getPointerType(Context->CharTy);
1427 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1428 clsName->getLength(),
1429 false, argType, SourceLocation(),
1430 SourceLocation()));
1431 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1432 &ClsExprs[0],
1433 ClsExprs.size());
1434 MsgExprs.push_back(Cls);
1435 }
Steve Naroff885e2122007-11-14 23:54:14 +00001436 } else { // instance message.
1437 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001438
Steve Naroff3b1caac2007-12-07 03:50:46 +00001439 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001440 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001441 if (MsgSendStretFlavor)
1442 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001443 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1444
1445 llvm::SmallVector<Expr*, 4> InitExprs;
1446
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001447 InitExprs.push_back(
1448 new CastExpr(Context->getObjcIdType(),
1449 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001450
1451 llvm::SmallVector<Expr*, 8> ClsExprs;
1452 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001453 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1454 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001455 false, argType, SourceLocation(),
1456 SourceLocation()));
1457 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001458 &ClsExprs[0],
1459 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001460 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001461 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001462 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001463 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001464 // struct objc_super
1465 QualType superType = getSuperStructType();
1466 // (struct objc_super) { <exprs from above> }
1467 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1468 &InitExprs[0], InitExprs.size(),
1469 SourceLocation());
1470 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1471 // struct objc_super *
1472 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1473 Context->getPointerType(SuperRep->getType()),
1474 SourceLocation());
1475 MsgExprs.push_back(Unop);
1476 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001477 // Remove all type-casts because it may contain objc-style types; e.g.
1478 // Foo<Proto> *.
1479 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1480 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001481 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1482 MsgExprs.push_back(recExpr);
1483 }
Steve Naroff885e2122007-11-14 23:54:14 +00001484 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001485 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001486 llvm::SmallVector<Expr*, 8> SelExprs;
1487 QualType argType = Context->getPointerType(Context->CharTy);
1488 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1489 Exp->getSelector().getName().size(),
1490 false, argType, SourceLocation(),
1491 SourceLocation()));
1492 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1493 &SelExprs[0], SelExprs.size());
1494 MsgExprs.push_back(SelExp);
1495
1496 // Now push any user supplied arguments.
1497 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001498 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001499 // Make all implicit casts explicit...ICE comes in handy:-)
1500 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1501 // Reuse the ICE type, it is exactly what the doctor ordered.
1502 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1503 }
Steve Naroff885e2122007-11-14 23:54:14 +00001504 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001505 // We've transferred the ownership to MsgExprs. Null out the argument in
1506 // the original expression, since we will delete it below.
1507 Exp->setArg(i, 0);
1508 }
Steve Naroff0744c472007-11-04 22:37:50 +00001509 // Generate the funky cast.
1510 CastExpr *cast;
1511 llvm::SmallVector<QualType, 8> ArgTypes;
1512 QualType returnType;
1513
1514 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001515 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1516 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1517 else
1518 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001519 ArgTypes.push_back(Context->getObjcSelType());
1520 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1521 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001522 for (int i = 0; i < mDecl->getNumParams(); i++) {
1523 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001524 ArgTypes.push_back(t);
1525 }
Steve Naroff0744c472007-11-04 22:37:50 +00001526 returnType = mDecl->getResultType();
1527 } else {
1528 returnType = Context->getObjcIdType();
1529 }
1530 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001531 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001532
1533 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001534 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1535 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001536
1537 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1538 // If we don't do this cast, we get the following bizarre warning/note:
1539 // xx.m:13: warning: function called through a non-compatible type
1540 // xx.m:13: note: if this code is reached, the program will abort
1541 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1542 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001543
Steve Naroff0744c472007-11-04 22:37:50 +00001544 // Now do the "normal" pointer to function cast.
1545 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001546 &ArgTypes[0], ArgTypes.size(),
1547 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001548 castType = Context->getPointerType(castType);
1549 cast = new CastExpr(castType, cast, SourceLocation());
1550
1551 // Don't forget the parens to enforce the proper binding.
1552 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1553
1554 const FunctionType *FT = msgSendType->getAsFunctionType();
1555 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1556 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001557 if (MsgSendStretFlavor) {
1558 // We have the method which returns a struct/union. Must also generate
1559 // call to objc_msgSend_stret and hang both varieties on a conditional
1560 // expression which dictate which one to envoke depending on size of
1561 // method's return type.
1562
1563 // Create a reference to the objc_msgSend_stret() declaration.
1564 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1565 SourceLocation());
1566 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1567 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1568 SourceLocation());
1569 // Now do the "normal" pointer to function cast.
1570 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001571 &ArgTypes[0], ArgTypes.size(),
1572 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001573 castType = Context->getPointerType(castType);
1574 cast = new CastExpr(castType, cast, SourceLocation());
1575
1576 // Don't forget the parens to enforce the proper binding.
1577 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1578
1579 FT = msgSendType->getAsFunctionType();
1580 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1581 FT->getResultType(), SourceLocation());
1582
1583 // Build sizeof(returnType)
1584 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1585 returnType, Context->getSizeType(),
1586 SourceLocation(), SourceLocation());
1587 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1588 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1589 // For X86 it is more complicated and some kind of target specific routine
1590 // is needed to decide what to do.
1591 unsigned IntSize = static_cast<unsigned>(
1592 Context->getTypeSize(Context->IntTy, SourceLocation()));
1593
1594 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1595 Context->IntTy,
1596 SourceLocation());
1597 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1598 BinaryOperator::LE,
1599 Context->IntTy,
1600 SourceLocation());
1601 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1602 ConditionalOperator *CondExpr =
1603 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1604 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1605 // Now do the actual rewrite.
1606 Rewrite.ReplaceStmt(Exp, PE);
1607 delete Exp;
1608 return PE;
1609 }
Steve Naroff71226032007-10-24 22:48:43 +00001610 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001611 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001612
Chris Lattner0021f452007-10-24 16:57:36 +00001613 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001614 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001615}
1616
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001617/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1618/// call to objc_getProtocol("proto-name").
1619Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1620 if (!GetProtocolFunctionDecl)
1621 SynthGetProtocolFunctionDecl();
1622 // Create a call to objc_getProtocol("ProtocolName").
1623 llvm::SmallVector<Expr*, 8> ProtoExprs;
1624 QualType argType = Context->getPointerType(Context->CharTy);
1625 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1626 strlen(Exp->getProtocol()->getName()),
1627 false, argType, SourceLocation(),
1628 SourceLocation()));
1629 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1630 &ProtoExprs[0],
1631 ProtoExprs.size());
1632 Rewrite.ReplaceStmt(Exp, ProtoExp);
1633 delete Exp;
1634 return ProtoExp;
1635
1636}
1637
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001638/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1639/// an objective-c class with ivars.
1640void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1641 std::string &Result) {
1642 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1643 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001644 // Do not synthesize more than once.
1645 if (ObjcSynthesizedStructs.count(CDecl))
1646 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001647 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001648 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001649 SourceLocation LocStart = CDecl->getLocStart();
1650 SourceLocation LocEnd = CDecl->getLocEnd();
1651
1652 const char *startBuf = SM->getCharacterData(LocStart);
1653 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001654 // If no ivars and no root or if its root, directly or indirectly,
1655 // have no ivars (thus not synthesized) then no need to synthesize this class.
1656 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001657 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1658 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1659 Result.c_str(), Result.size());
1660 return;
1661 }
1662
1663 // FIXME: This has potential of causing problem. If
1664 // SynthesizeObjcInternalStruct is ever called recursively.
1665 Result += "\nstruct ";
1666 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001667
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001668 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001669 const char *cursor = strchr(startBuf, '{');
1670 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001671 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001672
1673 // rewrite the original header *without* disturbing the '{'
1674 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1675 Result.c_str(), Result.size());
1676 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1677 Result = "\n struct ";
1678 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001679 // Note: We don't name the field decl. This simplifies the "codegen" for
1680 // accessing a superclasses instance variables (and is similar to what gcc
1681 // does internally). The unnamed struct field feature is enabled with
1682 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1683 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001684 Result += ";\n";
1685
1686 // insert the super class structure definition.
1687 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1688 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1689 }
1690 cursor++; // past '{'
1691
1692 // Now comment out any visibility specifiers.
1693 while (cursor < endBuf) {
1694 if (*cursor == '@') {
1695 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001696 // Skip whitespace.
1697 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1698 /*scan*/;
1699
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001700 // FIXME: presence of @public, etc. inside comment results in
1701 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001702 if (!strncmp(cursor, "public", strlen("public")) ||
1703 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001704 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001705 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001706 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001707 // FIXME: If there are cases where '<' is used in ivar declaration part
1708 // of user code, then scan the ivar list and use needToScanForQualifiers
1709 // for type checking.
1710 else if (*cursor == '<') {
1711 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1712 Rewrite.InsertText(atLoc, "/* ", 3);
1713 cursor = strchr(cursor, '>');
1714 cursor++;
1715 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1716 Rewrite.InsertText(atLoc, " */", 3);
1717 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001718 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001719 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001720 // Don't forget to add a ';'!!
1721 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1722 } else { // we don't have any instance variables - insert super struct.
1723 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1724 Result += " {\n struct ";
1725 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001726 // Note: We don't name the field decl. This simplifies the "codegen" for
1727 // accessing a superclasses instance variables (and is similar to what gcc
1728 // does internally). The unnamed struct field feature is enabled with
1729 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1730 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001731 Result += ";\n};\n";
1732 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1733 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001734 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001735 // Mark this struct as having been generated.
1736 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001737 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001738}
1739
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001740// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1741/// class methods.
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001742void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1743 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001744 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001745 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001746 const char *ClassName,
1747 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001748 if (MethodBegin == MethodEnd) return;
1749
Fariborz Jahanian04455192007-10-22 21:41:37 +00001750 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001751 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001752 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001753 SEL _cmd;
1754 char *method_types;
1755 void *_imp;
1756 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001757 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001758 Result += "\nstruct _objc_method {\n";
1759 Result += "\tSEL _cmd;\n";
1760 Result += "\tchar *method_types;\n";
1761 Result += "\tvoid *_imp;\n";
1762 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001763
1764 /* struct _objc_method_list {
1765 struct _objc_method_list *next_method;
1766 int method_count;
1767 struct _objc_method method_list[];
1768 }
1769 */
1770 Result += "\nstruct _objc_method_list {\n";
1771 Result += "\tstruct _objc_method_list *next_method;\n";
1772 Result += "\tint method_count;\n";
1773 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001774 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001775 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001776
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001777 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001778 Result += "\nstatic struct _objc_method_list _OBJC_";
1779 Result += prefix;
1780 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1781 Result += "_METHODS_";
1782 Result += ClassName;
1783 Result += " __attribute__ ((section (\"__OBJC, __";
1784 Result += IsInstanceMethod ? "inst" : "cls";
1785 Result += "_meth\")))= ";
1786 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001787
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001788 Result += "\t,{{(SEL)\"";
1789 Result += (*MethodBegin)->getSelector().getName().c_str();
1790 std::string MethodTypeString;
1791 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1792 Result += "\", \"";
1793 Result += MethodTypeString;
1794 Result += "\", ";
1795 Result += MethodInternalNames[*MethodBegin];
1796 Result += "}\n";
1797 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1798 Result += "\t ,{(SEL)\"";
1799 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001800 std::string MethodTypeString;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001801 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001802 Result += "\", \"";
1803 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001804 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001805 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001806 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001807 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001808 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001809}
1810
1811/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1812void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1813 int NumProtocols,
1814 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001815 const char *ClassName,
1816 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001817 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001818 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001819 for (int i = 0; i < NumProtocols; i++) {
1820 ObjcProtocolDecl *PDecl = Protocols[i];
1821 // Output struct protocol_methods holder of method selector and type.
1822 if (!objc_protocol_methods &&
1823 (PDecl->getNumInstanceMethods() > 0
1824 || PDecl->getNumClassMethods() > 0)) {
1825 /* struct protocol_methods {
1826 SEL _cmd;
1827 char *method_types;
1828 }
1829 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001830 Result += "\nstruct protocol_methods {\n";
1831 Result += "\tSEL _cmd;\n";
1832 Result += "\tchar *method_types;\n";
1833 Result += "};\n";
1834
1835 /* struct _objc_protocol_method_list {
1836 int protocol_method_count;
1837 struct protocol_methods protocols[];
1838 }
1839 */
1840 Result += "\nstruct _objc_protocol_method_list {\n";
1841 Result += "\tint protocol_method_count;\n";
1842 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001843 objc_protocol_methods = true;
1844 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001845
Fariborz Jahanian04455192007-10-22 21:41:37 +00001846 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001847 int NumMethods = PDecl->getNumInstanceMethods();
1848 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001849 Result += "\nstatic struct _objc_protocol_method_list "
1850 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1851 Result += PDecl->getName();
1852 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1853 "{\n\t" + utostr(NumMethods) + "\n";
1854
Fariborz Jahanian04455192007-10-22 21:41:37 +00001855 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001856 Result += "\t,{{(SEL)\"";
1857 Result += Methods[0]->getSelector().getName().c_str();
1858 Result += "\", \"\"}\n";
1859
1860 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001861 Result += "\t ,{(SEL)\"";
1862 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001863 std::string MethodTypeString;
1864 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1865 Result += "\", \"";
1866 Result += MethodTypeString;
1867 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001868 }
1869 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001870 }
1871
1872 // Output class methods declared in this protocol.
1873 NumMethods = PDecl->getNumClassMethods();
1874 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001875 Result += "\nstatic struct _objc_protocol_method_list "
1876 "_OBJC_PROTOCOL_CLASS_METHODS_";
1877 Result += PDecl->getName();
1878 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1879 "{\n\t";
1880 Result += utostr(NumMethods);
1881 Result += "\n";
1882
Fariborz Jahanian04455192007-10-22 21:41:37 +00001883 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001884 Result += "\t,{{(SEL)\"";
1885 Result += Methods[0]->getSelector().getName().c_str();
1886 Result += "\", \"\"}\n";
1887
1888 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001889 Result += "\t ,{(SEL)\"";
1890 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001891 std::string MethodTypeString;
1892 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1893 Result += "\", \"";
1894 Result += MethodTypeString;
1895 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001896 }
1897 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001898 }
1899 // Output:
1900 /* struct _objc_protocol {
1901 // Objective-C 1.0 extensions
1902 struct _objc_protocol_extension *isa;
1903 char *protocol_name;
1904 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001905 struct _objc_protocol_method_list *instance_methods;
1906 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001907 };
1908 */
1909 static bool objc_protocol = false;
1910 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001911 Result += "\nstruct _objc_protocol {\n";
1912 Result += "\tstruct _objc_protocol_extension *isa;\n";
1913 Result += "\tchar *protocol_name;\n";
1914 Result += "\tstruct _objc_protocol **protocol_list;\n";
1915 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1916 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1917 Result += "};\n";
1918
1919 /* struct _objc_protocol_list {
1920 struct _objc_protocol_list *next;
1921 int protocol_count;
1922 struct _objc_protocol *class_protocols[];
1923 }
1924 */
1925 Result += "\nstruct _objc_protocol_list {\n";
1926 Result += "\tstruct _objc_protocol_list *next;\n";
1927 Result += "\tint protocol_count;\n";
1928 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1929 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001930 objc_protocol = true;
1931 }
1932
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001933 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1934 Result += PDecl->getName();
1935 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1936 "{\n\t0, \"";
1937 Result += PDecl->getName();
1938 Result += "\", 0, ";
1939 if (PDecl->getInstanceMethods() > 0) {
1940 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1941 Result += PDecl->getName();
1942 Result += ", ";
1943 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001944 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001945 Result += "0, ";
1946 if (PDecl->getClassMethods() > 0) {
1947 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1948 Result += PDecl->getName();
1949 Result += "\n";
1950 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001951 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001952 Result += "0\n";
1953 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001954 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001955 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001956 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1957 Result += prefix;
1958 Result += "_PROTOCOLS_";
1959 Result += ClassName;
1960 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1961 "{\n\t0, ";
1962 Result += utostr(NumProtocols);
1963 Result += "\n";
1964
1965 Result += "\t,{&_OBJC_PROTOCOL_";
1966 Result += Protocols[0]->getName();
1967 Result += " \n";
1968
1969 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001970 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001971 Result += "\t ,&_OBJC_PROTOCOL_";
1972 Result += PDecl->getName();
1973 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001974 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001975 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001976 }
1977}
1978
1979/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1980/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001981void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1982 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001983 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1984 // Find category declaration for this implementation.
1985 ObjcCategoryDecl *CDecl;
1986 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1987 CDecl = CDecl->getNextClassCategory())
1988 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1989 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001990
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001991 char *FullCategoryName = (char*)alloca(
1992 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1993 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1994
1995 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001996 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
1997 true, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001998
1999 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002000 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2001 false, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002002
2003 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002004 // Null CDecl is case of a category implementation with no category interface
2005 if (CDecl)
2006 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2007 CDecl->getNumReferencedProtocols(),
2008 "CATEGORY",
2009 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002010
2011 /* struct _objc_category {
2012 char *category_name;
2013 char *class_name;
2014 struct _objc_method_list *instance_methods;
2015 struct _objc_method_list *class_methods;
2016 struct _objc_protocol_list *protocols;
2017 // Objective-C 1.0 extensions
2018 uint32_t size; // sizeof (struct _objc_category)
2019 struct _objc_property_list *instance_properties; // category's own
2020 // @property decl.
2021 };
2022 */
2023
2024 static bool objc_category = false;
2025 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002026 Result += "\nstruct _objc_category {\n";
2027 Result += "\tchar *category_name;\n";
2028 Result += "\tchar *class_name;\n";
2029 Result += "\tstruct _objc_method_list *instance_methods;\n";
2030 Result += "\tstruct _objc_method_list *class_methods;\n";
2031 Result += "\tstruct _objc_protocol_list *protocols;\n";
2032 Result += "\tunsigned int size;\n";
2033 Result += "\tstruct _objc_property_list *instance_properties;\n";
2034 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002035 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002036 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002037 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2038 Result += FullCategoryName;
2039 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2040 Result += IDecl->getName();
2041 Result += "\"\n\t, \"";
2042 Result += ClassDecl->getName();
2043 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002044
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002045 if (IDecl->getNumInstanceMethods() > 0) {
2046 Result += "\t, (struct _objc_method_list *)"
2047 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2048 Result += FullCategoryName;
2049 Result += "\n";
2050 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002051 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002052 Result += "\t, 0\n";
2053 if (IDecl->getNumClassMethods() > 0) {
2054 Result += "\t, (struct _objc_method_list *)"
2055 "&_OBJC_CATEGORY_CLASS_METHODS_";
2056 Result += FullCategoryName;
2057 Result += "\n";
2058 }
2059 else
2060 Result += "\t, 0\n";
2061
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002062 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002063 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2064 Result += FullCategoryName;
2065 Result += "\n";
2066 }
2067 else
2068 Result += "\t, 0\n";
2069 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002070}
2071
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002072/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2073/// ivar offset.
2074void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2075 ObjcIvarDecl *ivar,
2076 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002077 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002078 Result += IDecl->getName();
2079 Result += ", ";
2080 Result += ivar->getName();
2081 Result += ")";
2082}
2083
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002084//===----------------------------------------------------------------------===//
2085// Meta Data Emission
2086//===----------------------------------------------------------------------===//
2087
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002088void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2089 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002090 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2091
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002092 // Explictly declared @interface's are already synthesized.
2093 if (CDecl->ImplicitInterfaceDecl()) {
2094 // FIXME: Implementation of a class with no @interface (legacy) doese not
2095 // produce correct synthesis as yet.
2096 SynthesizeObjcInternalStruct(CDecl, Result);
2097 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002098
Chris Lattnerc7b06752007-12-12 07:56:42 +00002099 // Build _objc_ivar_list metadata for classes ivars if needed
2100 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2101 ? IDecl->getImplDeclNumIvars()
2102 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002103 if (NumIvars > 0) {
2104 static bool objc_ivar = false;
2105 if (!objc_ivar) {
2106 /* struct _objc_ivar {
2107 char *ivar_name;
2108 char *ivar_type;
2109 int ivar_offset;
2110 };
2111 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002112 Result += "\nstruct _objc_ivar {\n";
2113 Result += "\tchar *ivar_name;\n";
2114 Result += "\tchar *ivar_type;\n";
2115 Result += "\tint ivar_offset;\n";
2116 Result += "};\n";
2117
2118 /* struct _objc_ivar_list {
2119 int ivar_count;
2120 struct _objc_ivar ivar_list[];
2121 };
2122 */
2123 Result += "\nstruct _objc_ivar_list {\n";
2124 Result += "\tint ivar_count;\n";
2125 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002126 objc_ivar = true;
2127 }
2128
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002129 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2130 Result += IDecl->getName();
2131 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2132 "{\n\t";
2133 Result += utostr(NumIvars);
2134 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002135
2136 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2137 if (IDecl->getImplDeclNumIvars() > 0) {
2138 IVI = IDecl->ivar_begin();
2139 IVE = IDecl->ivar_end();
2140 } else {
2141 IVI = CDecl->ivar_begin();
2142 IVE = CDecl->ivar_end();
2143 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002144 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002145 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002146 Result += "\", \"";
2147 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002148 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002149 Result += StrEncoding;
2150 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002151 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002152 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002153 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002154 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002155 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002156 Result += "\", \"";
2157 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002158 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002159 Result += StrEncoding;
2160 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002161 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002162 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002163 }
2164
2165 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002166 }
2167
2168 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002169 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2170 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002171
2172 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002173 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2174 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002175
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002176 // Protocols referenced in class declaration?
2177 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2178 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002179 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002180
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002181
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002182 // Declaration of class/meta-class metadata
2183 /* struct _objc_class {
2184 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002185 const char *super_class_name;
2186 char *name;
2187 long version;
2188 long info;
2189 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002190 struct _objc_ivar_list *ivars;
2191 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002192 struct objc_cache *cache;
2193 struct objc_protocol_list *protocols;
2194 const char *ivar_layout;
2195 struct _objc_class_ext *ext;
2196 };
2197 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002198 static bool objc_class = false;
2199 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002200 Result += "\nstruct _objc_class {\n";
2201 Result += "\tstruct _objc_class *isa;\n";
2202 Result += "\tconst char *super_class_name;\n";
2203 Result += "\tchar *name;\n";
2204 Result += "\tlong version;\n";
2205 Result += "\tlong info;\n";
2206 Result += "\tlong instance_size;\n";
2207 Result += "\tstruct _objc_ivar_list *ivars;\n";
2208 Result += "\tstruct _objc_method_list *methods;\n";
2209 Result += "\tstruct objc_cache *cache;\n";
2210 Result += "\tstruct _objc_protocol_list *protocols;\n";
2211 Result += "\tconst char *ivar_layout;\n";
2212 Result += "\tstruct _objc_class_ext *ext;\n";
2213 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002214 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002215 }
2216
2217 // Meta-class metadata generation.
2218 ObjcInterfaceDecl *RootClass = 0;
2219 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2220 while (SuperClass) {
2221 RootClass = SuperClass;
2222 SuperClass = SuperClass->getSuperClass();
2223 }
2224 SuperClass = CDecl->getSuperClass();
2225
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002226 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2227 Result += CDecl->getName();
2228 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2229 "{\n\t(struct _objc_class *)\"";
2230 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2231 Result += "\"";
2232
2233 if (SuperClass) {
2234 Result += ", \"";
2235 Result += SuperClass->getName();
2236 Result += "\", \"";
2237 Result += CDecl->getName();
2238 Result += "\"";
2239 }
2240 else {
2241 Result += ", 0, \"";
2242 Result += CDecl->getName();
2243 Result += "\"";
2244 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002245 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002246 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002247 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002248 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002249 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002250 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002251 Result += "\n";
2252 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002253 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002254 Result += ", 0\n";
2255 if (CDecl->getNumIntfRefProtocols() > 0) {
2256 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2257 Result += CDecl->getName();
2258 Result += ",0,0\n";
2259 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002260 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002261 Result += "\t,0,0,0,0\n";
2262 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002263
2264 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002265 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2266 Result += CDecl->getName();
2267 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2268 "{\n\t&_OBJC_METACLASS_";
2269 Result += CDecl->getName();
2270 if (SuperClass) {
2271 Result += ", \"";
2272 Result += SuperClass->getName();
2273 Result += "\", \"";
2274 Result += CDecl->getName();
2275 Result += "\"";
2276 }
2277 else {
2278 Result += ", 0, \"";
2279 Result += CDecl->getName();
2280 Result += "\"";
2281 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002282 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002283 Result += ", 0,1";
2284 if (!ObjcSynthesizedStructs.count(CDecl))
2285 Result += ",0";
2286 else {
2287 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002288 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002289 Result += CDecl->getName();
2290 Result += ")";
2291 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002292 if (NumIvars > 0) {
2293 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2294 Result += CDecl->getName();
2295 Result += "\n\t";
2296 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002297 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002298 Result += ",0";
2299 if (IDecl->getNumInstanceMethods() > 0) {
2300 Result += ", &_OBJC_INSTANCE_METHODS_";
2301 Result += CDecl->getName();
2302 Result += ", 0\n\t";
2303 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002304 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002305 Result += ",0,0";
2306 if (CDecl->getNumIntfRefProtocols() > 0) {
2307 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2308 Result += CDecl->getName();
2309 Result += ", 0,0\n";
2310 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002311 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002312 Result += ",0,0,0\n";
2313 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002314}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002315
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002316/// RewriteImplementations - This routine rewrites all method implementations
2317/// and emits meta-data.
2318
2319void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002320 int ClsDefCount = ClassImplementation.size();
2321 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002322
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002323 if (ClsDefCount == 0 && CatDefCount == 0)
2324 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002325 // Rewrite implemented methods
2326 for (int i = 0; i < ClsDefCount; i++)
2327 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002328
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002329 for (int i = 0; i < CatDefCount; i++)
2330 RewriteImplementationDecl(CategoryImplementation[i]);
2331
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002332 // This is needed for use of offsetof
2333 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002334
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002335 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002336 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002337 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002338
2339 // For each implemented category, write out all its meta data.
2340 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002341 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002342
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002343 // Write objc_symtab metadata
2344 /*
2345 struct _objc_symtab
2346 {
2347 long sel_ref_cnt;
2348 SEL *refs;
2349 short cls_def_cnt;
2350 short cat_def_cnt;
2351 void *defs[cls_def_cnt + cat_def_cnt];
2352 };
2353 */
2354
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002355 Result += "\nstruct _objc_symtab {\n";
2356 Result += "\tlong sel_ref_cnt;\n";
2357 Result += "\tSEL *refs;\n";
2358 Result += "\tshort cls_def_cnt;\n";
2359 Result += "\tshort cat_def_cnt;\n";
2360 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2361 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002362
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002363 Result += "static struct _objc_symtab "
2364 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2365 Result += "\t0, 0, " + utostr(ClsDefCount)
2366 + ", " + utostr(CatDefCount) + "\n";
2367 for (int i = 0; i < ClsDefCount; i++) {
2368 Result += "\t,&_OBJC_CLASS_";
2369 Result += ClassImplementation[i]->getName();
2370 Result += "\n";
2371 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002372
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002373 for (int i = 0; i < CatDefCount; i++) {
2374 Result += "\t,&_OBJC_CATEGORY_";
2375 Result += CategoryImplementation[i]->getClassInterface()->getName();
2376 Result += "_";
2377 Result += CategoryImplementation[i]->getName();
2378 Result += "\n";
2379 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002380
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002381 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002382
2383 // Write objc_module metadata
2384
2385 /*
2386 struct _objc_module {
2387 long version;
2388 long size;
2389 const char *name;
2390 struct _objc_symtab *symtab;
2391 }
2392 */
2393
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002394 Result += "\nstruct _objc_module {\n";
2395 Result += "\tlong version;\n";
2396 Result += "\tlong size;\n";
2397 Result += "\tconst char *name;\n";
2398 Result += "\tstruct _objc_symtab *symtab;\n";
2399 Result += "};\n\n";
2400 Result += "static struct _objc_module "
2401 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002402 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2403 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002404 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002405
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002406}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002407