blob: 8dd39f538e67a329ea0117b394b5ff4d185f8934 [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 Naroff71226032007-10-24 22:48:43 +000050 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000051 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000052
Steve Naroff0add5d22007-11-03 11:27:19 +000053 // ObjC string constant support.
54 FileVarDecl *ConstantStringClassReference;
55 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000056
Steve Naroff764c1ae2007-11-15 10:28:18 +000057 // Needed for super.
58 ObjcMethodDecl *CurMethodDecl;
59 RecordDecl *SuperStructDecl;
60
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000061 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000062 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000063 void Initialize(ASTContext &context, unsigned mainFileID) {
64 Context = &context;
65 SM = &Context->SourceMgr;
Steve Naroffe9780582007-10-23 23:50:29 +000066 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000067 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000068 MsgSendStretFunctionDecl = 0;
69 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000070 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000071 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000072 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000073 CFStringFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000074 ConstantStringClassReference = 0;
75 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000076 CurMethodDecl = 0;
77 SuperStructDecl = 0;
78
Chris Lattnerae43eb72007-12-02 01:13:47 +000079 // Get the ID and start/end of the main file.
80 MainFileID = mainFileID;
81 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
82 MainFileStart = MainBuf->getBufferStart();
83 MainFileEnd = MainBuf->getBufferEnd();
84
85
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000086 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000087 // declaring objc_selector outside the parameter list removes a silly
88 // scope related warning...
Steve Naroff9b99a262007-11-15 17:06:21 +000089 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Narofffcab7932007-11-05 14:55:35 +000090 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000091 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +000092 "extern struct objc_object *objc_msgSendSuper"
93 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000094 "extern struct objc_object *objc_msgSend_stret"
95 "(struct objc_object *, struct objc_selector *, ...);\n"
96 "extern struct objc_object *objc_msgSendSuper_stret"
97 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000098 "extern struct objc_object *objc_msgSend_fpret"
99 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000100 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000101 "(const char *);\n"
102 "extern void objc_exception_throw(struct objc_object *);\n"
103 "extern void objc_exception_try_enter(void *);\n"
104 "extern void objc_exception_try_exit(void *);\n"
105 "extern struct objc_object *objc_exception_extract(void *);\n"
106 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000107 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000108 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000109
Steve Naroff0744c472007-11-04 22:37:50 +0000110 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
111 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000112 }
Chris Lattner569faa62007-10-11 18:38:32 +0000113
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000114 // Top Level Driver code.
115 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000116 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000117 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000118 ~RewriteTest();
119
120 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000121 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000122 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000123 void RewriteTabs();
124 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000125 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000126 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000127 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000128 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000129 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000130 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +0000131 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000132 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000133 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000134 void RewriteObjcQualifiedInterfaceTypes(
135 const FunctionTypeProto *proto, FunctionDecl *FD);
136 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000137 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
138 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000139
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000141 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000142 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000143 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000144 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000145 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000146 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000147 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
148 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
149 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000150 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000151 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
152 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000153 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000154 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000155 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000156 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000157 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000158 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000159 void SynthCFStringFunctionDecl();
160
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000161 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000162 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
163 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000164
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000165 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
166 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000167
Steve Naroffb82c50f2007-11-11 17:19:15 +0000168 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000169 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000170 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000171 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000172 const char *ClassName,
173 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000174
175 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
176 int NumProtocols,
177 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000178 const char *ClassName,
179 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000180 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
181 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000182 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
183 ObjcIvarDecl *ivar,
184 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000185 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000186 };
187}
188
Chris Lattner258f26c2007-11-30 22:25:36 +0000189ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
190 return new RewriteTest(Diags);
191}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000192
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000193//===----------------------------------------------------------------------===//
194// Top Level Driver Code
195//===----------------------------------------------------------------------===//
196
Chris Lattner569faa62007-10-11 18:38:32 +0000197void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000198 // Two cases: either the decl could be in the main file, or it could be in a
199 // #included file. If the former, rewrite it now. If the later, check to see
200 // if we rewrote the #include/#import.
201 SourceLocation Loc = D->getLocation();
202 Loc = SM->getLogicalLoc(Loc);
203
204 // If this is for a builtin, ignore it.
205 if (Loc.isInvalid()) return;
206
Steve Naroffe9780582007-10-23 23:50:29 +0000207 // Look for built-in declarations that we need to refer during the rewrite.
208 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000209 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000210 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
211 // declared in <Foundation/NSString.h>
212 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
213 ConstantStringClassReference = FVD;
214 return;
215 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000216 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
217 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000218 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
219 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000220 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
221 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000222 } else if (ObjcForwardProtocolDecl *FP =
223 dyn_cast<ObjcForwardProtocolDecl>(D)){
224 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000225 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000226 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000227 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
228 return HandleDeclInMainFile(D);
229
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000230 // Otherwise, see if there is a #import in the main file that should be
231 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000232 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000233}
234
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000235/// HandleDeclInMainFile - This is called for each top-level decl defined in the
236/// main file of the input.
237void RewriteTest::HandleDeclInMainFile(Decl *D) {
238 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
239 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000240 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000241
242 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000243 if (Stmt *Body = MD->getBody()) {
244 //Body->dump();
245 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000246 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000247 CurMethodDecl = 0;
248 }
Steve Naroff18c83382007-11-13 23:01:27 +0000249 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000250 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
251 ClassImplementation.push_back(CI);
252 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
253 CategoryImplementation.push_back(CI);
254 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
255 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000256 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
257 if (VD->getInit())
258 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
259 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000260 // Nothing yet.
261}
262
263RewriteTest::~RewriteTest() {
264 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000265
266 // Rewrite tabs if we care.
267 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000268
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000269 // Rewrite Objective-c meta data*
270 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000271 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000272
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000273 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
274 // we are done.
275 if (const RewriteBuffer *RewriteBuf =
276 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000277 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000278 std::string S(RewriteBuf->begin(), RewriteBuf->end());
279 printf("%s\n", S.c_str());
280 } else {
281 printf("No changes\n");
282 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000283 // Emit metadata.
284 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000285}
286
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000287//===----------------------------------------------------------------------===//
288// Syntactic (non-AST) Rewriting Code
289//===----------------------------------------------------------------------===//
290
Chris Lattner74db1682007-10-16 21:07:07 +0000291void RewriteTest::RewriteInclude(SourceLocation Loc) {
292 // Rip up the #include stack to the main file.
293 SourceLocation IncLoc = Loc, NextLoc = Loc;
294 do {
295 IncLoc = Loc;
296 Loc = SM->getLogicalLoc(NextLoc);
297 NextLoc = SM->getIncludeLoc(Loc);
298 } while (!NextLoc.isInvalid());
299
300 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
301 // IncLoc indicates the header that was included if it is useful.
302 IncLoc = SM->getLogicalLoc(IncLoc);
303 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
304 Loc == LastIncLoc)
305 return;
306 LastIncLoc = Loc;
307
308 unsigned IncCol = SM->getColumnNumber(Loc);
309 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
310
311 // Replace the #import with #include.
312 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
313}
314
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000315void RewriteTest::RewriteTabs() {
316 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
317 const char *MainBufStart = MainBuf.first;
318 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000319
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000320 // Loop over the whole file, looking for tabs.
321 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
322 if (*BufPtr != '\t')
323 continue;
324
325 // Okay, we found a tab. This tab will turn into at least one character,
326 // but it depends on which 'virtual column' it is in. Compute that now.
327 unsigned VCol = 0;
328 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
329 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
330 ++VCol;
331
332 // Okay, now that we know the virtual column, we know how many spaces to
333 // insert. We assume 8-character tab-stops.
334 unsigned Spaces = 8-(VCol & 7);
335
336 // Get the location of the tab.
337 SourceLocation TabLoc =
338 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
339
340 // Rewrite the single tab character into a sequence of spaces.
341 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
342 }
Chris Lattner569faa62007-10-11 18:38:32 +0000343}
344
345
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000346void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
347 int numDecls = ClassDecl->getNumForwardDecls();
348 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
349
350 // Get the start location and compute the semi location.
351 SourceLocation startLoc = ClassDecl->getLocation();
352 const char *startBuf = SM->getCharacterData(startLoc);
353 const char *semiPtr = strchr(startBuf, ';');
354
355 // Translate to typedef's that forward reference structs with the same name
356 // as the class. As a convenience, we include the original declaration
357 // as a comment.
358 std::string typedefString;
359 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000360 typedefString.append(startBuf, semiPtr-startBuf+1);
361 typedefString += "\n";
362 for (int i = 0; i < numDecls; i++) {
363 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000364 typedefString += "#ifndef _REWRITER_typedef_";
365 typedefString += ForwardDecl->getName();
366 typedefString += "\n";
367 typedefString += "#define _REWRITER_typedef_";
368 typedefString += ForwardDecl->getName();
369 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000370 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000371 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000372 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000373 }
374
375 // Replace the @class with typedefs corresponding to the classes.
376 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
377 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000378}
379
Steve Naroff18c83382007-11-13 23:01:27 +0000380void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000381 for (int i = 0; i < nMethods; i++) {
382 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000383 SourceLocation LocStart = Method->getLocStart();
384 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000385
Steve Narofffbfb46d2007-11-14 14:34:23 +0000386 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
387 Rewrite.InsertText(LocStart, "/* ", 3);
388 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
389 } else {
390 Rewrite.InsertText(LocStart, "// ", 3);
391 }
Steve Naroff667f1682007-10-30 13:30:57 +0000392 }
393}
394
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000395void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
396{
397 for (int i = 0; i < nProperties; i++) {
398 ObjcPropertyDecl *Property = Properties[i];
399 SourceLocation Loc = Property->getLocation();
400
401 Rewrite.ReplaceText(Loc, 0, "// ", 3);
402
403 // FIXME: handle properties that are declared across multiple lines.
404 }
405}
406
Steve Naroff667f1682007-10-30 13:30:57 +0000407void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
408 SourceLocation LocStart = CatDecl->getLocStart();
409
410 // FIXME: handle category headers that are declared across multiple lines.
411 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
412
Steve Naroff18c83382007-11-13 23:01:27 +0000413 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
414 CatDecl->getInstanceMethods());
415 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
416 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000417 // Lastly, comment out the @end.
418 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
419}
420
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000421void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000422 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000423
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000424 SourceLocation LocStart = PDecl->getLocStart();
425
426 // FIXME: handle protocol headers that are declared across multiple lines.
427 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
428
Steve Naroff18c83382007-11-13 23:01:27 +0000429 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
430 PDecl->getInstanceMethods());
431 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
432 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000433 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000434 SourceLocation LocEnd = PDecl->getAtEndLoc();
435 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000436
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000437 // Must comment out @optional/@required
438 const char *startBuf = SM->getCharacterData(LocStart);
439 const char *endBuf = SM->getCharacterData(LocEnd);
440 for (const char *p = startBuf; p < endBuf; p++) {
441 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
442 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000443 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000444 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
445 CommentedOptional.c_str(), CommentedOptional.size());
446
447 }
448 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
449 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000450 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000451 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
452 CommentedRequired.c_str(), CommentedRequired.size());
453
454 }
455 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000456}
457
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000458void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
459 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000460 if (LocStart.isInvalid())
461 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000462 // FIXME: handle forward protocol that are declared across multiple lines.
463 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
464}
465
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000466void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
467 std::string &ResultStr) {
468 ResultStr += "\nstatic ";
469 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000470 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000471
472 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000473 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000474
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000475 if (OMD->isInstance())
476 NameStr += "_I_";
477 else
478 NameStr += "_C_";
479
480 NameStr += OMD->getClassInterface()->getName();
481 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000482
483 NamedDecl *MethodContext = OMD->getMethodContext();
484 if (ObjcCategoryImplDecl *CID =
485 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000486 NameStr += CID->getName();
487 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000488 }
489 // Append selector names, replacing ':' with '_'
490 const char *selName = OMD->getSelector().getName().c_str();
491 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000492 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000493 else {
494 std::string selString = OMD->getSelector().getName();
495 int len = selString.size();
496 for (int i = 0; i < len; i++)
497 if (selString[i] == ':')
498 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000499 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000500 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000501 // Remember this name for metadata emission
502 MethodInternalNames[OMD] = NameStr;
503 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000504
505 // Rewrite arguments
506 ResultStr += "(";
507
508 // invisible arguments
509 if (OMD->isInstance()) {
510 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
511 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000512 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
513 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000514 ResultStr += selfTy.getAsString();
515 }
516 else
517 ResultStr += Context->getObjcIdType().getAsString();
518
519 ResultStr += " self, ";
520 ResultStr += Context->getObjcSelType().getAsString();
521 ResultStr += " _cmd";
522
523 // Method arguments.
524 for (int i = 0; i < OMD->getNumParams(); i++) {
525 ParmVarDecl *PDecl = OMD->getParamDecl(i);
526 ResultStr += ", ";
527 ResultStr += PDecl->getType().getAsString();
528 ResultStr += " ";
529 ResultStr += PDecl->getName();
530 }
531 ResultStr += ")";
532
533}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000534void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
535 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
536 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000537
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000538 if (IMD)
539 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
540 else
541 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000542
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000543 int numMethods = IMD ? IMD->getNumInstanceMethods()
544 : CID->getNumInstanceMethods();
545
546 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000547 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000548 ObjcMethodDecl *OMD;
549 if (IMD)
550 OMD = IMD->getInstanceMethods()[i];
551 else
552 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000553 RewriteObjcMethodDecl(OMD, ResultStr);
554 SourceLocation LocStart = OMD->getLocStart();
555 SourceLocation LocEnd = OMD->getBody()->getLocStart();
556
557 const char *startBuf = SM->getCharacterData(LocStart);
558 const char *endBuf = SM->getCharacterData(LocEnd);
559 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
560 ResultStr.c_str(), ResultStr.size());
561 }
562
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000563 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
564 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000565 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000566 ObjcMethodDecl *OMD;
567 if (IMD)
568 OMD = IMD->getClassMethods()[i];
569 else
570 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000571 RewriteObjcMethodDecl(OMD, ResultStr);
572 SourceLocation LocStart = OMD->getLocStart();
573 SourceLocation LocEnd = OMD->getBody()->getLocStart();
574
575 const char *startBuf = SM->getCharacterData(LocStart);
576 const char *endBuf = SM->getCharacterData(LocEnd);
577 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
578 ResultStr.c_str(), ResultStr.size());
579 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000580 if (IMD)
581 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
582 else
583 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000584}
585
Steve Naroff3774dd92007-10-26 20:53:56 +0000586void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000587 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000588 if (!ObjcForwardDecls.count(ClassDecl)) {
589 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000590 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000591 ResultStr += ClassDecl->getName();
592 ResultStr += "\n";
593 ResultStr += "#define _REWRITER_typedef_";
594 ResultStr += ClassDecl->getName();
595 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000596 ResultStr += "typedef struct ";
597 ResultStr += ClassDecl->getName();
598 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000599 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000600 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000601
602 // Mark this typedef as having been generated.
603 ObjcForwardDecls.insert(ClassDecl);
604 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000605 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
606
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000607 RewriteProperties(ClassDecl->getNumPropertyDecl(),
608 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000609 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
610 ClassDecl->getInstanceMethods());
611 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
612 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000613
Steve Naroff1ccf4632007-10-30 03:43:13 +0000614 // Lastly, comment out the @end.
615 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000616}
617
Steve Naroff6b759ce2007-11-15 02:58:25 +0000618Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
619 ObjcIvarDecl *D = IV->getDecl();
620 if (IV->isFreeIvar()) {
621 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
622 IV->getLocation());
623 Rewrite.ReplaceStmt(IV, Replacement);
624 delete IV;
625 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000626 } else {
627 if (CurMethodDecl) {
628 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
629 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
630 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
631 IdentifierInfo *II = intT->getDecl()->getIdentifier();
632 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
633 II, 0);
634 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
635
636 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
637 // Don't forget the parens to enforce the proper binding.
638 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
639 Rewrite.ReplaceStmt(IV->getBase(), PE);
640 delete IV->getBase();
641 return PE;
642 }
643 }
644 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000645 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000646 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000647}
648
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000649//===----------------------------------------------------------------------===//
650// Function Body / Expression rewriting
651//===----------------------------------------------------------------------===//
652
Steve Naroff334fbc22007-11-09 15:20:18 +0000653Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000654 // Otherwise, just rewrite all children.
655 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
656 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000657 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000658 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000659 if (newStmt)
660 *CI = newStmt;
661 }
Steve Naroffe9780582007-10-23 23:50:29 +0000662
663 // Handle specific things.
664 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
665 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000666
667 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
668 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000669
670 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
671 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000672
673 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
674 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000675
Steve Naroff71226032007-10-24 22:48:43 +0000676 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
677 // Before we rewrite it, put the original message expression in a comment.
678 SourceLocation startLoc = MessExpr->getLocStart();
679 SourceLocation endLoc = MessExpr->getLocEnd();
680
681 const char *startBuf = SM->getCharacterData(startLoc);
682 const char *endBuf = SM->getCharacterData(endLoc);
683
684 std::string messString;
685 messString += "// ";
686 messString.append(startBuf, endBuf-startBuf+1);
687 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000688
Steve Naroff71226032007-10-24 22:48:43 +0000689 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
690 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
691 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000692 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000693 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000694 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000695
696 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
697 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000698
699 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
700 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000701#if 0
702 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
703 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
704 // Get the new text.
705 std::ostringstream Buf;
706 Replacement->printPretty(Buf);
707 const std::string &Str = Buf.str();
708
709 printf("CAST = %s\n", &Str[0]);
710 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
711 delete S;
712 return Replacement;
713 }
714#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000715 // Return this stmt unmodified.
716 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000717}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000718
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000719Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000720 // Get the start location and compute the semi location.
721 SourceLocation startLoc = S->getLocStart();
722 const char *startBuf = SM->getCharacterData(startLoc);
723
724 assert((*startBuf == '@') && "bogus @try location");
725
726 std::string buf;
727 // declare a new scope with two variables, _stack and _rethrow.
728 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
729 buf += "int buf[18/*32-bit i386*/];\n";
730 buf += "char *pointers[4];} _stack;\n";
731 buf += "id volatile _rethrow = 0;\n";
732 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000733 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000734
735 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
736
737 startLoc = S->getTryBody()->getLocEnd();
738 startBuf = SM->getCharacterData(startLoc);
739
740 assert((*startBuf == '}') && "bogus @try block");
741
742 SourceLocation lastCurlyLoc = startLoc;
743
744 startLoc = startLoc.getFileLocWithOffset(1);
745 buf = " /* @catch begin */ else {\n";
746 buf += " id _caught = objc_exception_extract(&_stack);\n";
747 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000748 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000749 buf += " _rethrow = objc_exception_extract(&_stack);\n";
750 buf += " else { /* @catch continue */";
751
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000752 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000753
754 bool sawIdTypedCatch = false;
755 Stmt *lastCatchBody = 0;
756 ObjcAtCatchStmt *catchList = S->getCatchStmts();
757 while (catchList) {
758 Stmt *catchStmt = catchList->getCatchParamStmt();
759
760 if (catchList == S->getCatchStmts())
761 buf = "if ("; // we are generating code for the first catch clause
762 else
763 buf = "else if (";
764 startLoc = catchList->getLocStart();
765 startBuf = SM->getCharacterData(startLoc);
766
767 assert((*startBuf == '@') && "bogus @catch location");
768
769 const char *lParenLoc = strchr(startBuf, '(');
770
771 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
772 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
773 if (t == Context->getObjcIdType()) {
774 buf += "1) { ";
775 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
776 buf.c_str(), buf.size());
777 sawIdTypedCatch = true;
778 } else if (const PointerType *pType = t->getAsPointerType()) {
779 ObjcInterfaceType *cls; // Should be a pointer to a class.
780
781 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
782 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000783 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000784 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000785 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000786 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
787 buf.c_str(), buf.size());
788 }
789 }
790 // Now rewrite the body...
791 lastCatchBody = catchList->getCatchBody();
792 SourceLocation rParenLoc = catchList->getRParenLoc();
793 SourceLocation bodyLoc = lastCatchBody->getLocStart();
794 const char *bodyBuf = SM->getCharacterData(bodyLoc);
795 const char *rParenBuf = SM->getCharacterData(rParenLoc);
796 assert((*rParenBuf == ')') && "bogus @catch paren location");
797 assert((*bodyBuf == '{') && "bogus @catch body location");
798
799 buf = " = _caught;";
800 // Here we replace ") {" with "= _caught;" (which initializes and
801 // declares the @catch parameter).
802 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
803 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000804 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000805 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000806 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000807 catchList = catchList->getNextCatchStmt();
808 }
809 // Complete the catch list...
810 if (lastCatchBody) {
811 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
812 const char *bodyBuf = SM->getCharacterData(bodyLoc);
813 assert((*bodyBuf == '}') && "bogus @catch body location");
814 bodyLoc = bodyLoc.getFileLocWithOffset(1);
815 buf = " } } /* @catch end */\n";
816
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000817 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000818
819 // Set lastCurlyLoc
820 lastCurlyLoc = lastCatchBody->getLocEnd();
821 }
822 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
823 startLoc = finalStmt->getLocStart();
824 startBuf = SM->getCharacterData(startLoc);
825 assert((*startBuf == '@') && "bogus @finally start");
826
827 buf = "/* @finally */";
828 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
829
830 Stmt *body = finalStmt->getFinallyBody();
831 SourceLocation startLoc = body->getLocStart();
832 SourceLocation endLoc = body->getLocEnd();
833 const char *startBuf = SM->getCharacterData(startLoc);
834 const char *endBuf = SM->getCharacterData(endLoc);
835 assert((*startBuf == '{') && "bogus @finally body location");
836 assert((*endBuf == '}') && "bogus @finally body location");
837
838 startLoc = startLoc.getFileLocWithOffset(1);
839 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000840 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000841 endLoc = endLoc.getFileLocWithOffset(-1);
842 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000843 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000844
845 // Set lastCurlyLoc
846 lastCurlyLoc = body->getLocEnd();
847 }
848 // Now emit the final closing curly brace...
849 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
850 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000851 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000852 return 0;
853}
854
855Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
856 return 0;
857}
858
859Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
860 return 0;
861}
862
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000863// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
864// the throw expression is typically a message expression that's already
865// been rewritten! (which implies the SourceLocation's are invalid).
866Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
867 // Get the start location and compute the semi location.
868 SourceLocation startLoc = S->getLocStart();
869 const char *startBuf = SM->getCharacterData(startLoc);
870
871 assert((*startBuf == '@') && "bogus @throw location");
872
873 std::string buf;
874 /* void objc_exception_throw(id) __attribute__((noreturn)); */
875 buf = "objc_exception_throw(";
876 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
877 const char *semiBuf = strchr(startBuf, ';');
878 assert((*semiBuf == ';') && "@throw: can't find ';'");
879 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
880 buf = ");";
881 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
882 return 0;
883}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000884
Chris Lattner0021f452007-10-24 16:57:36 +0000885Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000886 // Create a new string expression.
887 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000888 std::string StrEncoding;
889 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
890 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
891 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000892 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000893 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
894 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000895 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
896 "rewriter could not replace sub-expression due to macros");
897 SourceRange Range = Exp->getSourceRange();
898 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
899 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000900 return Exp;
901 }
902
Chris Lattner4478db92007-11-30 22:53:43 +0000903 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000904 delete Exp;
905 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000906}
907
Steve Naroff296b74f2007-11-05 14:50:49 +0000908Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
909 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
910 // Create a call to sel_registerName("selName").
911 llvm::SmallVector<Expr*, 8> SelExprs;
912 QualType argType = Context->getPointerType(Context->CharTy);
913 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
914 Exp->getSelector().getName().size(),
915 false, argType, SourceLocation(),
916 SourceLocation()));
917 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
918 &SelExprs[0], SelExprs.size());
919 Rewrite.ReplaceStmt(Exp, SelExp);
920 delete Exp;
921 return SelExp;
922}
923
Steve Naroff71226032007-10-24 22:48:43 +0000924CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
925 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000926 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000927 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000928
929 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000930 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000931
932 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000933 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000934 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
935
936 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000937
Steve Naroff71226032007-10-24 22:48:43 +0000938 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
939}
940
Steve Naroffc8a92d12007-11-01 13:24:47 +0000941static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
942 const char *&startRef, const char *&endRef) {
943 while (startBuf < endBuf) {
944 if (*startBuf == '<')
945 startRef = startBuf; // mark the start.
946 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000947 if (startRef && *startRef == '<') {
948 endRef = startBuf; // mark the end.
949 return true;
950 }
951 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000952 }
953 startBuf++;
954 }
955 return false;
956}
957
958bool RewriteTest::needToScanForQualifiers(QualType T) {
959 // FIXME: we don't currently represent "id <Protocol>" in the type system.
960 if (T == Context->getObjcIdType())
961 return true;
962
963 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000964 Type *pointeeType = pType->getPointeeType().getTypePtr();
965 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
966 return true; // we have "Class <Protocol> *".
967 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000968 return false;
969}
970
971void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
972 const FunctionTypeProto *proto, FunctionDecl *FD) {
973
974 if (needToScanForQualifiers(proto->getResultType())) {
975 // Since types are unique, we need to scan the buffer.
976 SourceLocation Loc = FD->getLocation();
977
978 const char *endBuf = SM->getCharacterData(Loc);
979 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +0000980 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +0000981 startBuf--; // scan backward (from the decl location) for return type.
982 const char *startRef = 0, *endRef = 0;
983 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
984 // Get the locations of the startRef, endRef.
985 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
986 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
987 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000988 Rewrite.InsertText(LessLoc, "/*", 2);
989 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000990 }
991 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000992 // Now check arguments.
993 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
994 if (needToScanForQualifiers(proto->getArgType(i))) {
995 // Since types are unique, we need to scan the buffer.
996 SourceLocation Loc = FD->getLocation();
997
998 const char *startBuf = SM->getCharacterData(Loc);
999 const char *endBuf = startBuf;
1000 while (*endBuf != ';')
1001 endBuf++; // scan forward (from the decl location) for argument types.
1002 const char *startRef = 0, *endRef = 0;
1003 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1004 // Get the locations of the startRef, endRef.
1005 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1006 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1007 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001008 Rewrite.InsertText(LessLoc, "/*", 2);
1009 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001010 }
1011 }
1012 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001013}
1014
Steve Naroff02a82aa2007-10-30 23:14:51 +00001015void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1016 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001017 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001018 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001019 return;
1020 }
1021 // Check for ObjC 'id' and class types that have been adorned with protocol
1022 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1023 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1024 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +00001025 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1026 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001027}
1028
1029// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1030void RewriteTest::SynthMsgSendFunctionDecl() {
1031 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1032 llvm::SmallVector<QualType, 16> ArgTys;
1033 QualType argT = Context->getObjcIdType();
1034 assert(!argT.isNull() && "Can't find 'id' type");
1035 ArgTys.push_back(argT);
1036 argT = Context->getObjcSelType();
1037 assert(!argT.isNull() && "Can't find 'SEL' type");
1038 ArgTys.push_back(argT);
1039 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1040 &ArgTys[0], ArgTys.size(),
1041 true /*isVariadic*/);
1042 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1043 msgSendIdent, msgSendType,
1044 FunctionDecl::Extern, false, 0);
1045}
1046
Steve Naroff764c1ae2007-11-15 10:28:18 +00001047// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1048void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1049 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1050 llvm::SmallVector<QualType, 16> ArgTys;
1051 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1052 &Context->Idents.get("objc_super"), 0);
1053 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1054 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1055 ArgTys.push_back(argT);
1056 argT = Context->getObjcSelType();
1057 assert(!argT.isNull() && "Can't find 'SEL' type");
1058 ArgTys.push_back(argT);
1059 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1060 &ArgTys[0], ArgTys.size(),
1061 true /*isVariadic*/);
1062 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1063 msgSendIdent, msgSendType,
1064 FunctionDecl::Extern, false, 0);
1065}
1066
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001067// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1068void RewriteTest::SynthMsgSendStretFunctionDecl() {
1069 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1070 llvm::SmallVector<QualType, 16> ArgTys;
1071 QualType argT = Context->getObjcIdType();
1072 assert(!argT.isNull() && "Can't find 'id' type");
1073 ArgTys.push_back(argT);
1074 argT = Context->getObjcSelType();
1075 assert(!argT.isNull() && "Can't find 'SEL' type");
1076 ArgTys.push_back(argT);
1077 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1078 &ArgTys[0], ArgTys.size(),
1079 true /*isVariadic*/);
1080 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1081 msgSendIdent, msgSendType,
1082 FunctionDecl::Extern, false, 0);
1083}
1084
1085// SynthMsgSendSuperStretFunctionDecl -
1086// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1087void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1088 IdentifierInfo *msgSendIdent =
1089 &Context->Idents.get("objc_msgSendSuper_stret");
1090 llvm::SmallVector<QualType, 16> ArgTys;
1091 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1092 &Context->Idents.get("objc_super"), 0);
1093 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1094 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1095 ArgTys.push_back(argT);
1096 argT = Context->getObjcSelType();
1097 assert(!argT.isNull() && "Can't find 'SEL' type");
1098 ArgTys.push_back(argT);
1099 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1100 &ArgTys[0], ArgTys.size(),
1101 true /*isVariadic*/);
1102 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1103 msgSendIdent, msgSendType,
1104 FunctionDecl::Extern, false, 0);
1105}
1106
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001107// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1108void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1109 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1110 llvm::SmallVector<QualType, 16> ArgTys;
1111 QualType argT = Context->getObjcIdType();
1112 assert(!argT.isNull() && "Can't find 'id' type");
1113 ArgTys.push_back(argT);
1114 argT = Context->getObjcSelType();
1115 assert(!argT.isNull() && "Can't find 'SEL' type");
1116 ArgTys.push_back(argT);
1117 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1118 &ArgTys[0], ArgTys.size(),
1119 true /*isVariadic*/);
1120 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1121 msgSendIdent, msgSendType,
1122 FunctionDecl::Extern, false, 0);
1123}
1124
Steve Naroff02a82aa2007-10-30 23:14:51 +00001125// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1126void RewriteTest::SynthGetClassFunctionDecl() {
1127 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1128 llvm::SmallVector<QualType, 16> ArgTys;
1129 ArgTys.push_back(Context->getPointerType(
1130 Context->CharTy.getQualifiedType(QualType::Const)));
1131 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1132 &ArgTys[0], ArgTys.size(),
1133 false /*isVariadic*/);
1134 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1135 getClassIdent, getClassType,
1136 FunctionDecl::Extern, false, 0);
1137}
1138
Steve Naroffabb96362007-11-08 14:30:50 +00001139// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1140void RewriteTest::SynthCFStringFunctionDecl() {
1141 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1142 llvm::SmallVector<QualType, 16> ArgTys;
1143 ArgTys.push_back(Context->getPointerType(
1144 Context->CharTy.getQualifiedType(QualType::Const)));
1145 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1146 &ArgTys[0], ArgTys.size(),
1147 false /*isVariadic*/);
1148 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1149 getClassIdent, getClassType,
1150 FunctionDecl::Extern, false, 0);
1151}
1152
Steve Naroff0add5d22007-11-03 11:27:19 +00001153Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001154#if 1
1155 // This rewrite is specific to GCC, which has builtin support for CFString.
1156 if (!CFStringFunctionDecl)
1157 SynthCFStringFunctionDecl();
1158 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1159 llvm::SmallVector<Expr*, 8> StrExpr;
1160 StrExpr.push_back(Exp->getString());
1161 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1162 &StrExpr[0], StrExpr.size());
1163 // cast to NSConstantString *
1164 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1165 Rewrite.ReplaceStmt(Exp, cast);
1166 delete Exp;
1167 return cast;
1168#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001169 assert(ConstantStringClassReference && "Can't find constant string reference");
1170 llvm::SmallVector<Expr*, 4> InitExprs;
1171
1172 // Synthesize "(Class)&_NSConstantStringClassReference"
1173 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1174 ConstantStringClassReference->getType(),
1175 SourceLocation());
1176 QualType expType = Context->getPointerType(ClsRef->getType());
1177 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1178 expType, SourceLocation());
1179 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1180 SourceLocation());
1181 InitExprs.push_back(cast); // set the 'isa'.
1182 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1183 unsigned IntSize = static_cast<unsigned>(
1184 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1185 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1186 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1187 Exp->getLocStart());
1188 InitExprs.push_back(len); // set "int numBytes".
1189
1190 // struct NSConstantString
1191 QualType CFConstantStrType = Context->getCFConstantStringType();
1192 // (struct NSConstantString) { <exprs from above> }
1193 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1194 &InitExprs[0], InitExprs.size(),
1195 SourceLocation());
1196 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1197 // struct NSConstantString *
1198 expType = Context->getPointerType(StrRep->getType());
1199 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1200 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001201 // cast to NSConstantString *
1202 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001203 Rewrite.ReplaceStmt(Exp, cast);
1204 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001205 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001206#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001207}
1208
Steve Naroff764c1ae2007-11-15 10:28:18 +00001209ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1210 if (CurMethodDecl) { // check if we are sending a message to 'super'
1211 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1212 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1213 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1214 if (!strcmp(PVD->getName(), "self")) {
1215 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1216 if (ObjcInterfaceType *IT =
1217 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1218 if (IT->getDecl() ==
1219 CurMethodDecl->getClassInterface()->getSuperClass())
1220 return IT->getDecl();
1221 }
1222 }
1223 }
1224 }
1225 }
1226 }
1227 }
1228 return 0;
1229}
1230
1231// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1232QualType RewriteTest::getSuperStructType() {
1233 if (!SuperStructDecl) {
1234 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1235 &Context->Idents.get("objc_super"), 0);
1236 QualType FieldTypes[2];
1237
1238 // struct objc_object *receiver;
1239 FieldTypes[0] = Context->getObjcIdType();
1240 // struct objc_class *super;
1241 FieldTypes[1] = Context->getObjcClassType();
1242 // Create fields
1243 FieldDecl *FieldDecls[2];
1244
1245 for (unsigned i = 0; i < 2; ++i)
1246 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1247
1248 SuperStructDecl->defineBody(FieldDecls, 4);
1249 }
1250 return Context->getTagDeclType(SuperStructDecl);
1251}
1252
Steve Naroff71226032007-10-24 22:48:43 +00001253Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001254 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001255 if (!MsgSendFunctionDecl)
1256 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001257 if (!MsgSendSuperFunctionDecl)
1258 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001259 if (!MsgSendStretFunctionDecl)
1260 SynthMsgSendStretFunctionDecl();
1261 if (!MsgSendSuperStretFunctionDecl)
1262 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001263 if (!MsgSendFpretFunctionDecl)
1264 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001265 if (!GetClassFunctionDecl)
1266 SynthGetClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001267
Steve Naroff764c1ae2007-11-15 10:28:18 +00001268 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001269 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1270 // May need to use objc_msgSend_stret() as well.
1271 FunctionDecl *MsgSendStretFlavor = 0;
1272 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1273 QualType resultType = mDecl->getResultType();
1274 if (resultType.getCanonicalType()->isStructureType()
1275 || resultType.getCanonicalType()->isUnionType())
1276 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001277 else if (resultType.getCanonicalType()->isRealFloatingType())
1278 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001279 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001280
Steve Naroff71226032007-10-24 22:48:43 +00001281 // Synthesize a call to objc_msgSend().
1282 llvm::SmallVector<Expr*, 8> MsgExprs;
1283 IdentifierInfo *clsName = Exp->getClassName();
1284
1285 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1286 if (clsName) { // class message.
1287 llvm::SmallVector<Expr*, 8> ClsExprs;
1288 QualType argType = Context->getPointerType(Context->CharTy);
1289 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1290 clsName->getLength(),
1291 false, argType, SourceLocation(),
1292 SourceLocation()));
1293 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1294 &ClsExprs[0], ClsExprs.size());
1295 MsgExprs.push_back(Cls);
Steve Naroff885e2122007-11-14 23:54:14 +00001296 } else { // instance message.
1297 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001298
1299 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1300 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001301 if (MsgSendStretFlavor)
1302 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001303 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1304
1305 llvm::SmallVector<Expr*, 4> InitExprs;
1306
1307 InitExprs.push_back(recExpr); // set the 'receiver'.
1308
1309 llvm::SmallVector<Expr*, 8> ClsExprs;
1310 QualType argType = Context->getPointerType(Context->CharTy);
1311 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1312 ID->getIdentifier()->getLength(),
1313 false, argType, SourceLocation(),
1314 SourceLocation()));
1315 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1316 &ClsExprs[0], ClsExprs.size());
1317 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1318 // struct objc_super
1319 QualType superType = getSuperStructType();
1320 // (struct objc_super) { <exprs from above> }
1321 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1322 &InitExprs[0], InitExprs.size(),
1323 SourceLocation());
1324 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1325 // struct objc_super *
1326 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1327 Context->getPointerType(SuperRep->getType()),
1328 SourceLocation());
1329 MsgExprs.push_back(Unop);
1330 } else {
1331 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1332 MsgExprs.push_back(recExpr);
1333 }
Steve Naroff885e2122007-11-14 23:54:14 +00001334 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001335 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001336 llvm::SmallVector<Expr*, 8> SelExprs;
1337 QualType argType = Context->getPointerType(Context->CharTy);
1338 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1339 Exp->getSelector().getName().size(),
1340 false, argType, SourceLocation(),
1341 SourceLocation()));
1342 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1343 &SelExprs[0], SelExprs.size());
1344 MsgExprs.push_back(SelExp);
1345
1346 // Now push any user supplied arguments.
1347 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001348 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001349 // Make all implicit casts explicit...ICE comes in handy:-)
1350 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1351 // Reuse the ICE type, it is exactly what the doctor ordered.
1352 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1353 }
Steve Naroff885e2122007-11-14 23:54:14 +00001354 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001355 // We've transferred the ownership to MsgExprs. Null out the argument in
1356 // the original expression, since we will delete it below.
1357 Exp->setArg(i, 0);
1358 }
Steve Naroff0744c472007-11-04 22:37:50 +00001359 // Generate the funky cast.
1360 CastExpr *cast;
1361 llvm::SmallVector<QualType, 8> ArgTypes;
1362 QualType returnType;
1363
1364 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001365 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1366 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1367 else
1368 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001369 ArgTypes.push_back(Context->getObjcSelType());
1370 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1371 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001372 for (int i = 0; i < mDecl->getNumParams(); i++) {
1373 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001374 ArgTypes.push_back(t);
1375 }
Steve Naroff0744c472007-11-04 22:37:50 +00001376 returnType = mDecl->getResultType();
1377 } else {
1378 returnType = Context->getObjcIdType();
1379 }
1380 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001381 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001382
1383 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001384 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1385 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001386
1387 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1388 // If we don't do this cast, we get the following bizarre warning/note:
1389 // xx.m:13: warning: function called through a non-compatible type
1390 // xx.m:13: note: if this code is reached, the program will abort
1391 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1392 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001393
Steve Naroff0744c472007-11-04 22:37:50 +00001394 // Now do the "normal" pointer to function cast.
1395 QualType castType = Context->getFunctionType(returnType,
1396 &ArgTypes[0], ArgTypes.size(),
Steve Naroff29fe7462007-11-15 12:35:21 +00001397 Exp->getMethodDecl()->isVariadic());
Steve Naroff0744c472007-11-04 22:37:50 +00001398 castType = Context->getPointerType(castType);
1399 cast = new CastExpr(castType, cast, SourceLocation());
1400
1401 // Don't forget the parens to enforce the proper binding.
1402 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1403
1404 const FunctionType *FT = msgSendType->getAsFunctionType();
1405 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1406 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001407 if (MsgSendStretFlavor) {
1408 // We have the method which returns a struct/union. Must also generate
1409 // call to objc_msgSend_stret and hang both varieties on a conditional
1410 // expression which dictate which one to envoke depending on size of
1411 // method's return type.
1412
1413 // Create a reference to the objc_msgSend_stret() declaration.
1414 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1415 SourceLocation());
1416 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1417 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1418 SourceLocation());
1419 // Now do the "normal" pointer to function cast.
1420 castType = Context->getFunctionType(returnType,
1421 &ArgTypes[0], ArgTypes.size(),
1422 Exp->getMethodDecl()->isVariadic());
1423 castType = Context->getPointerType(castType);
1424 cast = new CastExpr(castType, cast, SourceLocation());
1425
1426 // Don't forget the parens to enforce the proper binding.
1427 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1428
1429 FT = msgSendType->getAsFunctionType();
1430 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1431 FT->getResultType(), SourceLocation());
1432
1433 // Build sizeof(returnType)
1434 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1435 returnType, Context->getSizeType(),
1436 SourceLocation(), SourceLocation());
1437 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1438 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1439 // For X86 it is more complicated and some kind of target specific routine
1440 // is needed to decide what to do.
1441 unsigned IntSize = static_cast<unsigned>(
1442 Context->getTypeSize(Context->IntTy, SourceLocation()));
1443
1444 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1445 Context->IntTy,
1446 SourceLocation());
1447 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1448 BinaryOperator::LE,
1449 Context->IntTy,
1450 SourceLocation());
1451 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1452 ConditionalOperator *CondExpr =
1453 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1454 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1455 // Now do the actual rewrite.
1456 Rewrite.ReplaceStmt(Exp, PE);
1457 delete Exp;
1458 return PE;
1459 }
Steve Naroff71226032007-10-24 22:48:43 +00001460 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001461 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001462
Chris Lattner0021f452007-10-24 16:57:36 +00001463 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001464 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001465}
1466
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001467/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1468/// an objective-c class with ivars.
1469void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1470 std::string &Result) {
1471 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1472 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001473 // Do not synthesize more than once.
1474 if (ObjcSynthesizedStructs.count(CDecl))
1475 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001476 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001477 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001478 SourceLocation LocStart = CDecl->getLocStart();
1479 SourceLocation LocEnd = CDecl->getLocEnd();
1480
1481 const char *startBuf = SM->getCharacterData(LocStart);
1482 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001483 // If no ivars and no root or if its root, directly or indirectly,
1484 // have no ivars (thus not synthesized) then no need to synthesize this class.
1485 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001486 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1487 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1488 Result.c_str(), Result.size());
1489 return;
1490 }
1491
1492 // FIXME: This has potential of causing problem. If
1493 // SynthesizeObjcInternalStruct is ever called recursively.
1494 Result += "\nstruct ";
1495 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001496
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001497 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001498 const char *cursor = strchr(startBuf, '{');
1499 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001500 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001501
1502 // rewrite the original header *without* disturbing the '{'
1503 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1504 Result.c_str(), Result.size());
1505 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1506 Result = "\n struct ";
1507 Result += RCDecl->getName();
1508 Result += " _";
1509 Result += RCDecl->getName();
1510 Result += ";\n";
1511
1512 // insert the super class structure definition.
1513 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1514 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1515 }
1516 cursor++; // past '{'
1517
1518 // Now comment out any visibility specifiers.
1519 while (cursor < endBuf) {
1520 if (*cursor == '@') {
1521 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001522 // Skip whitespace.
1523 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1524 /*scan*/;
1525
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001526 // FIXME: presence of @public, etc. inside comment results in
1527 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001528 if (!strncmp(cursor, "public", strlen("public")) ||
1529 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001530 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001531 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001532 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001533 // FIXME: If there are cases where '<' is used in ivar declaration part
1534 // of user code, then scan the ivar list and use needToScanForQualifiers
1535 // for type checking.
1536 else if (*cursor == '<') {
1537 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1538 Rewrite.InsertText(atLoc, "/* ", 3);
1539 cursor = strchr(cursor, '>');
1540 cursor++;
1541 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1542 Rewrite.InsertText(atLoc, " */", 3);
1543 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001544 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001545 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001546 // Don't forget to add a ';'!!
1547 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1548 } else { // we don't have any instance variables - insert super struct.
1549 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1550 Result += " {\n struct ";
1551 Result += RCDecl->getName();
1552 Result += " _";
1553 Result += RCDecl->getName();
1554 Result += ";\n};\n";
1555 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1556 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001557 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001558 // Mark this struct as having been generated.
1559 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001560 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001561}
1562
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001563// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1564/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001565void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001566 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001567 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001568 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001569 const char *ClassName,
1570 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001571 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001572 if (NumMethods > 0 && !objc_impl_method) {
1573 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001574 SEL _cmd;
1575 char *method_types;
1576 void *_imp;
1577 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001578 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001579 Result += "\nstruct _objc_method {\n";
1580 Result += "\tSEL _cmd;\n";
1581 Result += "\tchar *method_types;\n";
1582 Result += "\tvoid *_imp;\n";
1583 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001584
1585 /* struct _objc_method_list {
1586 struct _objc_method_list *next_method;
1587 int method_count;
1588 struct _objc_method method_list[];
1589 }
1590 */
1591 Result += "\nstruct _objc_method_list {\n";
1592 Result += "\tstruct _objc_method_list *next_method;\n";
1593 Result += "\tint method_count;\n";
1594 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001595 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001596 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001597 // Build _objc_method_list for class's methods if needed
1598 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001599 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001600 Result += prefix;
1601 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1602 Result += "_METHODS_";
1603 Result += ClassName;
1604 Result += " __attribute__ ((section (\"__OBJC, __";
1605 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001606 Result += "_meth\")))= ";
1607 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1608
1609 Result += "\t,{{(SEL)\"";
1610 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001611 std::string MethodTypeString;
1612 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1613 Result += "\", \"";
1614 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001615 Result += "\", ";
1616 Result += MethodInternalNames[Methods[0]];
1617 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001618 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001619 Result += "\t ,{(SEL)\"";
1620 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001621 std::string MethodTypeString;
1622 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1623 Result += "\", \"";
1624 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001625 Result += "\", ";
1626 Result += MethodInternalNames[Methods[i]];
1627 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001628 }
1629 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001630 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001631}
1632
1633/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1634void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1635 int NumProtocols,
1636 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001637 const char *ClassName,
1638 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001639 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001640 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001641 for (int i = 0; i < NumProtocols; i++) {
1642 ObjcProtocolDecl *PDecl = Protocols[i];
1643 // Output struct protocol_methods holder of method selector and type.
1644 if (!objc_protocol_methods &&
1645 (PDecl->getNumInstanceMethods() > 0
1646 || PDecl->getNumClassMethods() > 0)) {
1647 /* struct protocol_methods {
1648 SEL _cmd;
1649 char *method_types;
1650 }
1651 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001652 Result += "\nstruct protocol_methods {\n";
1653 Result += "\tSEL _cmd;\n";
1654 Result += "\tchar *method_types;\n";
1655 Result += "};\n";
1656
1657 /* struct _objc_protocol_method_list {
1658 int protocol_method_count;
1659 struct protocol_methods protocols[];
1660 }
1661 */
1662 Result += "\nstruct _objc_protocol_method_list {\n";
1663 Result += "\tint protocol_method_count;\n";
1664 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001665 objc_protocol_methods = true;
1666 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001667
Fariborz Jahanian04455192007-10-22 21:41:37 +00001668 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001669 int NumMethods = PDecl->getNumInstanceMethods();
1670 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001671 Result += "\nstatic struct _objc_protocol_method_list "
1672 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1673 Result += PDecl->getName();
1674 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1675 "{\n\t" + utostr(NumMethods) + "\n";
1676
Fariborz Jahanian04455192007-10-22 21:41:37 +00001677 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001678 Result += "\t,{{(SEL)\"";
1679 Result += Methods[0]->getSelector().getName().c_str();
1680 Result += "\", \"\"}\n";
1681
1682 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001683 Result += "\t ,{(SEL)\"";
1684 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001685 std::string MethodTypeString;
1686 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1687 Result += "\", \"";
1688 Result += MethodTypeString;
1689 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001690 }
1691 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001692 }
1693
1694 // Output class methods declared in this protocol.
1695 NumMethods = PDecl->getNumClassMethods();
1696 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001697 Result += "\nstatic struct _objc_protocol_method_list "
1698 "_OBJC_PROTOCOL_CLASS_METHODS_";
1699 Result += PDecl->getName();
1700 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1701 "{\n\t";
1702 Result += utostr(NumMethods);
1703 Result += "\n";
1704
Fariborz Jahanian04455192007-10-22 21:41:37 +00001705 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001706 Result += "\t,{{(SEL)\"";
1707 Result += Methods[0]->getSelector().getName().c_str();
1708 Result += "\", \"\"}\n";
1709
1710 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001711 Result += "\t ,{(SEL)\"";
1712 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001713 std::string MethodTypeString;
1714 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1715 Result += "\", \"";
1716 Result += MethodTypeString;
1717 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001718 }
1719 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001720 }
1721 // Output:
1722 /* struct _objc_protocol {
1723 // Objective-C 1.0 extensions
1724 struct _objc_protocol_extension *isa;
1725 char *protocol_name;
1726 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001727 struct _objc_protocol_method_list *instance_methods;
1728 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001729 };
1730 */
1731 static bool objc_protocol = false;
1732 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001733 Result += "\nstruct _objc_protocol {\n";
1734 Result += "\tstruct _objc_protocol_extension *isa;\n";
1735 Result += "\tchar *protocol_name;\n";
1736 Result += "\tstruct _objc_protocol **protocol_list;\n";
1737 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1738 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1739 Result += "};\n";
1740
1741 /* struct _objc_protocol_list {
1742 struct _objc_protocol_list *next;
1743 int protocol_count;
1744 struct _objc_protocol *class_protocols[];
1745 }
1746 */
1747 Result += "\nstruct _objc_protocol_list {\n";
1748 Result += "\tstruct _objc_protocol_list *next;\n";
1749 Result += "\tint protocol_count;\n";
1750 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1751 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001752 objc_protocol = true;
1753 }
1754
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001755 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1756 Result += PDecl->getName();
1757 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1758 "{\n\t0, \"";
1759 Result += PDecl->getName();
1760 Result += "\", 0, ";
1761 if (PDecl->getInstanceMethods() > 0) {
1762 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1763 Result += PDecl->getName();
1764 Result += ", ";
1765 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001766 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001767 Result += "0, ";
1768 if (PDecl->getClassMethods() > 0) {
1769 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1770 Result += PDecl->getName();
1771 Result += "\n";
1772 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001773 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001774 Result += "0\n";
1775 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001776 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001777 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001778 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1779 Result += prefix;
1780 Result += "_PROTOCOLS_";
1781 Result += ClassName;
1782 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1783 "{\n\t0, ";
1784 Result += utostr(NumProtocols);
1785 Result += "\n";
1786
1787 Result += "\t,{&_OBJC_PROTOCOL_";
1788 Result += Protocols[0]->getName();
1789 Result += " \n";
1790
1791 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001792 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001793 Result += "\t ,&_OBJC_PROTOCOL_";
1794 Result += PDecl->getName();
1795 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001796 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001797 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001798 }
1799}
1800
1801/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1802/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001803void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1804 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001805 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1806 // Find category declaration for this implementation.
1807 ObjcCategoryDecl *CDecl;
1808 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1809 CDecl = CDecl->getNextClassCategory())
1810 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1811 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001812
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001813 char *FullCategoryName = (char*)alloca(
1814 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1815 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1816
1817 // Build _objc_method_list for class's instance methods if needed
1818 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1819 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001820 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001821 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001822
1823 // Build _objc_method_list for class's class methods if needed
1824 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1825 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001826 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001827 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001828
1829 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001830 // Null CDecl is case of a category implementation with no category interface
1831 if (CDecl)
1832 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1833 CDecl->getNumReferencedProtocols(),
1834 "CATEGORY",
1835 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001836
1837 /* struct _objc_category {
1838 char *category_name;
1839 char *class_name;
1840 struct _objc_method_list *instance_methods;
1841 struct _objc_method_list *class_methods;
1842 struct _objc_protocol_list *protocols;
1843 // Objective-C 1.0 extensions
1844 uint32_t size; // sizeof (struct _objc_category)
1845 struct _objc_property_list *instance_properties; // category's own
1846 // @property decl.
1847 };
1848 */
1849
1850 static bool objc_category = false;
1851 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001852 Result += "\nstruct _objc_category {\n";
1853 Result += "\tchar *category_name;\n";
1854 Result += "\tchar *class_name;\n";
1855 Result += "\tstruct _objc_method_list *instance_methods;\n";
1856 Result += "\tstruct _objc_method_list *class_methods;\n";
1857 Result += "\tstruct _objc_protocol_list *protocols;\n";
1858 Result += "\tunsigned int size;\n";
1859 Result += "\tstruct _objc_property_list *instance_properties;\n";
1860 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001861 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001862 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001863 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1864 Result += FullCategoryName;
1865 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1866 Result += IDecl->getName();
1867 Result += "\"\n\t, \"";
1868 Result += ClassDecl->getName();
1869 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001870
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001871 if (IDecl->getNumInstanceMethods() > 0) {
1872 Result += "\t, (struct _objc_method_list *)"
1873 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1874 Result += FullCategoryName;
1875 Result += "\n";
1876 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001877 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001878 Result += "\t, 0\n";
1879 if (IDecl->getNumClassMethods() > 0) {
1880 Result += "\t, (struct _objc_method_list *)"
1881 "&_OBJC_CATEGORY_CLASS_METHODS_";
1882 Result += FullCategoryName;
1883 Result += "\n";
1884 }
1885 else
1886 Result += "\t, 0\n";
1887
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001888 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001889 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1890 Result += FullCategoryName;
1891 Result += "\n";
1892 }
1893 else
1894 Result += "\t, 0\n";
1895 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001896}
1897
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001898/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1899/// ivar offset.
1900void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1901 ObjcIvarDecl *ivar,
1902 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001903 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001904 Result += IDecl->getName();
1905 Result += ", ";
1906 Result += ivar->getName();
1907 Result += ")";
1908}
1909
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001910//===----------------------------------------------------------------------===//
1911// Meta Data Emission
1912//===----------------------------------------------------------------------===//
1913
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001914void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1915 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001916 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1917
1918 // Build _objc_ivar_list metadata for classes ivars if needed
1919 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1920 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001921 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00001922 // Explictly declared @interface's are already synthesized.
1923 if (CDecl->ImplicitInterfaceDecl()) {
1924 // FIXME: Implementation of a class with no @interface (legacy) doese not
1925 // produce correct synthesis as yet.
1926 SynthesizeObjcInternalStruct(CDecl, Result);
1927 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001928
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001929 if (NumIvars > 0) {
1930 static bool objc_ivar = false;
1931 if (!objc_ivar) {
1932 /* struct _objc_ivar {
1933 char *ivar_name;
1934 char *ivar_type;
1935 int ivar_offset;
1936 };
1937 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001938 Result += "\nstruct _objc_ivar {\n";
1939 Result += "\tchar *ivar_name;\n";
1940 Result += "\tchar *ivar_type;\n";
1941 Result += "\tint ivar_offset;\n";
1942 Result += "};\n";
1943
1944 /* struct _objc_ivar_list {
1945 int ivar_count;
1946 struct _objc_ivar ivar_list[];
1947 };
1948 */
1949 Result += "\nstruct _objc_ivar_list {\n";
1950 Result += "\tint ivar_count;\n";
1951 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001952 objc_ivar = true;
1953 }
1954
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001955 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1956 Result += IDecl->getName();
1957 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1958 "{\n\t";
1959 Result += utostr(NumIvars);
1960 Result += "\n";
1961
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001962 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1963 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001964 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001965 Result += "\t,{{\"";
1966 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001967 Result += "\", \"";
1968 std::string StrEncoding;
1969 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1970 Result += StrEncoding;
1971 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001972 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1973 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001974 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001975 Result += "\t ,{\"";
1976 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001977 Result += "\", \"";
1978 std::string StrEncoding;
1979 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1980 Result += StrEncoding;
1981 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001982 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1983 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001984 }
1985
1986 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001987 }
1988
1989 // Build _objc_method_list for class's instance methods if needed
1990 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1991 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001992 true,
1993 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001994
1995 // Build _objc_method_list for class's class methods if needed
1996 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001997 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001998 false,
1999 "", IDecl->getName(), Result);
2000
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002001 // Protocols referenced in class declaration?
2002 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2003 CDecl->getNumIntfRefProtocols(),
2004 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002005 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002006
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002007
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002008 // Declaration of class/meta-class metadata
2009 /* struct _objc_class {
2010 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002011 const char *super_class_name;
2012 char *name;
2013 long version;
2014 long info;
2015 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002016 struct _objc_ivar_list *ivars;
2017 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002018 struct objc_cache *cache;
2019 struct objc_protocol_list *protocols;
2020 const char *ivar_layout;
2021 struct _objc_class_ext *ext;
2022 };
2023 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002024 static bool objc_class = false;
2025 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002026 Result += "\nstruct _objc_class {\n";
2027 Result += "\tstruct _objc_class *isa;\n";
2028 Result += "\tconst char *super_class_name;\n";
2029 Result += "\tchar *name;\n";
2030 Result += "\tlong version;\n";
2031 Result += "\tlong info;\n";
2032 Result += "\tlong instance_size;\n";
2033 Result += "\tstruct _objc_ivar_list *ivars;\n";
2034 Result += "\tstruct _objc_method_list *methods;\n";
2035 Result += "\tstruct objc_cache *cache;\n";
2036 Result += "\tstruct _objc_protocol_list *protocols;\n";
2037 Result += "\tconst char *ivar_layout;\n";
2038 Result += "\tstruct _objc_class_ext *ext;\n";
2039 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002040 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002041 }
2042
2043 // Meta-class metadata generation.
2044 ObjcInterfaceDecl *RootClass = 0;
2045 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2046 while (SuperClass) {
2047 RootClass = SuperClass;
2048 SuperClass = SuperClass->getSuperClass();
2049 }
2050 SuperClass = CDecl->getSuperClass();
2051
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002052 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2053 Result += CDecl->getName();
2054 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2055 "{\n\t(struct _objc_class *)\"";
2056 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2057 Result += "\"";
2058
2059 if (SuperClass) {
2060 Result += ", \"";
2061 Result += SuperClass->getName();
2062 Result += "\", \"";
2063 Result += CDecl->getName();
2064 Result += "\"";
2065 }
2066 else {
2067 Result += ", 0, \"";
2068 Result += CDecl->getName();
2069 Result += "\"";
2070 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002071 // TODO: 'ivars' field for root class is currently set to 0.
2072 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002073 Result += ", 0,2, sizeof(struct _objc_class), 0";
2074 if (CDecl->getNumClassMethods() > 0) {
2075 Result += "\n\t, &_OBJC_CLASS_METHODS_";
2076 Result += CDecl->getName();
2077 Result += "\n";
2078 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002079 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002080 Result += ", 0\n";
2081 if (CDecl->getNumIntfRefProtocols() > 0) {
2082 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2083 Result += CDecl->getName();
2084 Result += ",0,0\n";
2085 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002086 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002087 Result += "\t,0,0,0,0\n";
2088 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002089
2090 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002091 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2092 Result += CDecl->getName();
2093 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2094 "{\n\t&_OBJC_METACLASS_";
2095 Result += CDecl->getName();
2096 if (SuperClass) {
2097 Result += ", \"";
2098 Result += SuperClass->getName();
2099 Result += "\", \"";
2100 Result += CDecl->getName();
2101 Result += "\"";
2102 }
2103 else {
2104 Result += ", 0, \"";
2105 Result += CDecl->getName();
2106 Result += "\"";
2107 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002108 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002109 Result += ", 0,1";
2110 if (!ObjcSynthesizedStructs.count(CDecl))
2111 Result += ",0";
2112 else {
2113 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002114 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002115 Result += CDecl->getName();
2116 Result += ")";
2117 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002118 if (NumIvars > 0) {
2119 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2120 Result += CDecl->getName();
2121 Result += "\n\t";
2122 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002123 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002124 Result += ",0";
2125 if (IDecl->getNumInstanceMethods() > 0) {
2126 Result += ", &_OBJC_INSTANCE_METHODS_";
2127 Result += CDecl->getName();
2128 Result += ", 0\n\t";
2129 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002130 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002131 Result += ",0,0";
2132 if (CDecl->getNumIntfRefProtocols() > 0) {
2133 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2134 Result += CDecl->getName();
2135 Result += ", 0,0\n";
2136 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002137 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002138 Result += ",0,0,0\n";
2139 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002140}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002141
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002142/// RewriteImplementations - This routine rewrites all method implementations
2143/// and emits meta-data.
2144
2145void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002146 int ClsDefCount = ClassImplementation.size();
2147 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002148
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002149 if (ClsDefCount == 0 && CatDefCount == 0)
2150 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002151 // Rewrite implemented methods
2152 for (int i = 0; i < ClsDefCount; i++)
2153 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002154
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002155 for (int i = 0; i < CatDefCount; i++)
2156 RewriteImplementationDecl(CategoryImplementation[i]);
2157
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002158 // This is needed for use of offsetof
2159 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002160
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002161 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002162 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002163 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002164
2165 // For each implemented category, write out all its meta data.
2166 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002167 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002168
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002169 // Write objc_symtab metadata
2170 /*
2171 struct _objc_symtab
2172 {
2173 long sel_ref_cnt;
2174 SEL *refs;
2175 short cls_def_cnt;
2176 short cat_def_cnt;
2177 void *defs[cls_def_cnt + cat_def_cnt];
2178 };
2179 */
2180
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002181 Result += "\nstruct _objc_symtab {\n";
2182 Result += "\tlong sel_ref_cnt;\n";
2183 Result += "\tSEL *refs;\n";
2184 Result += "\tshort cls_def_cnt;\n";
2185 Result += "\tshort cat_def_cnt;\n";
2186 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2187 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002188
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002189 Result += "static struct _objc_symtab "
2190 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2191 Result += "\t0, 0, " + utostr(ClsDefCount)
2192 + ", " + utostr(CatDefCount) + "\n";
2193 for (int i = 0; i < ClsDefCount; i++) {
2194 Result += "\t,&_OBJC_CLASS_";
2195 Result += ClassImplementation[i]->getName();
2196 Result += "\n";
2197 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002198
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002199 for (int i = 0; i < CatDefCount; i++) {
2200 Result += "\t,&_OBJC_CATEGORY_";
2201 Result += CategoryImplementation[i]->getClassInterface()->getName();
2202 Result += "_";
2203 Result += CategoryImplementation[i]->getName();
2204 Result += "\n";
2205 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002206
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002207 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002208
2209 // Write objc_module metadata
2210
2211 /*
2212 struct _objc_module {
2213 long version;
2214 long size;
2215 const char *name;
2216 struct _objc_symtab *symtab;
2217 }
2218 */
2219
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002220 Result += "\nstruct _objc_module {\n";
2221 Result += "\tlong version;\n";
2222 Result += "\tlong size;\n";
2223 Result += "\tconst char *name;\n";
2224 Result += "\tstruct _objc_symtab *symtab;\n";
2225 Result += "};\n\n";
2226 Result += "static struct _objc_module "
2227 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002228 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2229 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002230 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002231
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002232}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002233