blob: 9c845a4473369ed5e12e5ae03b7130a3da6ae43e [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;
67 SM = &Context->SourceMgr;
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
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000090 Rewrite.setSourceMgr(Context->SourceMgr);
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);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000150 void RewriteObjcQualifiedInterfaceTypes(
151 const FunctionTypeProto *proto, FunctionDecl *FD);
152 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000153 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
154 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000155
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000156 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000157 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000158 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000159 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000160 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000161 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000162 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000163 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000164 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
165 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
166 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000167 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000170 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000171 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000172 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000173 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000174 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000175 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000176 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000177 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000178 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000179 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000180
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000181 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000182 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
183 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000184
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000185 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
186 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000187
Steve Naroffb82c50f2007-11-11 17:19:15 +0000188 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000189 int NumMethods,
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)) {
277 if (VD->getInit())
278 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
279 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000280 // Nothing yet.
281}
282
283RewriteTest::~RewriteTest() {
284 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000285
286 // Rewrite tabs if we care.
287 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000288
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000289 // Rewrite Objective-c meta data*
290 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000291 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000292
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000293 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
294 // we are done.
295 if (const RewriteBuffer *RewriteBuf =
296 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000297 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000298 std::string S(RewriteBuf->begin(), RewriteBuf->end());
299 printf("%s\n", S.c_str());
300 } else {
301 printf("No changes\n");
302 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000303 // Emit metadata.
304 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000305}
306
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000307//===----------------------------------------------------------------------===//
308// Syntactic (non-AST) Rewriting Code
309//===----------------------------------------------------------------------===//
310
Chris Lattner74db1682007-10-16 21:07:07 +0000311void RewriteTest::RewriteInclude(SourceLocation Loc) {
312 // Rip up the #include stack to the main file.
313 SourceLocation IncLoc = Loc, NextLoc = Loc;
314 do {
315 IncLoc = Loc;
316 Loc = SM->getLogicalLoc(NextLoc);
317 NextLoc = SM->getIncludeLoc(Loc);
318 } while (!NextLoc.isInvalid());
319
320 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
321 // IncLoc indicates the header that was included if it is useful.
322 IncLoc = SM->getLogicalLoc(IncLoc);
323 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
324 Loc == LastIncLoc)
325 return;
326 LastIncLoc = Loc;
327
328 unsigned IncCol = SM->getColumnNumber(Loc);
329 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
330
331 // Replace the #import with #include.
332 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
333}
334
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000335void RewriteTest::RewriteTabs() {
336 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
337 const char *MainBufStart = MainBuf.first;
338 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000339
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000340 // Loop over the whole file, looking for tabs.
341 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
342 if (*BufPtr != '\t')
343 continue;
344
345 // Okay, we found a tab. This tab will turn into at least one character,
346 // but it depends on which 'virtual column' it is in. Compute that now.
347 unsigned VCol = 0;
348 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
349 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
350 ++VCol;
351
352 // Okay, now that we know the virtual column, we know how many spaces to
353 // insert. We assume 8-character tab-stops.
354 unsigned Spaces = 8-(VCol & 7);
355
356 // Get the location of the tab.
357 SourceLocation TabLoc =
358 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
359
360 // Rewrite the single tab character into a sequence of spaces.
361 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
362 }
Chris Lattner569faa62007-10-11 18:38:32 +0000363}
364
365
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000366void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
367 int numDecls = ClassDecl->getNumForwardDecls();
368 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
369
370 // Get the start location and compute the semi location.
371 SourceLocation startLoc = ClassDecl->getLocation();
372 const char *startBuf = SM->getCharacterData(startLoc);
373 const char *semiPtr = strchr(startBuf, ';');
374
375 // Translate to typedef's that forward reference structs with the same name
376 // as the class. As a convenience, we include the original declaration
377 // as a comment.
378 std::string typedefString;
379 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000380 typedefString.append(startBuf, semiPtr-startBuf+1);
381 typedefString += "\n";
382 for (int i = 0; i < numDecls; i++) {
383 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000384 typedefString += "#ifndef _REWRITER_typedef_";
385 typedefString += ForwardDecl->getName();
386 typedefString += "\n";
387 typedefString += "#define _REWRITER_typedef_";
388 typedefString += ForwardDecl->getName();
389 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000390 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000391 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000392 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000393 }
394
395 // Replace the @class with typedefs corresponding to the classes.
396 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
397 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000398}
399
Steve Naroff18c83382007-11-13 23:01:27 +0000400void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000401 for (int i = 0; i < nMethods; i++) {
402 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000405
Steve Narofffbfb46d2007-11-14 14:34:23 +0000406 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
407 Rewrite.InsertText(LocStart, "/* ", 3);
408 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
409 } else {
410 Rewrite.InsertText(LocStart, "// ", 3);
411 }
Steve Naroff667f1682007-10-30 13:30:57 +0000412 }
413}
414
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000415void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
416{
417 for (int i = 0; i < nProperties; i++) {
418 ObjcPropertyDecl *Property = Properties[i];
419 SourceLocation Loc = Property->getLocation();
420
421 Rewrite.ReplaceText(Loc, 0, "// ", 3);
422
423 // FIXME: handle properties that are declared across multiple lines.
424 }
425}
426
Steve Naroff667f1682007-10-30 13:30:57 +0000427void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
428 SourceLocation LocStart = CatDecl->getLocStart();
429
430 // FIXME: handle category headers that are declared across multiple lines.
431 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
432
Steve Naroff18c83382007-11-13 23:01:27 +0000433 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
434 CatDecl->getInstanceMethods());
435 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
436 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000437 // Lastly, comment out the @end.
438 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
439}
440
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000441void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000442 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000443
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000444 SourceLocation LocStart = PDecl->getLocStart();
445
446 // FIXME: handle protocol headers that are declared across multiple lines.
447 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
448
Steve Naroff18c83382007-11-13 23:01:27 +0000449 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
450 PDecl->getInstanceMethods());
451 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
452 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000453 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000454 SourceLocation LocEnd = PDecl->getAtEndLoc();
455 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000456
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000457 // Must comment out @optional/@required
458 const char *startBuf = SM->getCharacterData(LocStart);
459 const char *endBuf = SM->getCharacterData(LocEnd);
460 for (const char *p = startBuf; p < endBuf; p++) {
461 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
462 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000463 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000464 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
465 CommentedOptional.c_str(), CommentedOptional.size());
466
467 }
468 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
469 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000470 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000471 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
472 CommentedRequired.c_str(), CommentedRequired.size());
473
474 }
475 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000476}
477
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000478void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
479 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000480 if (LocStart.isInvalid())
481 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000482 // FIXME: handle forward protocol that are declared across multiple lines.
483 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
484}
485
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000486void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
487 std::string &ResultStr) {
488 ResultStr += "\nstatic ";
489 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000490 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000491
492 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000493 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000494
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000495 if (OMD->isInstance())
496 NameStr += "_I_";
497 else
498 NameStr += "_C_";
499
500 NameStr += OMD->getClassInterface()->getName();
501 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000502
503 NamedDecl *MethodContext = OMD->getMethodContext();
504 if (ObjcCategoryImplDecl *CID =
505 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000506 NameStr += CID->getName();
507 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000508 }
509 // Append selector names, replacing ':' with '_'
510 const char *selName = OMD->getSelector().getName().c_str();
511 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000512 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000513 else {
514 std::string selString = OMD->getSelector().getName();
515 int len = selString.size();
516 for (int i = 0; i < len; i++)
517 if (selString[i] == ':')
518 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000519 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000520 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000521 // Remember this name for metadata emission
522 MethodInternalNames[OMD] = NameStr;
523 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000524
525 // Rewrite arguments
526 ResultStr += "(";
527
528 // invisible arguments
529 if (OMD->isInstance()) {
530 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
531 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000532 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
533 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000534 ResultStr += selfTy.getAsString();
535 }
536 else
537 ResultStr += Context->getObjcIdType().getAsString();
538
539 ResultStr += " self, ";
540 ResultStr += Context->getObjcSelType().getAsString();
541 ResultStr += " _cmd";
542
543 // Method arguments.
544 for (int i = 0; i < OMD->getNumParams(); i++) {
545 ParmVarDecl *PDecl = OMD->getParamDecl(i);
546 ResultStr += ", ";
547 ResultStr += PDecl->getType().getAsString();
548 ResultStr += " ";
549 ResultStr += PDecl->getName();
550 }
551 ResultStr += ")";
552
553}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000554void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
555 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
556 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000557
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000558 if (IMD)
559 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
560 else
561 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000562
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000563 int numMethods = IMD ? IMD->getNumInstanceMethods()
564 : CID->getNumInstanceMethods();
565
566 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000567 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000568 ObjcMethodDecl *OMD;
569 if (IMD)
570 OMD = IMD->getInstanceMethods()[i];
571 else
572 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000573 RewriteObjcMethodDecl(OMD, ResultStr);
574 SourceLocation LocStart = OMD->getLocStart();
575 SourceLocation LocEnd = OMD->getBody()->getLocStart();
576
577 const char *startBuf = SM->getCharacterData(LocStart);
578 const char *endBuf = SM->getCharacterData(LocEnd);
579 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
580 ResultStr.c_str(), ResultStr.size());
581 }
582
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000583 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
584 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000585 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000586 ObjcMethodDecl *OMD;
587 if (IMD)
588 OMD = IMD->getClassMethods()[i];
589 else
590 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000591 RewriteObjcMethodDecl(OMD, ResultStr);
592 SourceLocation LocStart = OMD->getLocStart();
593 SourceLocation LocEnd = OMD->getBody()->getLocStart();
594
595 const char *startBuf = SM->getCharacterData(LocStart);
596 const char *endBuf = SM->getCharacterData(LocEnd);
597 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
598 ResultStr.c_str(), ResultStr.size());
599 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000600 if (IMD)
601 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
602 else
603 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000604}
605
Steve Naroff3774dd92007-10-26 20:53:56 +0000606void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000607 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000608 if (!ObjcForwardDecls.count(ClassDecl)) {
609 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000610 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000611 ResultStr += ClassDecl->getName();
612 ResultStr += "\n";
613 ResultStr += "#define _REWRITER_typedef_";
614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000616 ResultStr += "typedef struct ";
617 ResultStr += ClassDecl->getName();
618 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000619 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000620 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000621
622 // Mark this typedef as having been generated.
623 ObjcForwardDecls.insert(ClassDecl);
624 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000625 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
626
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000627 RewriteProperties(ClassDecl->getNumPropertyDecl(),
628 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000629 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
630 ClassDecl->getInstanceMethods());
631 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
632 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000633
Steve Naroff1ccf4632007-10-30 03:43:13 +0000634 // Lastly, comment out the @end.
635 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000636}
637
Steve Naroff6b759ce2007-11-15 02:58:25 +0000638Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
639 ObjcIvarDecl *D = IV->getDecl();
640 if (IV->isFreeIvar()) {
641 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
642 IV->getLocation());
643 Rewrite.ReplaceStmt(IV, Replacement);
644 delete IV;
645 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000646 } else {
647 if (CurMethodDecl) {
648 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
649 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
650 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
651 IdentifierInfo *II = intT->getDecl()->getIdentifier();
652 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
653 II, 0);
654 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
655
656 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
657 // Don't forget the parens to enforce the proper binding.
658 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
659 Rewrite.ReplaceStmt(IV->getBase(), PE);
660 delete IV->getBase();
661 return PE;
662 }
663 }
664 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000665 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000666 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000667}
668
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000669//===----------------------------------------------------------------------===//
670// Function Body / Expression rewriting
671//===----------------------------------------------------------------------===//
672
Steve Naroff334fbc22007-11-09 15:20:18 +0000673Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000674 // Otherwise, just rewrite all children.
675 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
676 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000677 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000678 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000679 if (newStmt)
680 *CI = newStmt;
681 }
Steve Naroffe9780582007-10-23 23:50:29 +0000682
683 // Handle specific things.
684 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
685 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000686
687 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
688 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000689
690 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
691 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000692
693 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
694 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000695
Steve Naroff71226032007-10-24 22:48:43 +0000696 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
697 // Before we rewrite it, put the original message expression in a comment.
698 SourceLocation startLoc = MessExpr->getLocStart();
699 SourceLocation endLoc = MessExpr->getLocEnd();
700
701 const char *startBuf = SM->getCharacterData(startLoc);
702 const char *endBuf = SM->getCharacterData(endLoc);
703
704 std::string messString;
705 messString += "// ";
706 messString.append(startBuf, endBuf-startBuf+1);
707 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000708
Steve Naroff71226032007-10-24 22:48:43 +0000709 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
710 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
711 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000712 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000713 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000714 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000715
716 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
717 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000718
719 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
720 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000721
722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
723 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000724#if 0
725 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
726 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
727 // Get the new text.
728 std::ostringstream Buf;
729 Replacement->printPretty(Buf);
730 const std::string &Str = Buf.str();
731
732 printf("CAST = %s\n", &Str[0]);
733 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
734 delete S;
735 return Replacement;
736 }
737#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000738 // Return this stmt unmodified.
739 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000740}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000741
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000742Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000743 // Get the start location and compute the semi location.
744 SourceLocation startLoc = S->getLocStart();
745 const char *startBuf = SM->getCharacterData(startLoc);
746
747 assert((*startBuf == '@') && "bogus @try location");
748
749 std::string buf;
750 // declare a new scope with two variables, _stack and _rethrow.
751 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
752 buf += "int buf[18/*32-bit i386*/];\n";
753 buf += "char *pointers[4];} _stack;\n";
754 buf += "id volatile _rethrow = 0;\n";
755 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000756 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000757
758 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
759
760 startLoc = S->getTryBody()->getLocEnd();
761 startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '}') && "bogus @try block");
764
765 SourceLocation lastCurlyLoc = startLoc;
766
767 startLoc = startLoc.getFileLocWithOffset(1);
768 buf = " /* @catch begin */ else {\n";
769 buf += " id _caught = objc_exception_extract(&_stack);\n";
770 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000771 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000772 buf += " _rethrow = objc_exception_extract(&_stack);\n";
773 buf += " else { /* @catch continue */";
774
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000775 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000776
777 bool sawIdTypedCatch = false;
778 Stmt *lastCatchBody = 0;
779 ObjcAtCatchStmt *catchList = S->getCatchStmts();
780 while (catchList) {
781 Stmt *catchStmt = catchList->getCatchParamStmt();
782
783 if (catchList == S->getCatchStmts())
784 buf = "if ("; // we are generating code for the first catch clause
785 else
786 buf = "else if (";
787 startLoc = catchList->getLocStart();
788 startBuf = SM->getCharacterData(startLoc);
789
790 assert((*startBuf == '@') && "bogus @catch location");
791
792 const char *lParenLoc = strchr(startBuf, '(');
793
794 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
795 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
796 if (t == Context->getObjcIdType()) {
797 buf += "1) { ";
798 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
799 buf.c_str(), buf.size());
800 sawIdTypedCatch = true;
801 } else if (const PointerType *pType = t->getAsPointerType()) {
802 ObjcInterfaceType *cls; // Should be a pointer to a class.
803
804 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
805 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000806 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000807 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000808 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000809 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
810 buf.c_str(), buf.size());
811 }
812 }
813 // Now rewrite the body...
814 lastCatchBody = catchList->getCatchBody();
815 SourceLocation rParenLoc = catchList->getRParenLoc();
816 SourceLocation bodyLoc = lastCatchBody->getLocStart();
817 const char *bodyBuf = SM->getCharacterData(bodyLoc);
818 const char *rParenBuf = SM->getCharacterData(rParenLoc);
819 assert((*rParenBuf == ')') && "bogus @catch paren location");
820 assert((*bodyBuf == '{') && "bogus @catch body location");
821
822 buf = " = _caught;";
823 // Here we replace ") {" with "= _caught;" (which initializes and
824 // declares the @catch parameter).
825 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
826 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000827 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000828 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000829 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000830 catchList = catchList->getNextCatchStmt();
831 }
832 // Complete the catch list...
833 if (lastCatchBody) {
834 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
835 const char *bodyBuf = SM->getCharacterData(bodyLoc);
836 assert((*bodyBuf == '}') && "bogus @catch body location");
837 bodyLoc = bodyLoc.getFileLocWithOffset(1);
838 buf = " } } /* @catch end */\n";
839
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000840 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000841
842 // Set lastCurlyLoc
843 lastCurlyLoc = lastCatchBody->getLocEnd();
844 }
845 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
846 startLoc = finalStmt->getLocStart();
847 startBuf = SM->getCharacterData(startLoc);
848 assert((*startBuf == '@') && "bogus @finally start");
849
850 buf = "/* @finally */";
851 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
852
853 Stmt *body = finalStmt->getFinallyBody();
854 SourceLocation startLoc = body->getLocStart();
855 SourceLocation endLoc = body->getLocEnd();
856 const char *startBuf = SM->getCharacterData(startLoc);
857 const char *endBuf = SM->getCharacterData(endLoc);
858 assert((*startBuf == '{') && "bogus @finally body location");
859 assert((*endBuf == '}') && "bogus @finally body location");
860
861 startLoc = startLoc.getFileLocWithOffset(1);
862 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000863 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000864 endLoc = endLoc.getFileLocWithOffset(-1);
865 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000866 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000867
868 // Set lastCurlyLoc
869 lastCurlyLoc = body->getLocEnd();
870 }
871 // Now emit the final closing curly brace...
872 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
873 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000874 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000875 return 0;
876}
877
878Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
879 return 0;
880}
881
882Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
883 return 0;
884}
885
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000886// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
887// the throw expression is typically a message expression that's already
888// been rewritten! (which implies the SourceLocation's are invalid).
889Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = S->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893
894 assert((*startBuf == '@') && "bogus @throw location");
895
896 std::string buf;
897 /* void objc_exception_throw(id) __attribute__((noreturn)); */
898 buf = "objc_exception_throw(";
899 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
900 const char *semiBuf = strchr(startBuf, ';');
901 assert((*semiBuf == ';') && "@throw: can't find ';'");
902 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
903 buf = ");";
904 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
905 return 0;
906}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000907
Chris Lattner0021f452007-10-24 16:57:36 +0000908Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000909 // Create a new string expression.
910 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000911 std::string StrEncoding;
912 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
913 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
914 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000915 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000916 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
917 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000918 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
919 "rewriter could not replace sub-expression due to macros");
920 SourceRange Range = Exp->getSourceRange();
921 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
922 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000923 return Exp;
924 }
925
Chris Lattner4478db92007-11-30 22:53:43 +0000926 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000927 delete Exp;
928 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000929}
930
Steve Naroff296b74f2007-11-05 14:50:49 +0000931Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
932 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
933 // Create a call to sel_registerName("selName").
934 llvm::SmallVector<Expr*, 8> SelExprs;
935 QualType argType = Context->getPointerType(Context->CharTy);
936 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
937 Exp->getSelector().getName().size(),
938 false, argType, SourceLocation(),
939 SourceLocation()));
940 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
941 &SelExprs[0], SelExprs.size());
942 Rewrite.ReplaceStmt(Exp, SelExp);
943 delete Exp;
944 return SelExp;
945}
946
Steve Naroff71226032007-10-24 22:48:43 +0000947CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
948 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000949 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000950 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000951
952 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000953 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000954
955 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000956 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000957 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
958
959 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000960
Steve Naroff71226032007-10-24 22:48:43 +0000961 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
962}
963
Steve Naroffc8a92d12007-11-01 13:24:47 +0000964static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
965 const char *&startRef, const char *&endRef) {
966 while (startBuf < endBuf) {
967 if (*startBuf == '<')
968 startRef = startBuf; // mark the start.
969 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000970 if (startRef && *startRef == '<') {
971 endRef = startBuf; // mark the end.
972 return true;
973 }
974 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000975 }
976 startBuf++;
977 }
978 return false;
979}
980
981bool RewriteTest::needToScanForQualifiers(QualType T) {
982 // FIXME: we don't currently represent "id <Protocol>" in the type system.
983 if (T == Context->getObjcIdType())
984 return true;
985
986 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000987 Type *pointeeType = pType->getPointeeType().getTypePtr();
988 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
989 return true; // we have "Class <Protocol> *".
990 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000991 return false;
992}
993
994void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
995 const FunctionTypeProto *proto, FunctionDecl *FD) {
996
997 if (needToScanForQualifiers(proto->getResultType())) {
998 // Since types are unique, we need to scan the buffer.
999 SourceLocation Loc = FD->getLocation();
1000
1001 const char *endBuf = SM->getCharacterData(Loc);
1002 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001003 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001004 startBuf--; // scan backward (from the decl location) for return type.
1005 const char *startRef = 0, *endRef = 0;
1006 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1007 // Get the locations of the startRef, endRef.
1008 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1009 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1010 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001011 Rewrite.InsertText(LessLoc, "/*", 2);
1012 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001013 }
1014 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001015 // Now check arguments.
1016 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1017 if (needToScanForQualifiers(proto->getArgType(i))) {
1018 // Since types are unique, we need to scan the buffer.
1019 SourceLocation Loc = FD->getLocation();
1020
1021 const char *startBuf = SM->getCharacterData(Loc);
1022 const char *endBuf = startBuf;
1023 while (*endBuf != ';')
1024 endBuf++; // scan forward (from the decl location) for argument types.
1025 const char *startRef = 0, *endRef = 0;
1026 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1027 // Get the locations of the startRef, endRef.
1028 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1029 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1030 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001031 Rewrite.InsertText(LessLoc, "/*", 2);
1032 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001033 }
1034 }
1035 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001036}
1037
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001038// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1039void RewriteTest::SynthSelGetUidFunctionDecl() {
1040 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1041 llvm::SmallVector<QualType, 16> ArgTys;
1042 ArgTys.push_back(Context->getPointerType(
1043 Context->CharTy.getQualifiedType(QualType::Const)));
1044 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1045 &ArgTys[0], ArgTys.size(),
1046 false /*isVariadic*/);
1047 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1048 SelGetUidIdent, getFuncType,
1049 FunctionDecl::Extern, false, 0);
1050}
1051
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001052// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1053void RewriteTest::SynthGetProtocolFunctionDecl() {
1054 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1055 llvm::SmallVector<QualType, 16> ArgTys;
1056 ArgTys.push_back(Context->getPointerType(
1057 Context->CharTy.getQualifiedType(QualType::Const)));
1058 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1059 &ArgTys[0], ArgTys.size(),
1060 false /*isVariadic*/);
1061 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1062 SelGetProtoIdent, getFuncType,
1063 FunctionDecl::Extern, false, 0);
1064}
1065
Steve Naroff02a82aa2007-10-30 23:14:51 +00001066void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1067 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001068 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001069 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001070 return;
1071 }
1072 // Check for ObjC 'id' and class types that have been adorned with protocol
1073 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1074 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1075 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +00001076 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1077 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001078}
1079
1080// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1081void RewriteTest::SynthMsgSendFunctionDecl() {
1082 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1083 llvm::SmallVector<QualType, 16> ArgTys;
1084 QualType argT = Context->getObjcIdType();
1085 assert(!argT.isNull() && "Can't find 'id' type");
1086 ArgTys.push_back(argT);
1087 argT = Context->getObjcSelType();
1088 assert(!argT.isNull() && "Can't find 'SEL' type");
1089 ArgTys.push_back(argT);
1090 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1091 &ArgTys[0], ArgTys.size(),
1092 true /*isVariadic*/);
1093 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1094 msgSendIdent, msgSendType,
1095 FunctionDecl::Extern, false, 0);
1096}
1097
Steve Naroff764c1ae2007-11-15 10:28:18 +00001098// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1099void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1100 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1101 llvm::SmallVector<QualType, 16> ArgTys;
1102 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1103 &Context->Idents.get("objc_super"), 0);
1104 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1105 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1106 ArgTys.push_back(argT);
1107 argT = Context->getObjcSelType();
1108 assert(!argT.isNull() && "Can't find 'SEL' type");
1109 ArgTys.push_back(argT);
1110 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1111 &ArgTys[0], ArgTys.size(),
1112 true /*isVariadic*/);
1113 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1114 msgSendIdent, msgSendType,
1115 FunctionDecl::Extern, false, 0);
1116}
1117
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001118// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1119void RewriteTest::SynthMsgSendStretFunctionDecl() {
1120 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1121 llvm::SmallVector<QualType, 16> ArgTys;
1122 QualType argT = Context->getObjcIdType();
1123 assert(!argT.isNull() && "Can't find 'id' type");
1124 ArgTys.push_back(argT);
1125 argT = Context->getObjcSelType();
1126 assert(!argT.isNull() && "Can't find 'SEL' type");
1127 ArgTys.push_back(argT);
1128 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1129 &ArgTys[0], ArgTys.size(),
1130 true /*isVariadic*/);
1131 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1132 msgSendIdent, msgSendType,
1133 FunctionDecl::Extern, false, 0);
1134}
1135
1136// SynthMsgSendSuperStretFunctionDecl -
1137// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1138void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1139 IdentifierInfo *msgSendIdent =
1140 &Context->Idents.get("objc_msgSendSuper_stret");
1141 llvm::SmallVector<QualType, 16> ArgTys;
1142 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1143 &Context->Idents.get("objc_super"), 0);
1144 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1145 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1146 ArgTys.push_back(argT);
1147 argT = Context->getObjcSelType();
1148 assert(!argT.isNull() && "Can't find 'SEL' type");
1149 ArgTys.push_back(argT);
1150 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1151 &ArgTys[0], ArgTys.size(),
1152 true /*isVariadic*/);
1153 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1154 msgSendIdent, msgSendType,
1155 FunctionDecl::Extern, false, 0);
1156}
1157
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001158// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1159void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1160 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1161 llvm::SmallVector<QualType, 16> ArgTys;
1162 QualType argT = Context->getObjcIdType();
1163 assert(!argT.isNull() && "Can't find 'id' type");
1164 ArgTys.push_back(argT);
1165 argT = Context->getObjcSelType();
1166 assert(!argT.isNull() && "Can't find 'SEL' type");
1167 ArgTys.push_back(argT);
1168 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1169 &ArgTys[0], ArgTys.size(),
1170 true /*isVariadic*/);
1171 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1172 msgSendIdent, msgSendType,
1173 FunctionDecl::Extern, false, 0);
1174}
1175
Steve Naroff02a82aa2007-10-30 23:14:51 +00001176// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1177void RewriteTest::SynthGetClassFunctionDecl() {
1178 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1179 llvm::SmallVector<QualType, 16> ArgTys;
1180 ArgTys.push_back(Context->getPointerType(
1181 Context->CharTy.getQualifiedType(QualType::Const)));
1182 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1183 &ArgTys[0], ArgTys.size(),
1184 false /*isVariadic*/);
1185 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1186 getClassIdent, getClassType,
1187 FunctionDecl::Extern, false, 0);
1188}
1189
Steve Naroff3b1caac2007-12-07 03:50:46 +00001190// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1191void RewriteTest::SynthGetMetaClassFunctionDecl() {
1192 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1193 llvm::SmallVector<QualType, 16> ArgTys;
1194 ArgTys.push_back(Context->getPointerType(
1195 Context->CharTy.getQualifiedType(QualType::Const)));
1196 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1197 &ArgTys[0], ArgTys.size(),
1198 false /*isVariadic*/);
1199 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1200 getClassIdent, getClassType,
1201 FunctionDecl::Extern, false, 0);
1202}
1203
Steve Naroffabb96362007-11-08 14:30:50 +00001204// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1205void RewriteTest::SynthCFStringFunctionDecl() {
1206 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
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 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1214 getClassIdent, getClassType,
1215 FunctionDecl::Extern, false, 0);
1216}
1217
Steve Naroff0add5d22007-11-03 11:27:19 +00001218Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001219#if 1
1220 // This rewrite is specific to GCC, which has builtin support for CFString.
1221 if (!CFStringFunctionDecl)
1222 SynthCFStringFunctionDecl();
1223 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1224 llvm::SmallVector<Expr*, 8> StrExpr;
1225 StrExpr.push_back(Exp->getString());
1226 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1227 &StrExpr[0], StrExpr.size());
1228 // cast to NSConstantString *
1229 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1230 Rewrite.ReplaceStmt(Exp, cast);
1231 delete Exp;
1232 return cast;
1233#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001234 assert(ConstantStringClassReference && "Can't find constant string reference");
1235 llvm::SmallVector<Expr*, 4> InitExprs;
1236
1237 // Synthesize "(Class)&_NSConstantStringClassReference"
1238 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1239 ConstantStringClassReference->getType(),
1240 SourceLocation());
1241 QualType expType = Context->getPointerType(ClsRef->getType());
1242 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1243 expType, SourceLocation());
1244 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1245 SourceLocation());
1246 InitExprs.push_back(cast); // set the 'isa'.
1247 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1248 unsigned IntSize = static_cast<unsigned>(
1249 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1250 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1251 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1252 Exp->getLocStart());
1253 InitExprs.push_back(len); // set "int numBytes".
1254
1255 // struct NSConstantString
1256 QualType CFConstantStrType = Context->getCFConstantStringType();
1257 // (struct NSConstantString) { <exprs from above> }
1258 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1259 &InitExprs[0], InitExprs.size(),
1260 SourceLocation());
1261 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1262 // struct NSConstantString *
1263 expType = Context->getPointerType(StrRep->getType());
1264 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1265 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001266 // cast to NSConstantString *
1267 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001268 Rewrite.ReplaceStmt(Exp, cast);
1269 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001270 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001271#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001272}
1273
Steve Naroff764c1ae2007-11-15 10:28:18 +00001274ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001275 // check if we are sending a message to 'super'
1276 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001277 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1278 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1279 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1280 if (!strcmp(PVD->getName(), "self")) {
1281 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1282 if (ObjcInterfaceType *IT =
1283 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1284 if (IT->getDecl() ==
1285 CurMethodDecl->getClassInterface()->getSuperClass())
1286 return IT->getDecl();
1287 }
1288 }
1289 }
1290 }
1291 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001292 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001293 }
1294 return 0;
1295}
1296
1297// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1298QualType RewriteTest::getSuperStructType() {
1299 if (!SuperStructDecl) {
1300 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1301 &Context->Idents.get("objc_super"), 0);
1302 QualType FieldTypes[2];
1303
1304 // struct objc_object *receiver;
1305 FieldTypes[0] = Context->getObjcIdType();
1306 // struct objc_class *super;
1307 FieldTypes[1] = Context->getObjcClassType();
1308 // Create fields
1309 FieldDecl *FieldDecls[2];
1310
1311 for (unsigned i = 0; i < 2; ++i)
1312 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1313
1314 SuperStructDecl->defineBody(FieldDecls, 4);
1315 }
1316 return Context->getTagDeclType(SuperStructDecl);
1317}
1318
Steve Naroff71226032007-10-24 22:48:43 +00001319Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001320 if (!SelGetUidFunctionDecl)
1321 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001322 if (!MsgSendFunctionDecl)
1323 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001324 if (!MsgSendSuperFunctionDecl)
1325 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001326 if (!MsgSendStretFunctionDecl)
1327 SynthMsgSendStretFunctionDecl();
1328 if (!MsgSendSuperStretFunctionDecl)
1329 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001330 if (!MsgSendFpretFunctionDecl)
1331 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001332 if (!GetClassFunctionDecl)
1333 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001334 if (!GetMetaClassFunctionDecl)
1335 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001336
Steve Naroff764c1ae2007-11-15 10:28:18 +00001337 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001338 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1339 // May need to use objc_msgSend_stret() as well.
1340 FunctionDecl *MsgSendStretFlavor = 0;
1341 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1342 QualType resultType = mDecl->getResultType();
1343 if (resultType.getCanonicalType()->isStructureType()
1344 || resultType.getCanonicalType()->isUnionType())
1345 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001346 else if (resultType.getCanonicalType()->isRealFloatingType())
1347 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001348 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001349
Steve Naroff71226032007-10-24 22:48:43 +00001350 // Synthesize a call to objc_msgSend().
1351 llvm::SmallVector<Expr*, 8> MsgExprs;
1352 IdentifierInfo *clsName = Exp->getClassName();
1353
1354 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1355 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001356 if (!strcmp(clsName->getName(), "super")) {
1357 MsgSendFlavor = MsgSendSuperFunctionDecl;
1358 if (MsgSendStretFlavor)
1359 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1360 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1361
1362 ObjcInterfaceDecl *SuperDecl =
1363 CurMethodDecl->getClassInterface()->getSuperClass();
1364
1365 llvm::SmallVector<Expr*, 4> InitExprs;
1366
1367 // set the receiver to self, the first argument to all methods.
1368 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1369 Context->getObjcIdType(),
1370 SourceLocation()));
1371 llvm::SmallVector<Expr*, 8> ClsExprs;
1372 QualType argType = Context->getPointerType(Context->CharTy);
1373 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1374 SuperDecl->getIdentifier()->getLength(),
1375 false, argType, SourceLocation(),
1376 SourceLocation()));
1377 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1378 &ClsExprs[0],
1379 ClsExprs.size());
1380 // To turn off a warning, type-cast to 'id'
1381 InitExprs.push_back(
1382 new CastExpr(Context->getObjcIdType(),
1383 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1384 // struct objc_super
1385 QualType superType = getSuperStructType();
1386 // (struct objc_super) { <exprs from above> }
1387 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1388 &InitExprs[0], InitExprs.size(),
1389 SourceLocation());
1390 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1391 // struct objc_super *
1392 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1393 Context->getPointerType(SuperRep->getType()),
1394 SourceLocation());
1395 MsgExprs.push_back(Unop);
1396 } else {
1397 llvm::SmallVector<Expr*, 8> ClsExprs;
1398 QualType argType = Context->getPointerType(Context->CharTy);
1399 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1400 clsName->getLength(),
1401 false, argType, SourceLocation(),
1402 SourceLocation()));
1403 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1404 &ClsExprs[0],
1405 ClsExprs.size());
1406 MsgExprs.push_back(Cls);
1407 }
Steve Naroff885e2122007-11-14 23:54:14 +00001408 } else { // instance message.
1409 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001410
Steve Naroff3b1caac2007-12-07 03:50:46 +00001411 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001412 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001413 if (MsgSendStretFlavor)
1414 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001415 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1416
1417 llvm::SmallVector<Expr*, 4> InitExprs;
1418
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001419 InitExprs.push_back(
1420 new CastExpr(Context->getObjcIdType(),
1421 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001422
1423 llvm::SmallVector<Expr*, 8> ClsExprs;
1424 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001425 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1426 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001427 false, argType, SourceLocation(),
1428 SourceLocation()));
1429 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001430 &ClsExprs[0],
1431 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001432 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001433 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001434 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001435 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001436 // struct objc_super
1437 QualType superType = getSuperStructType();
1438 // (struct objc_super) { <exprs from above> }
1439 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1440 &InitExprs[0], InitExprs.size(),
1441 SourceLocation());
1442 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1443 // struct objc_super *
1444 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1445 Context->getPointerType(SuperRep->getType()),
1446 SourceLocation());
1447 MsgExprs.push_back(Unop);
1448 } else {
1449 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1450 MsgExprs.push_back(recExpr);
1451 }
Steve Naroff885e2122007-11-14 23:54:14 +00001452 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001453 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001454 llvm::SmallVector<Expr*, 8> SelExprs;
1455 QualType argType = Context->getPointerType(Context->CharTy);
1456 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1457 Exp->getSelector().getName().size(),
1458 false, argType, SourceLocation(),
1459 SourceLocation()));
1460 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1461 &SelExprs[0], SelExprs.size());
1462 MsgExprs.push_back(SelExp);
1463
1464 // Now push any user supplied arguments.
1465 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001466 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001467 // Make all implicit casts explicit...ICE comes in handy:-)
1468 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1469 // Reuse the ICE type, it is exactly what the doctor ordered.
1470 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1471 }
Steve Naroff885e2122007-11-14 23:54:14 +00001472 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001473 // We've transferred the ownership to MsgExprs. Null out the argument in
1474 // the original expression, since we will delete it below.
1475 Exp->setArg(i, 0);
1476 }
Steve Naroff0744c472007-11-04 22:37:50 +00001477 // Generate the funky cast.
1478 CastExpr *cast;
1479 llvm::SmallVector<QualType, 8> ArgTypes;
1480 QualType returnType;
1481
1482 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001483 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1484 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1485 else
1486 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001487 ArgTypes.push_back(Context->getObjcSelType());
1488 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1489 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001490 for (int i = 0; i < mDecl->getNumParams(); i++) {
1491 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001492 ArgTypes.push_back(t);
1493 }
Steve Naroff0744c472007-11-04 22:37:50 +00001494 returnType = mDecl->getResultType();
1495 } else {
1496 returnType = Context->getObjcIdType();
1497 }
1498 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001499 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001500
1501 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001502 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1503 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001504
1505 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1506 // If we don't do this cast, we get the following bizarre warning/note:
1507 // xx.m:13: warning: function called through a non-compatible type
1508 // xx.m:13: note: if this code is reached, the program will abort
1509 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1510 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001511
Steve Naroff0744c472007-11-04 22:37:50 +00001512 // Now do the "normal" pointer to function cast.
1513 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001514 &ArgTypes[0], ArgTypes.size(),
1515 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001516 castType = Context->getPointerType(castType);
1517 cast = new CastExpr(castType, cast, SourceLocation());
1518
1519 // Don't forget the parens to enforce the proper binding.
1520 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1521
1522 const FunctionType *FT = msgSendType->getAsFunctionType();
1523 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1524 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001525 if (MsgSendStretFlavor) {
1526 // We have the method which returns a struct/union. Must also generate
1527 // call to objc_msgSend_stret and hang both varieties on a conditional
1528 // expression which dictate which one to envoke depending on size of
1529 // method's return type.
1530
1531 // Create a reference to the objc_msgSend_stret() declaration.
1532 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1533 SourceLocation());
1534 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1535 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1536 SourceLocation());
1537 // Now do the "normal" pointer to function cast.
1538 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001539 &ArgTypes[0], ArgTypes.size(),
1540 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001541 castType = Context->getPointerType(castType);
1542 cast = new CastExpr(castType, cast, SourceLocation());
1543
1544 // Don't forget the parens to enforce the proper binding.
1545 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1546
1547 FT = msgSendType->getAsFunctionType();
1548 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1549 FT->getResultType(), SourceLocation());
1550
1551 // Build sizeof(returnType)
1552 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1553 returnType, Context->getSizeType(),
1554 SourceLocation(), SourceLocation());
1555 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1556 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1557 // For X86 it is more complicated and some kind of target specific routine
1558 // is needed to decide what to do.
1559 unsigned IntSize = static_cast<unsigned>(
1560 Context->getTypeSize(Context->IntTy, SourceLocation()));
1561
1562 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1563 Context->IntTy,
1564 SourceLocation());
1565 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1566 BinaryOperator::LE,
1567 Context->IntTy,
1568 SourceLocation());
1569 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1570 ConditionalOperator *CondExpr =
1571 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1572 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1573 // Now do the actual rewrite.
1574 Rewrite.ReplaceStmt(Exp, PE);
1575 delete Exp;
1576 return PE;
1577 }
Steve Naroff71226032007-10-24 22:48:43 +00001578 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001579 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001580
Chris Lattner0021f452007-10-24 16:57:36 +00001581 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001582 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001583}
1584
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001585/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1586/// call to objc_getProtocol("proto-name").
1587Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1588 if (!GetProtocolFunctionDecl)
1589 SynthGetProtocolFunctionDecl();
1590 // Create a call to objc_getProtocol("ProtocolName").
1591 llvm::SmallVector<Expr*, 8> ProtoExprs;
1592 QualType argType = Context->getPointerType(Context->CharTy);
1593 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1594 strlen(Exp->getProtocol()->getName()),
1595 false, argType, SourceLocation(),
1596 SourceLocation()));
1597 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1598 &ProtoExprs[0],
1599 ProtoExprs.size());
1600 Rewrite.ReplaceStmt(Exp, ProtoExp);
1601 delete Exp;
1602 return ProtoExp;
1603
1604}
1605
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001606/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1607/// an objective-c class with ivars.
1608void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1609 std::string &Result) {
1610 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1611 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001612 // Do not synthesize more than once.
1613 if (ObjcSynthesizedStructs.count(CDecl))
1614 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001615 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001616 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001617 SourceLocation LocStart = CDecl->getLocStart();
1618 SourceLocation LocEnd = CDecl->getLocEnd();
1619
1620 const char *startBuf = SM->getCharacterData(LocStart);
1621 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001622 // If no ivars and no root or if its root, directly or indirectly,
1623 // have no ivars (thus not synthesized) then no need to synthesize this class.
1624 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001625 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1626 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1627 Result.c_str(), Result.size());
1628 return;
1629 }
1630
1631 // FIXME: This has potential of causing problem. If
1632 // SynthesizeObjcInternalStruct is ever called recursively.
1633 Result += "\nstruct ";
1634 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001635
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001636 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001637 const char *cursor = strchr(startBuf, '{');
1638 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001639 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001640
1641 // rewrite the original header *without* disturbing the '{'
1642 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1643 Result.c_str(), Result.size());
1644 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1645 Result = "\n struct ";
1646 Result += RCDecl->getName();
1647 Result += " _";
1648 Result += RCDecl->getName();
1649 Result += ";\n";
1650
1651 // insert the super class structure definition.
1652 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1653 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1654 }
1655 cursor++; // past '{'
1656
1657 // Now comment out any visibility specifiers.
1658 while (cursor < endBuf) {
1659 if (*cursor == '@') {
1660 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001661 // Skip whitespace.
1662 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1663 /*scan*/;
1664
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001665 // FIXME: presence of @public, etc. inside comment results in
1666 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001667 if (!strncmp(cursor, "public", strlen("public")) ||
1668 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001669 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001670 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001671 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001672 // FIXME: If there are cases where '<' is used in ivar declaration part
1673 // of user code, then scan the ivar list and use needToScanForQualifiers
1674 // for type checking.
1675 else if (*cursor == '<') {
1676 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1677 Rewrite.InsertText(atLoc, "/* ", 3);
1678 cursor = strchr(cursor, '>');
1679 cursor++;
1680 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1681 Rewrite.InsertText(atLoc, " */", 3);
1682 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001683 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001684 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001685 // Don't forget to add a ';'!!
1686 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1687 } else { // we don't have any instance variables - insert super struct.
1688 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1689 Result += " {\n struct ";
1690 Result += RCDecl->getName();
1691 Result += " _";
1692 Result += RCDecl->getName();
1693 Result += ";\n};\n";
1694 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1695 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001696 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001697 // Mark this struct as having been generated.
1698 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001699 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001700}
1701
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001702// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1703/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001704void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001705 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001706 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001707 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001708 const char *ClassName,
1709 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001710 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001711 if (NumMethods > 0 && !objc_impl_method) {
1712 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001713 SEL _cmd;
1714 char *method_types;
1715 void *_imp;
1716 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001717 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001718 Result += "\nstruct _objc_method {\n";
1719 Result += "\tSEL _cmd;\n";
1720 Result += "\tchar *method_types;\n";
1721 Result += "\tvoid *_imp;\n";
1722 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001723
1724 /* struct _objc_method_list {
1725 struct _objc_method_list *next_method;
1726 int method_count;
1727 struct _objc_method method_list[];
1728 }
1729 */
1730 Result += "\nstruct _objc_method_list {\n";
1731 Result += "\tstruct _objc_method_list *next_method;\n";
1732 Result += "\tint method_count;\n";
1733 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001734 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001735 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001736 // Build _objc_method_list for class's methods if needed
1737 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001738 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001739 Result += prefix;
1740 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1741 Result += "_METHODS_";
1742 Result += ClassName;
1743 Result += " __attribute__ ((section (\"__OBJC, __";
1744 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001745 Result += "_meth\")))= ";
1746 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1747
1748 Result += "\t,{{(SEL)\"";
1749 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001750 std::string MethodTypeString;
1751 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1752 Result += "\", \"";
1753 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001754 Result += "\", ";
1755 Result += MethodInternalNames[Methods[0]];
1756 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001757 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001758 Result += "\t ,{(SEL)\"";
1759 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001760 std::string MethodTypeString;
1761 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1762 Result += "\", \"";
1763 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001764 Result += "\", ";
1765 Result += MethodInternalNames[Methods[i]];
1766 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001767 }
1768 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001769 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001770}
1771
1772/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1773void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1774 int NumProtocols,
1775 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001776 const char *ClassName,
1777 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001778 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001779 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001780 for (int i = 0; i < NumProtocols; i++) {
1781 ObjcProtocolDecl *PDecl = Protocols[i];
1782 // Output struct protocol_methods holder of method selector and type.
1783 if (!objc_protocol_methods &&
1784 (PDecl->getNumInstanceMethods() > 0
1785 || PDecl->getNumClassMethods() > 0)) {
1786 /* struct protocol_methods {
1787 SEL _cmd;
1788 char *method_types;
1789 }
1790 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001791 Result += "\nstruct protocol_methods {\n";
1792 Result += "\tSEL _cmd;\n";
1793 Result += "\tchar *method_types;\n";
1794 Result += "};\n";
1795
1796 /* struct _objc_protocol_method_list {
1797 int protocol_method_count;
1798 struct protocol_methods protocols[];
1799 }
1800 */
1801 Result += "\nstruct _objc_protocol_method_list {\n";
1802 Result += "\tint protocol_method_count;\n";
1803 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001804 objc_protocol_methods = true;
1805 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001806
Fariborz Jahanian04455192007-10-22 21:41:37 +00001807 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001808 int NumMethods = PDecl->getNumInstanceMethods();
1809 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001810 Result += "\nstatic struct _objc_protocol_method_list "
1811 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1812 Result += PDecl->getName();
1813 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1814 "{\n\t" + utostr(NumMethods) + "\n";
1815
Fariborz Jahanian04455192007-10-22 21:41:37 +00001816 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001817 Result += "\t,{{(SEL)\"";
1818 Result += Methods[0]->getSelector().getName().c_str();
1819 Result += "\", \"\"}\n";
1820
1821 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001822 Result += "\t ,{(SEL)\"";
1823 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001824 std::string MethodTypeString;
1825 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1826 Result += "\", \"";
1827 Result += MethodTypeString;
1828 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001829 }
1830 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001831 }
1832
1833 // Output class methods declared in this protocol.
1834 NumMethods = PDecl->getNumClassMethods();
1835 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001836 Result += "\nstatic struct _objc_protocol_method_list "
1837 "_OBJC_PROTOCOL_CLASS_METHODS_";
1838 Result += PDecl->getName();
1839 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1840 "{\n\t";
1841 Result += utostr(NumMethods);
1842 Result += "\n";
1843
Fariborz Jahanian04455192007-10-22 21:41:37 +00001844 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001845 Result += "\t,{{(SEL)\"";
1846 Result += Methods[0]->getSelector().getName().c_str();
1847 Result += "\", \"\"}\n";
1848
1849 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001850 Result += "\t ,{(SEL)\"";
1851 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001852 std::string MethodTypeString;
1853 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1854 Result += "\", \"";
1855 Result += MethodTypeString;
1856 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001857 }
1858 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001859 }
1860 // Output:
1861 /* struct _objc_protocol {
1862 // Objective-C 1.0 extensions
1863 struct _objc_protocol_extension *isa;
1864 char *protocol_name;
1865 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001866 struct _objc_protocol_method_list *instance_methods;
1867 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001868 };
1869 */
1870 static bool objc_protocol = false;
1871 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001872 Result += "\nstruct _objc_protocol {\n";
1873 Result += "\tstruct _objc_protocol_extension *isa;\n";
1874 Result += "\tchar *protocol_name;\n";
1875 Result += "\tstruct _objc_protocol **protocol_list;\n";
1876 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1877 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1878 Result += "};\n";
1879
1880 /* struct _objc_protocol_list {
1881 struct _objc_protocol_list *next;
1882 int protocol_count;
1883 struct _objc_protocol *class_protocols[];
1884 }
1885 */
1886 Result += "\nstruct _objc_protocol_list {\n";
1887 Result += "\tstruct _objc_protocol_list *next;\n";
1888 Result += "\tint protocol_count;\n";
1889 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1890 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001891 objc_protocol = true;
1892 }
1893
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001894 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1895 Result += PDecl->getName();
1896 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1897 "{\n\t0, \"";
1898 Result += PDecl->getName();
1899 Result += "\", 0, ";
1900 if (PDecl->getInstanceMethods() > 0) {
1901 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1902 Result += PDecl->getName();
1903 Result += ", ";
1904 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001905 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001906 Result += "0, ";
1907 if (PDecl->getClassMethods() > 0) {
1908 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1909 Result += PDecl->getName();
1910 Result += "\n";
1911 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001912 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001913 Result += "0\n";
1914 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001915 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001916 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001917 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1918 Result += prefix;
1919 Result += "_PROTOCOLS_";
1920 Result += ClassName;
1921 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1922 "{\n\t0, ";
1923 Result += utostr(NumProtocols);
1924 Result += "\n";
1925
1926 Result += "\t,{&_OBJC_PROTOCOL_";
1927 Result += Protocols[0]->getName();
1928 Result += " \n";
1929
1930 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001931 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001932 Result += "\t ,&_OBJC_PROTOCOL_";
1933 Result += PDecl->getName();
1934 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001935 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001936 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001937 }
1938}
1939
1940/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1941/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001942void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1943 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001944 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1945 // Find category declaration for this implementation.
1946 ObjcCategoryDecl *CDecl;
1947 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1948 CDecl = CDecl->getNextClassCategory())
1949 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1950 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001951
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001952 char *FullCategoryName = (char*)alloca(
1953 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1954 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1955
1956 // Build _objc_method_list for class's instance methods if needed
1957 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1958 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001959 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001960 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001961
1962 // Build _objc_method_list for class's class methods if needed
1963 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1964 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001965 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001966 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001967
1968 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001969 // Null CDecl is case of a category implementation with no category interface
1970 if (CDecl)
1971 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1972 CDecl->getNumReferencedProtocols(),
1973 "CATEGORY",
1974 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001975
1976 /* struct _objc_category {
1977 char *category_name;
1978 char *class_name;
1979 struct _objc_method_list *instance_methods;
1980 struct _objc_method_list *class_methods;
1981 struct _objc_protocol_list *protocols;
1982 // Objective-C 1.0 extensions
1983 uint32_t size; // sizeof (struct _objc_category)
1984 struct _objc_property_list *instance_properties; // category's own
1985 // @property decl.
1986 };
1987 */
1988
1989 static bool objc_category = false;
1990 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001991 Result += "\nstruct _objc_category {\n";
1992 Result += "\tchar *category_name;\n";
1993 Result += "\tchar *class_name;\n";
1994 Result += "\tstruct _objc_method_list *instance_methods;\n";
1995 Result += "\tstruct _objc_method_list *class_methods;\n";
1996 Result += "\tstruct _objc_protocol_list *protocols;\n";
1997 Result += "\tunsigned int size;\n";
1998 Result += "\tstruct _objc_property_list *instance_properties;\n";
1999 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002000 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002001 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002002 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2003 Result += FullCategoryName;
2004 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2005 Result += IDecl->getName();
2006 Result += "\"\n\t, \"";
2007 Result += ClassDecl->getName();
2008 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002009
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002010 if (IDecl->getNumInstanceMethods() > 0) {
2011 Result += "\t, (struct _objc_method_list *)"
2012 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2013 Result += FullCategoryName;
2014 Result += "\n";
2015 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002016 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002017 Result += "\t, 0\n";
2018 if (IDecl->getNumClassMethods() > 0) {
2019 Result += "\t, (struct _objc_method_list *)"
2020 "&_OBJC_CATEGORY_CLASS_METHODS_";
2021 Result += FullCategoryName;
2022 Result += "\n";
2023 }
2024 else
2025 Result += "\t, 0\n";
2026
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002027 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002028 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2029 Result += FullCategoryName;
2030 Result += "\n";
2031 }
2032 else
2033 Result += "\t, 0\n";
2034 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002035}
2036
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002037/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2038/// ivar offset.
2039void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2040 ObjcIvarDecl *ivar,
2041 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002042 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002043 Result += IDecl->getName();
2044 Result += ", ";
2045 Result += ivar->getName();
2046 Result += ")";
2047}
2048
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002049//===----------------------------------------------------------------------===//
2050// Meta Data Emission
2051//===----------------------------------------------------------------------===//
2052
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002053void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2054 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002055 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2056
2057 // Build _objc_ivar_list metadata for classes ivars if needed
2058 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2059 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002060 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002061 // Explictly declared @interface's are already synthesized.
2062 if (CDecl->ImplicitInterfaceDecl()) {
2063 // FIXME: Implementation of a class with no @interface (legacy) doese not
2064 // produce correct synthesis as yet.
2065 SynthesizeObjcInternalStruct(CDecl, Result);
2066 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002067
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002068 if (NumIvars > 0) {
2069 static bool objc_ivar = false;
2070 if (!objc_ivar) {
2071 /* struct _objc_ivar {
2072 char *ivar_name;
2073 char *ivar_type;
2074 int ivar_offset;
2075 };
2076 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002077 Result += "\nstruct _objc_ivar {\n";
2078 Result += "\tchar *ivar_name;\n";
2079 Result += "\tchar *ivar_type;\n";
2080 Result += "\tint ivar_offset;\n";
2081 Result += "};\n";
2082
2083 /* struct _objc_ivar_list {
2084 int ivar_count;
2085 struct _objc_ivar ivar_list[];
2086 };
2087 */
2088 Result += "\nstruct _objc_ivar_list {\n";
2089 Result += "\tint ivar_count;\n";
2090 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002091 objc_ivar = true;
2092 }
2093
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002094 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2095 Result += IDecl->getName();
2096 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2097 "{\n\t";
2098 Result += utostr(NumIvars);
2099 Result += "\n";
2100
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002101 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2102 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002103 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002104 Result += "\t,{{\"";
2105 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002106 Result += "\", \"";
2107 std::string StrEncoding;
2108 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2109 Result += StrEncoding;
2110 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002111 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2112 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002113 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002114 Result += "\t ,{\"";
2115 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002116 Result += "\", \"";
2117 std::string StrEncoding;
2118 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2119 Result += StrEncoding;
2120 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002121 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2122 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002123 }
2124
2125 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002126 }
2127
2128 // Build _objc_method_list for class's instance methods if needed
2129 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2130 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002131 true,
2132 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002133
2134 // Build _objc_method_list for class's class methods if needed
2135 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002136 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002137 false,
2138 "", IDecl->getName(), Result);
2139
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002140 // Protocols referenced in class declaration?
2141 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2142 CDecl->getNumIntfRefProtocols(),
2143 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002144 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002145
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002146
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002147 // Declaration of class/meta-class metadata
2148 /* struct _objc_class {
2149 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002150 const char *super_class_name;
2151 char *name;
2152 long version;
2153 long info;
2154 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002155 struct _objc_ivar_list *ivars;
2156 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002157 struct objc_cache *cache;
2158 struct objc_protocol_list *protocols;
2159 const char *ivar_layout;
2160 struct _objc_class_ext *ext;
2161 };
2162 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002163 static bool objc_class = false;
2164 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002165 Result += "\nstruct _objc_class {\n";
2166 Result += "\tstruct _objc_class *isa;\n";
2167 Result += "\tconst char *super_class_name;\n";
2168 Result += "\tchar *name;\n";
2169 Result += "\tlong version;\n";
2170 Result += "\tlong info;\n";
2171 Result += "\tlong instance_size;\n";
2172 Result += "\tstruct _objc_ivar_list *ivars;\n";
2173 Result += "\tstruct _objc_method_list *methods;\n";
2174 Result += "\tstruct objc_cache *cache;\n";
2175 Result += "\tstruct _objc_protocol_list *protocols;\n";
2176 Result += "\tconst char *ivar_layout;\n";
2177 Result += "\tstruct _objc_class_ext *ext;\n";
2178 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002179 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002180 }
2181
2182 // Meta-class metadata generation.
2183 ObjcInterfaceDecl *RootClass = 0;
2184 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2185 while (SuperClass) {
2186 RootClass = SuperClass;
2187 SuperClass = SuperClass->getSuperClass();
2188 }
2189 SuperClass = CDecl->getSuperClass();
2190
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002191 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2192 Result += CDecl->getName();
2193 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2194 "{\n\t(struct _objc_class *)\"";
2195 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2196 Result += "\"";
2197
2198 if (SuperClass) {
2199 Result += ", \"";
2200 Result += SuperClass->getName();
2201 Result += "\", \"";
2202 Result += CDecl->getName();
2203 Result += "\"";
2204 }
2205 else {
2206 Result += ", 0, \"";
2207 Result += CDecl->getName();
2208 Result += "\"";
2209 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002210 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002211 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002212 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002213 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002214 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002215 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002216 Result += "\n";
2217 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002218 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002219 Result += ", 0\n";
2220 if (CDecl->getNumIntfRefProtocols() > 0) {
2221 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2222 Result += CDecl->getName();
2223 Result += ",0,0\n";
2224 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002225 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002226 Result += "\t,0,0,0,0\n";
2227 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002228
2229 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002230 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2231 Result += CDecl->getName();
2232 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2233 "{\n\t&_OBJC_METACLASS_";
2234 Result += CDecl->getName();
2235 if (SuperClass) {
2236 Result += ", \"";
2237 Result += SuperClass->getName();
2238 Result += "\", \"";
2239 Result += CDecl->getName();
2240 Result += "\"";
2241 }
2242 else {
2243 Result += ", 0, \"";
2244 Result += CDecl->getName();
2245 Result += "\"";
2246 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002247 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002248 Result += ", 0,1";
2249 if (!ObjcSynthesizedStructs.count(CDecl))
2250 Result += ",0";
2251 else {
2252 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002253 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002254 Result += CDecl->getName();
2255 Result += ")";
2256 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002257 if (NumIvars > 0) {
2258 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2259 Result += CDecl->getName();
2260 Result += "\n\t";
2261 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002262 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002263 Result += ",0";
2264 if (IDecl->getNumInstanceMethods() > 0) {
2265 Result += ", &_OBJC_INSTANCE_METHODS_";
2266 Result += CDecl->getName();
2267 Result += ", 0\n\t";
2268 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002269 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002270 Result += ",0,0";
2271 if (CDecl->getNumIntfRefProtocols() > 0) {
2272 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2273 Result += CDecl->getName();
2274 Result += ", 0,0\n";
2275 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002276 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002277 Result += ",0,0,0\n";
2278 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002279}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002280
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002281/// RewriteImplementations - This routine rewrites all method implementations
2282/// and emits meta-data.
2283
2284void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002285 int ClsDefCount = ClassImplementation.size();
2286 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002287
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002288 if (ClsDefCount == 0 && CatDefCount == 0)
2289 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002290 // Rewrite implemented methods
2291 for (int i = 0; i < ClsDefCount; i++)
2292 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002293
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002294 for (int i = 0; i < CatDefCount; i++)
2295 RewriteImplementationDecl(CategoryImplementation[i]);
2296
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002297 // This is needed for use of offsetof
2298 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002299
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002300 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002301 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002302 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002303
2304 // For each implemented category, write out all its meta data.
2305 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002306 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002307
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002308 // Write objc_symtab metadata
2309 /*
2310 struct _objc_symtab
2311 {
2312 long sel_ref_cnt;
2313 SEL *refs;
2314 short cls_def_cnt;
2315 short cat_def_cnt;
2316 void *defs[cls_def_cnt + cat_def_cnt];
2317 };
2318 */
2319
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002320 Result += "\nstruct _objc_symtab {\n";
2321 Result += "\tlong sel_ref_cnt;\n";
2322 Result += "\tSEL *refs;\n";
2323 Result += "\tshort cls_def_cnt;\n";
2324 Result += "\tshort cat_def_cnt;\n";
2325 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2326 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002327
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002328 Result += "static struct _objc_symtab "
2329 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2330 Result += "\t0, 0, " + utostr(ClsDefCount)
2331 + ", " + utostr(CatDefCount) + "\n";
2332 for (int i = 0; i < ClsDefCount; i++) {
2333 Result += "\t,&_OBJC_CLASS_";
2334 Result += ClassImplementation[i]->getName();
2335 Result += "\n";
2336 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002337
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002338 for (int i = 0; i < CatDefCount; i++) {
2339 Result += "\t,&_OBJC_CATEGORY_";
2340 Result += CategoryImplementation[i]->getClassInterface()->getName();
2341 Result += "_";
2342 Result += CategoryImplementation[i]->getName();
2343 Result += "\n";
2344 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002345
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002346 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002347
2348 // Write objc_module metadata
2349
2350 /*
2351 struct _objc_module {
2352 long version;
2353 long size;
2354 const char *name;
2355 struct _objc_symtab *symtab;
2356 }
2357 */
2358
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002359 Result += "\nstruct _objc_module {\n";
2360 Result += "\tlong version;\n";
2361 Result += "\tlong size;\n";
2362 Result += "\tconst char *name;\n";
2363 Result += "\tstruct _objc_symtab *symtab;\n";
2364 Result += "};\n\n";
2365 Result += "static struct _objc_module "
2366 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002367 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2368 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002369 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002370
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002371}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002372