blob: 0a6171c65f2c93b7e8029f205f94e2e5f2863e3b [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000054
Steve Naroff0add5d22007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000058
Steve Naroff764c1ae2007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattnerae43eb72007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenekb3ee1932007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000125
Steve Naroff0744c472007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000128 }
Chris Lattner569faa62007-10-11 18:38:32 +0000129
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000147 void RewriteMethodDeclaration(ObjcMethodDecl *Method);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000154
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000179
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000183
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000186
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000187 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
189 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000194
195 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
196 int NumProtocols,
197 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000200 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
201 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000202 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
203 ObjcIvarDecl *ivar,
204 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattner258f26c2007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000212
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner569faa62007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffe9780582007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000236 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
237 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000238 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
239 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000240 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
241 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000242 } else if (ObjcForwardProtocolDecl *FP =
243 dyn_cast<ObjcForwardProtocolDecl>(D)){
244 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000245 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000253}
254
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000261
262 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff18c83382007-11-13 23:01:27 +0000269 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000270 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
271 ClassImplementation.push_back(CI);
272 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
273 CategoryImplementation.push_back(CI);
274 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
275 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000277 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000289
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000293
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000306}
307
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner74db1682007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000340
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner569faa62007-10-11 18:38:32 +0000364}
365
366
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
368 int numDecls = ClassDecl->getNumForwardDecls();
369 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
384 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000399}
400
Steve Naroff2ce399a2007-12-14 23:37:57 +0000401void RewriteTest::RewriteMethodDeclaration(ObjcMethodDecl *Method) {
402 SourceLocation LocStart = Method->getLocStart();
403 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000404
Steve Naroff2ce399a2007-12-14 23:37:57 +0000405 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
406 Rewrite.InsertText(LocStart, "/* ", 3);
407 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
408 } else {
409 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000410 }
411}
412
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000413void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
414{
415 for (int i = 0; i < nProperties; i++) {
416 ObjcPropertyDecl *Property = Properties[i];
417 SourceLocation Loc = Property->getLocation();
418
419 Rewrite.ReplaceText(Loc, 0, "// ", 3);
420
421 // FIXME: handle properties that are declared across multiple lines.
422 }
423}
424
Steve Naroff667f1682007-10-30 13:30:57 +0000425void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
426 SourceLocation LocStart = CatDecl->getLocStart();
427
428 // FIXME: handle category headers that are declared across multiple lines.
429 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
430
Steve Naroff2ce399a2007-12-14 23:37:57 +0000431 for (ObjcCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
432 E = CatDecl->instmeth_end(); I != E; ++I)
433 RewriteMethodDeclaration(*I);
434 for (ObjcCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
435 E = CatDecl->classmeth_end(); I != E; ++I)
436 RewriteMethodDeclaration(*I);
437
Steve Naroff667f1682007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000442void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000444
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Steve Naroff2ce399a2007-12-14 23:37:57 +0000450 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
451 E = PDecl->instmeth_end(); I != E; ++I)
452 RewriteMethodDeclaration(*I);
453 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
454 E = PDecl->classmeth_end(); I != E; ++I)
455 RewriteMethodDeclaration(*I);
456
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000457 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000458 SourceLocation LocEnd = PDecl->getAtEndLoc();
459 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000460
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000461 // Must comment out @optional/@required
462 const char *startBuf = SM->getCharacterData(LocStart);
463 const char *endBuf = SM->getCharacterData(LocEnd);
464 for (const char *p = startBuf; p < endBuf; p++) {
465 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
466 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000467 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000468 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
469 CommentedOptional.c_str(), CommentedOptional.size());
470
471 }
472 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
473 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000474 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000475 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
476 CommentedRequired.c_str(), CommentedRequired.size());
477
478 }
479 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000480}
481
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000482void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
483 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000484 if (LocStart.isInvalid())
485 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000486 // FIXME: handle forward protocol that are declared across multiple lines.
487 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
488}
489
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000490void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
491 std::string &ResultStr) {
492 ResultStr += "\nstatic ";
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +0000493 if (OMD->getResultType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000494 ResultStr += "id";
495 else
496 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000497 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000498
499 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000500 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000501
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000502 if (OMD->isInstance())
503 NameStr += "_I_";
504 else
505 NameStr += "_C_";
506
507 NameStr += OMD->getClassInterface()->getName();
508 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000509
510 NamedDecl *MethodContext = OMD->getMethodContext();
511 if (ObjcCategoryImplDecl *CID =
512 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000513 NameStr += CID->getName();
514 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000515 }
516 // Append selector names, replacing ':' with '_'
517 const char *selName = OMD->getSelector().getName().c_str();
518 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000519 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000520 else {
521 std::string selString = OMD->getSelector().getName();
522 int len = selString.size();
523 for (int i = 0; i < len; i++)
524 if (selString[i] == ':')
525 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000526 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000527 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000528 // Remember this name for metadata emission
529 MethodInternalNames[OMD] = NameStr;
530 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000531
532 // Rewrite arguments
533 ResultStr += "(";
534
535 // invisible arguments
536 if (OMD->isInstance()) {
537 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
538 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000539 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
540 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000541 ResultStr += selfTy.getAsString();
542 }
543 else
544 ResultStr += Context->getObjcIdType().getAsString();
545
546 ResultStr += " self, ";
547 ResultStr += Context->getObjcSelType().getAsString();
548 ResultStr += " _cmd";
549
550 // Method arguments.
551 for (int i = 0; i < OMD->getNumParams(); i++) {
552 ParmVarDecl *PDecl = OMD->getParamDecl(i);
553 ResultStr += ", ";
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +0000554 if (PDecl->getType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000555 ResultStr += "id";
556 else
557 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000558 ResultStr += " ";
559 ResultStr += PDecl->getName();
560 }
561 ResultStr += ")";
562
563}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000564void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
565 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
566 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000567
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000568 if (IMD)
569 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
570 else
571 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000572
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000573 for (ObjcCategoryImplDecl::instmeth_iterator
574 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
575 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000576 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000577 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000578 RewriteObjcMethodDecl(OMD, ResultStr);
579 SourceLocation LocStart = OMD->getLocStart();
580 SourceLocation LocEnd = OMD->getBody()->getLocStart();
581
582 const char *startBuf = SM->getCharacterData(LocStart);
583 const char *endBuf = SM->getCharacterData(LocEnd);
584 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
585 ResultStr.c_str(), ResultStr.size());
586 }
587
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000588 for (ObjcCategoryImplDecl::classmeth_iterator
589 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
590 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000591 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000592 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000593 RewriteObjcMethodDecl(OMD, ResultStr);
594 SourceLocation LocStart = OMD->getLocStart();
595 SourceLocation LocEnd = OMD->getBody()->getLocStart();
596
597 const char *startBuf = SM->getCharacterData(LocStart);
598 const char *endBuf = SM->getCharacterData(LocEnd);
599 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
600 ResultStr.c_str(), ResultStr.size());
601 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000602 if (IMD)
603 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
604 else
605 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000606}
607
Steve Naroff3774dd92007-10-26 20:53:56 +0000608void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000609 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000610 if (!ObjcForwardDecls.count(ClassDecl)) {
611 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000612 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000613 ResultStr += ClassDecl->getName();
614 ResultStr += "\n";
615 ResultStr += "#define _REWRITER_typedef_";
616 ResultStr += ClassDecl->getName();
617 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000618 ResultStr += "typedef struct ";
619 ResultStr += ClassDecl->getName();
620 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000621 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000622 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000623
624 // Mark this typedef as having been generated.
625 ObjcForwardDecls.insert(ClassDecl);
626 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000627 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
628
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000629 RewriteProperties(ClassDecl->getNumPropertyDecl(),
630 ClassDecl->getPropertyDecl());
Steve Naroff2ce399a2007-12-14 23:37:57 +0000631 for (ObjcInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
632 E = ClassDecl->instmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
634 for (ObjcInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
635 E = ClassDecl->classmeth_end(); I != E; ++I)
636 RewriteMethodDeclaration(*I);
637
Steve Naroff1ccf4632007-10-30 03:43:13 +0000638 // Lastly, comment out the @end.
639 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000640}
641
Steve Naroff6b759ce2007-11-15 02:58:25 +0000642Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
643 ObjcIvarDecl *D = IV->getDecl();
644 if (IV->isFreeIvar()) {
645 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
646 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000647 if (Rewrite.ReplaceStmt(IV, Replacement)) {
648 // replacement failed.
649 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
650 "rewriter could not replace sub-expression due to macros");
651 SourceRange Range = IV->getSourceRange();
652 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
653 delete IV;
654 return Replacement;
655 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000656 delete IV;
657 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000658 } else {
659 if (CurMethodDecl) {
660 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
661 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
662 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
663 IdentifierInfo *II = intT->getDecl()->getIdentifier();
664 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
665 II, 0);
666 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
667
668 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
669 // Don't forget the parens to enforce the proper binding.
670 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000671 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
672 // replacement failed.
673 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
674 "rewriter could not replace sub-expression due to macros");
675 SourceRange Range = IV->getBase()->getSourceRange();
676 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
677 delete IV->getBase();
678 return PE;
679 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000680 delete IV->getBase();
681 return PE;
682 }
683 }
684 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000685 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000686 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000687}
688
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000689//===----------------------------------------------------------------------===//
690// Function Body / Expression rewriting
691//===----------------------------------------------------------------------===//
692
Steve Naroff334fbc22007-11-09 15:20:18 +0000693Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000694 // Otherwise, just rewrite all children.
695 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
696 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000697 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000698 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000699 if (newStmt)
700 *CI = newStmt;
701 }
Steve Naroffe9780582007-10-23 23:50:29 +0000702
703 // Handle specific things.
704 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
705 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000706
707 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
708 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000709
710 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
711 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000712
713 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
714 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000715
Steve Naroff71226032007-10-24 22:48:43 +0000716 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
717 // Before we rewrite it, put the original message expression in a comment.
718 SourceLocation startLoc = MessExpr->getLocStart();
719 SourceLocation endLoc = MessExpr->getLocEnd();
720
721 const char *startBuf = SM->getCharacterData(startLoc);
722 const char *endBuf = SM->getCharacterData(endLoc);
723
724 std::string messString;
725 messString += "// ";
726 messString.append(startBuf, endBuf-startBuf+1);
727 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000728
Steve Naroff71226032007-10-24 22:48:43 +0000729 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
730 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
731 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000732 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000733 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000734 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000735
736 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
737 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000738
739 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
740 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000741
742 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
743 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000744#if 0
745 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
746 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
747 // Get the new text.
748 std::ostringstream Buf;
749 Replacement->printPretty(Buf);
750 const std::string &Str = Buf.str();
751
752 printf("CAST = %s\n", &Str[0]);
753 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
754 delete S;
755 return Replacement;
756 }
757#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000758 // Return this stmt unmodified.
759 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000760}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000761
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000762Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000763 // Get the start location and compute the semi location.
764 SourceLocation startLoc = S->getLocStart();
765 const char *startBuf = SM->getCharacterData(startLoc);
766
767 assert((*startBuf == '@') && "bogus @try location");
768
769 std::string buf;
770 // declare a new scope with two variables, _stack and _rethrow.
771 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
772 buf += "int buf[18/*32-bit i386*/];\n";
773 buf += "char *pointers[4];} _stack;\n";
774 buf += "id volatile _rethrow = 0;\n";
775 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000776 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000777
778 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
779
780 startLoc = S->getTryBody()->getLocEnd();
781 startBuf = SM->getCharacterData(startLoc);
782
783 assert((*startBuf == '}') && "bogus @try block");
784
785 SourceLocation lastCurlyLoc = startLoc;
786
787 startLoc = startLoc.getFileLocWithOffset(1);
788 buf = " /* @catch begin */ else {\n";
789 buf += " id _caught = objc_exception_extract(&_stack);\n";
790 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000791 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000792 buf += " _rethrow = objc_exception_extract(&_stack);\n";
793 buf += " else { /* @catch continue */";
794
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000795 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000796
797 bool sawIdTypedCatch = false;
798 Stmt *lastCatchBody = 0;
799 ObjcAtCatchStmt *catchList = S->getCatchStmts();
800 while (catchList) {
801 Stmt *catchStmt = catchList->getCatchParamStmt();
802
803 if (catchList == S->getCatchStmts())
804 buf = "if ("; // we are generating code for the first catch clause
805 else
806 buf = "else if (";
807 startLoc = catchList->getLocStart();
808 startBuf = SM->getCharacterData(startLoc);
809
810 assert((*startBuf == '@') && "bogus @catch location");
811
812 const char *lParenLoc = strchr(startBuf, '(');
813
814 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
815 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
816 if (t == Context->getObjcIdType()) {
817 buf += "1) { ";
818 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
819 buf.c_str(), buf.size());
820 sawIdTypedCatch = true;
821 } else if (const PointerType *pType = t->getAsPointerType()) {
822 ObjcInterfaceType *cls; // Should be a pointer to a class.
823
824 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
825 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000826 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000827 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000828 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000829 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
830 buf.c_str(), buf.size());
831 }
832 }
833 // Now rewrite the body...
834 lastCatchBody = catchList->getCatchBody();
835 SourceLocation rParenLoc = catchList->getRParenLoc();
836 SourceLocation bodyLoc = lastCatchBody->getLocStart();
837 const char *bodyBuf = SM->getCharacterData(bodyLoc);
838 const char *rParenBuf = SM->getCharacterData(rParenLoc);
839 assert((*rParenBuf == ')') && "bogus @catch paren location");
840 assert((*bodyBuf == '{') && "bogus @catch body location");
841
842 buf = " = _caught;";
843 // Here we replace ") {" with "= _caught;" (which initializes and
844 // declares the @catch parameter).
845 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
846 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000847 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000848 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000849 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000850 catchList = catchList->getNextCatchStmt();
851 }
852 // Complete the catch list...
853 if (lastCatchBody) {
854 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
855 const char *bodyBuf = SM->getCharacterData(bodyLoc);
856 assert((*bodyBuf == '}') && "bogus @catch body location");
857 bodyLoc = bodyLoc.getFileLocWithOffset(1);
858 buf = " } } /* @catch end */\n";
859
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000860 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000861
862 // Set lastCurlyLoc
863 lastCurlyLoc = lastCatchBody->getLocEnd();
864 }
865 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
866 startLoc = finalStmt->getLocStart();
867 startBuf = SM->getCharacterData(startLoc);
868 assert((*startBuf == '@') && "bogus @finally start");
869
870 buf = "/* @finally */";
871 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
872
873 Stmt *body = finalStmt->getFinallyBody();
874 SourceLocation startLoc = body->getLocStart();
875 SourceLocation endLoc = body->getLocEnd();
876 const char *startBuf = SM->getCharacterData(startLoc);
877 const char *endBuf = SM->getCharacterData(endLoc);
878 assert((*startBuf == '{') && "bogus @finally body location");
879 assert((*endBuf == '}') && "bogus @finally body location");
880
881 startLoc = startLoc.getFileLocWithOffset(1);
882 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000883 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000884 endLoc = endLoc.getFileLocWithOffset(-1);
885 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000886 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000887
888 // Set lastCurlyLoc
889 lastCurlyLoc = body->getLocEnd();
890 }
891 // Now emit the final closing curly brace...
892 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
893 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000894 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000895 return 0;
896}
897
898Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
899 return 0;
900}
901
902Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
903 return 0;
904}
905
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000906// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
907// the throw expression is typically a message expression that's already
908// been rewritten! (which implies the SourceLocation's are invalid).
909Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
910 // Get the start location and compute the semi location.
911 SourceLocation startLoc = S->getLocStart();
912 const char *startBuf = SM->getCharacterData(startLoc);
913
914 assert((*startBuf == '@') && "bogus @throw location");
915
916 std::string buf;
917 /* void objc_exception_throw(id) __attribute__((noreturn)); */
918 buf = "objc_exception_throw(";
919 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
920 const char *semiBuf = strchr(startBuf, ';');
921 assert((*semiBuf == ';') && "@throw: can't find ';'");
922 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
923 buf = ");";
924 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
925 return 0;
926}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000927
Chris Lattner0021f452007-10-24 16:57:36 +0000928Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000929 // Create a new string expression.
930 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000931 std::string StrEncoding;
932 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
933 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
934 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000935 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000936 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
937 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000938 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
939 "rewriter could not replace sub-expression due to macros");
940 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000941 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner217df512007-12-02 01:09:57 +0000942 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000943 return Exp;
944 }
945
Chris Lattner4478db92007-11-30 22:53:43 +0000946 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000947 delete Exp;
948 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000949}
950
Steve Naroff296b74f2007-11-05 14:50:49 +0000951Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
952 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
953 // Create a call to sel_registerName("selName").
954 llvm::SmallVector<Expr*, 8> SelExprs;
955 QualType argType = Context->getPointerType(Context->CharTy);
956 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
957 Exp->getSelector().getName().size(),
958 false, argType, SourceLocation(),
959 SourceLocation()));
960 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
961 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000962 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
963 // replacement failed.
964 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
965 "rewriter could not replace sub-expression due to macros");
966 SourceRange Range = Exp->getSourceRange();
967 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
968 delete SelExp;
969 return Exp;
970 }
Steve Naroff296b74f2007-11-05 14:50:49 +0000971 delete Exp;
972 return SelExp;
973}
974
Steve Naroff71226032007-10-24 22:48:43 +0000975CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
976 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000977 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000978 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000979
980 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000981 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000982
983 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000984 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000985 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
986
987 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000988
Steve Naroff71226032007-10-24 22:48:43 +0000989 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
990}
991
Steve Naroffc8a92d12007-11-01 13:24:47 +0000992static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
993 const char *&startRef, const char *&endRef) {
994 while (startBuf < endBuf) {
995 if (*startBuf == '<')
996 startRef = startBuf; // mark the start.
997 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000998 if (startRef && *startRef == '<') {
999 endRef = startBuf; // mark the end.
1000 return true;
1001 }
1002 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001003 }
1004 startBuf++;
1005 }
1006 return false;
1007}
1008
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001009static void scanToNextArgument(const char *&argRef) {
1010 int angle = 0;
1011 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1012 if (*argRef == '<')
1013 angle++;
1014 else if (*argRef == '>')
1015 angle--;
1016 argRef++;
1017 }
1018 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1019}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001020
Steve Naroffc8a92d12007-11-01 13:24:47 +00001021bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001022
Steve Naroffc8a92d12007-11-01 13:24:47 +00001023 if (T == Context->getObjcIdType())
1024 return true;
1025
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001026 if (T->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001027 return true;
1028
Steve Naroffc8a92d12007-11-01 13:24:47 +00001029 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001030 Type *pointeeType = pType->getPointeeType().getTypePtr();
1031 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1032 return true; // we have "Class <Protocol> *".
1033 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001034 return false;
1035}
1036
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001037void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001038 SourceLocation Loc;
1039 QualType Type;
1040 const FunctionTypeProto *proto = 0;
1041 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1042 Loc = VD->getLocation();
1043 Type = VD->getType();
1044 }
1045 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1046 Loc = FD->getLocation();
1047 // Check for ObjC 'id' and class types that have been adorned with protocol
1048 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1049 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1050 assert(funcType && "missing function type");
1051 proto = dyn_cast<FunctionTypeProto>(funcType);
1052 if (!proto)
1053 return;
1054 Type = proto->getResultType();
1055 }
1056 else
1057 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001058
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001059 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001060 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001061
1062 const char *endBuf = SM->getCharacterData(Loc);
1063 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001064 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001065 startBuf--; // scan backward (from the decl location) for return type.
1066 const char *startRef = 0, *endRef = 0;
1067 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1068 // Get the locations of the startRef, endRef.
1069 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1070 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1071 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001072 Rewrite.InsertText(LessLoc, "/*", 2);
1073 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001074 }
1075 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001076 if (!proto)
1077 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001078 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001079 const char *startBuf = SM->getCharacterData(Loc);
1080 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001081 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1082 if (needToScanForQualifiers(proto->getArgType(i))) {
1083 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001084
Steve Naroffc8a92d12007-11-01 13:24:47 +00001085 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001086 // scan forward (from the decl location) for argument types.
1087 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001088 const char *startRef = 0, *endRef = 0;
1089 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1090 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001091 SourceLocation LessLoc =
1092 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1093 SourceLocation GreaterLoc =
1094 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001095 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001096 Rewrite.InsertText(LessLoc, "/*", 2);
1097 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001098 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001099 startBuf = ++endBuf;
1100 }
1101 else {
1102 while (*startBuf != ')' && *startBuf != ',')
1103 startBuf++; // scan forward (from the decl location) for argument types.
1104 startBuf++;
1105 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001106 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001107}
1108
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001109// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1110void RewriteTest::SynthSelGetUidFunctionDecl() {
1111 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1112 llvm::SmallVector<QualType, 16> ArgTys;
1113 ArgTys.push_back(Context->getPointerType(
1114 Context->CharTy.getQualifiedType(QualType::Const)));
1115 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1116 &ArgTys[0], ArgTys.size(),
1117 false /*isVariadic*/);
1118 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1119 SelGetUidIdent, getFuncType,
1120 FunctionDecl::Extern, false, 0);
1121}
1122
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001123// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1124void RewriteTest::SynthGetProtocolFunctionDecl() {
1125 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1126 llvm::SmallVector<QualType, 16> ArgTys;
1127 ArgTys.push_back(Context->getPointerType(
1128 Context->CharTy.getQualifiedType(QualType::Const)));
1129 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1130 &ArgTys[0], ArgTys.size(),
1131 false /*isVariadic*/);
1132 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1133 SelGetProtoIdent, getFuncType,
1134 FunctionDecl::Extern, false, 0);
1135}
1136
Steve Naroff02a82aa2007-10-30 23:14:51 +00001137void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1138 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001139 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001140 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001141 return;
1142 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001143 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001144}
1145
1146// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1147void RewriteTest::SynthMsgSendFunctionDecl() {
1148 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1149 llvm::SmallVector<QualType, 16> ArgTys;
1150 QualType argT = Context->getObjcIdType();
1151 assert(!argT.isNull() && "Can't find 'id' type");
1152 ArgTys.push_back(argT);
1153 argT = Context->getObjcSelType();
1154 assert(!argT.isNull() && "Can't find 'SEL' type");
1155 ArgTys.push_back(argT);
1156 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1157 &ArgTys[0], ArgTys.size(),
1158 true /*isVariadic*/);
1159 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1160 msgSendIdent, msgSendType,
1161 FunctionDecl::Extern, false, 0);
1162}
1163
Steve Naroff764c1ae2007-11-15 10:28:18 +00001164// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1165void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1166 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1167 llvm::SmallVector<QualType, 16> ArgTys;
1168 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1169 &Context->Idents.get("objc_super"), 0);
1170 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1171 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1172 ArgTys.push_back(argT);
1173 argT = Context->getObjcSelType();
1174 assert(!argT.isNull() && "Can't find 'SEL' type");
1175 ArgTys.push_back(argT);
1176 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1177 &ArgTys[0], ArgTys.size(),
1178 true /*isVariadic*/);
1179 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1180 msgSendIdent, msgSendType,
1181 FunctionDecl::Extern, false, 0);
1182}
1183
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001184// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1185void RewriteTest::SynthMsgSendStretFunctionDecl() {
1186 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1187 llvm::SmallVector<QualType, 16> ArgTys;
1188 QualType argT = Context->getObjcIdType();
1189 assert(!argT.isNull() && "Can't find 'id' type");
1190 ArgTys.push_back(argT);
1191 argT = Context->getObjcSelType();
1192 assert(!argT.isNull() && "Can't find 'SEL' type");
1193 ArgTys.push_back(argT);
1194 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1195 &ArgTys[0], ArgTys.size(),
1196 true /*isVariadic*/);
1197 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1198 msgSendIdent, msgSendType,
1199 FunctionDecl::Extern, false, 0);
1200}
1201
1202// SynthMsgSendSuperStretFunctionDecl -
1203// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1204void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1205 IdentifierInfo *msgSendIdent =
1206 &Context->Idents.get("objc_msgSendSuper_stret");
1207 llvm::SmallVector<QualType, 16> ArgTys;
1208 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1209 &Context->Idents.get("objc_super"), 0);
1210 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1211 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1212 ArgTys.push_back(argT);
1213 argT = Context->getObjcSelType();
1214 assert(!argT.isNull() && "Can't find 'SEL' type");
1215 ArgTys.push_back(argT);
1216 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1217 &ArgTys[0], ArgTys.size(),
1218 true /*isVariadic*/);
1219 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1220 msgSendIdent, msgSendType,
1221 FunctionDecl::Extern, false, 0);
1222}
1223
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001224// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1225void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1226 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1227 llvm::SmallVector<QualType, 16> ArgTys;
1228 QualType argT = Context->getObjcIdType();
1229 assert(!argT.isNull() && "Can't find 'id' type");
1230 ArgTys.push_back(argT);
1231 argT = Context->getObjcSelType();
1232 assert(!argT.isNull() && "Can't find 'SEL' type");
1233 ArgTys.push_back(argT);
1234 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1235 &ArgTys[0], ArgTys.size(),
1236 true /*isVariadic*/);
1237 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1238 msgSendIdent, msgSendType,
1239 FunctionDecl::Extern, false, 0);
1240}
1241
Steve Naroff02a82aa2007-10-30 23:14:51 +00001242// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1243void RewriteTest::SynthGetClassFunctionDecl() {
1244 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1245 llvm::SmallVector<QualType, 16> ArgTys;
1246 ArgTys.push_back(Context->getPointerType(
1247 Context->CharTy.getQualifiedType(QualType::Const)));
1248 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1249 &ArgTys[0], ArgTys.size(),
1250 false /*isVariadic*/);
1251 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1252 getClassIdent, getClassType,
1253 FunctionDecl::Extern, false, 0);
1254}
1255
Steve Naroff3b1caac2007-12-07 03:50:46 +00001256// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1257void RewriteTest::SynthGetMetaClassFunctionDecl() {
1258 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1259 llvm::SmallVector<QualType, 16> ArgTys;
1260 ArgTys.push_back(Context->getPointerType(
1261 Context->CharTy.getQualifiedType(QualType::Const)));
1262 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1263 &ArgTys[0], ArgTys.size(),
1264 false /*isVariadic*/);
1265 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1266 getClassIdent, getClassType,
1267 FunctionDecl::Extern, false, 0);
1268}
1269
Steve Naroffabb96362007-11-08 14:30:50 +00001270// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1271void RewriteTest::SynthCFStringFunctionDecl() {
1272 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1273 llvm::SmallVector<QualType, 16> ArgTys;
1274 ArgTys.push_back(Context->getPointerType(
1275 Context->CharTy.getQualifiedType(QualType::Const)));
1276 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1277 &ArgTys[0], ArgTys.size(),
1278 false /*isVariadic*/);
1279 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1280 getClassIdent, getClassType,
1281 FunctionDecl::Extern, false, 0);
1282}
1283
Steve Naroff0add5d22007-11-03 11:27:19 +00001284Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001285#if 1
1286 // This rewrite is specific to GCC, which has builtin support for CFString.
1287 if (!CFStringFunctionDecl)
1288 SynthCFStringFunctionDecl();
1289 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1290 llvm::SmallVector<Expr*, 8> StrExpr;
1291 StrExpr.push_back(Exp->getString());
1292 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1293 &StrExpr[0], StrExpr.size());
1294 // cast to NSConstantString *
1295 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001296 if (Rewrite.ReplaceStmt(Exp, cast)) {
1297 // replacement failed.
1298 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
1299 "rewriter could not replace sub-expression due to macros");
1300 SourceRange Range = Exp->getSourceRange();
1301 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
1302 delete cast;
1303 return Exp;
1304 }
Steve Naroffabb96362007-11-08 14:30:50 +00001305 delete Exp;
1306 return cast;
1307#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001308 assert(ConstantStringClassReference && "Can't find constant string reference");
1309 llvm::SmallVector<Expr*, 4> InitExprs;
1310
1311 // Synthesize "(Class)&_NSConstantStringClassReference"
1312 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1313 ConstantStringClassReference->getType(),
1314 SourceLocation());
1315 QualType expType = Context->getPointerType(ClsRef->getType());
1316 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1317 expType, SourceLocation());
1318 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1319 SourceLocation());
1320 InitExprs.push_back(cast); // set the 'isa'.
1321 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1322 unsigned IntSize = static_cast<unsigned>(
1323 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1324 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1325 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1326 Exp->getLocStart());
1327 InitExprs.push_back(len); // set "int numBytes".
1328
1329 // struct NSConstantString
1330 QualType CFConstantStrType = Context->getCFConstantStringType();
1331 // (struct NSConstantString) { <exprs from above> }
1332 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1333 &InitExprs[0], InitExprs.size(),
1334 SourceLocation());
1335 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1336 // struct NSConstantString *
1337 expType = Context->getPointerType(StrRep->getType());
1338 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1339 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001340 // cast to NSConstantString *
1341 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001342 Rewrite.ReplaceStmt(Exp, cast);
1343 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001344 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001345#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001346}
1347
Steve Naroff764c1ae2007-11-15 10:28:18 +00001348ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001349 // check if we are sending a message to 'super'
1350 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001351 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1353 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1354 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001355 // is this id<P1..> type?
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001356 if (CE->getType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001357 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001358 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1359 if (ObjcInterfaceType *IT =
1360 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1361 if (IT->getDecl() ==
1362 CurMethodDecl->getClassInterface()->getSuperClass())
1363 return IT->getDecl();
1364 }
1365 }
1366 }
1367 }
1368 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001369 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001370 }
1371 return 0;
1372}
1373
1374// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1375QualType RewriteTest::getSuperStructType() {
1376 if (!SuperStructDecl) {
1377 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1378 &Context->Idents.get("objc_super"), 0);
1379 QualType FieldTypes[2];
1380
1381 // struct objc_object *receiver;
1382 FieldTypes[0] = Context->getObjcIdType();
1383 // struct objc_class *super;
1384 FieldTypes[1] = Context->getObjcClassType();
1385 // Create fields
1386 FieldDecl *FieldDecls[2];
1387
1388 for (unsigned i = 0; i < 2; ++i)
1389 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1390
1391 SuperStructDecl->defineBody(FieldDecls, 4);
1392 }
1393 return Context->getTagDeclType(SuperStructDecl);
1394}
1395
Steve Naroff71226032007-10-24 22:48:43 +00001396Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001397 if (!SelGetUidFunctionDecl)
1398 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001399 if (!MsgSendFunctionDecl)
1400 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001401 if (!MsgSendSuperFunctionDecl)
1402 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001403 if (!MsgSendStretFunctionDecl)
1404 SynthMsgSendStretFunctionDecl();
1405 if (!MsgSendSuperStretFunctionDecl)
1406 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001407 if (!MsgSendFpretFunctionDecl)
1408 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001409 if (!GetClassFunctionDecl)
1410 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001411 if (!GetMetaClassFunctionDecl)
1412 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001413
Steve Naroff764c1ae2007-11-15 10:28:18 +00001414 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001415 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1416 // May need to use objc_msgSend_stret() as well.
1417 FunctionDecl *MsgSendStretFlavor = 0;
1418 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1419 QualType resultType = mDecl->getResultType();
1420 if (resultType.getCanonicalType()->isStructureType()
1421 || resultType.getCanonicalType()->isUnionType())
1422 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001423 else if (resultType.getCanonicalType()->isRealFloatingType())
1424 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001425 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001426
Steve Naroff71226032007-10-24 22:48:43 +00001427 // Synthesize a call to objc_msgSend().
1428 llvm::SmallVector<Expr*, 8> MsgExprs;
1429 IdentifierInfo *clsName = Exp->getClassName();
1430
1431 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1432 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001433 if (!strcmp(clsName->getName(), "super")) {
1434 MsgSendFlavor = MsgSendSuperFunctionDecl;
1435 if (MsgSendStretFlavor)
1436 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1437 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1438
1439 ObjcInterfaceDecl *SuperDecl =
1440 CurMethodDecl->getClassInterface()->getSuperClass();
1441
1442 llvm::SmallVector<Expr*, 4> InitExprs;
1443
1444 // set the receiver to self, the first argument to all methods.
1445 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1446 Context->getObjcIdType(),
1447 SourceLocation()));
1448 llvm::SmallVector<Expr*, 8> ClsExprs;
1449 QualType argType = Context->getPointerType(Context->CharTy);
1450 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1451 SuperDecl->getIdentifier()->getLength(),
1452 false, argType, SourceLocation(),
1453 SourceLocation()));
1454 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1455 &ClsExprs[0],
1456 ClsExprs.size());
1457 // To turn off a warning, type-cast to 'id'
1458 InitExprs.push_back(
1459 new CastExpr(Context->getObjcIdType(),
1460 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1461 // struct objc_super
1462 QualType superType = getSuperStructType();
1463 // (struct objc_super) { <exprs from above> }
1464 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1465 &InitExprs[0], InitExprs.size(),
1466 SourceLocation());
1467 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1468 // struct objc_super *
1469 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1470 Context->getPointerType(SuperRep->getType()),
1471 SourceLocation());
1472 MsgExprs.push_back(Unop);
1473 } else {
1474 llvm::SmallVector<Expr*, 8> ClsExprs;
1475 QualType argType = Context->getPointerType(Context->CharTy);
1476 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1477 clsName->getLength(),
1478 false, argType, SourceLocation(),
1479 SourceLocation()));
1480 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1481 &ClsExprs[0],
1482 ClsExprs.size());
1483 MsgExprs.push_back(Cls);
1484 }
Steve Naroff885e2122007-11-14 23:54:14 +00001485 } else { // instance message.
1486 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001487
Steve Naroff3b1caac2007-12-07 03:50:46 +00001488 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001489 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001490 if (MsgSendStretFlavor)
1491 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001492 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1493
1494 llvm::SmallVector<Expr*, 4> InitExprs;
1495
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001496 InitExprs.push_back(
1497 new CastExpr(Context->getObjcIdType(),
1498 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001499
1500 llvm::SmallVector<Expr*, 8> ClsExprs;
1501 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001502 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1503 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001504 false, argType, SourceLocation(),
1505 SourceLocation()));
1506 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001507 &ClsExprs[0],
1508 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001509 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001510 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001511 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001512 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001513 // struct objc_super
1514 QualType superType = getSuperStructType();
1515 // (struct objc_super) { <exprs from above> }
1516 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1517 &InitExprs[0], InitExprs.size(),
1518 SourceLocation());
1519 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1520 // struct objc_super *
1521 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1522 Context->getPointerType(SuperRep->getType()),
1523 SourceLocation());
1524 MsgExprs.push_back(Unop);
1525 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001526 // Remove all type-casts because it may contain objc-style types; e.g.
1527 // Foo<Proto> *.
1528 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1529 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001530 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1531 MsgExprs.push_back(recExpr);
1532 }
Steve Naroff885e2122007-11-14 23:54:14 +00001533 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001534 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001535 llvm::SmallVector<Expr*, 8> SelExprs;
1536 QualType argType = Context->getPointerType(Context->CharTy);
1537 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1538 Exp->getSelector().getName().size(),
1539 false, argType, SourceLocation(),
1540 SourceLocation()));
1541 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1542 &SelExprs[0], SelExprs.size());
1543 MsgExprs.push_back(SelExp);
1544
1545 // Now push any user supplied arguments.
1546 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001547 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001548 // Make all implicit casts explicit...ICE comes in handy:-)
1549 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1550 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001551 userExpr = new CastExpr(ICE->getType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001552 ? Context->getObjcIdType()
1553 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001554 }
1555 // Make id<P...> cast into an 'id' cast.
1556 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
1557 if (CE->getType()->isObjcQualifiedIdType()) {
1558 while ((CE = dyn_cast<CastExpr>(userExpr)))
1559 userExpr = CE->getSubExpr();
1560 userExpr = new CastExpr(Context->getObjcIdType(),
1561 userExpr, SourceLocation());
1562 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001563 }
Steve Naroff885e2122007-11-14 23:54:14 +00001564 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001565 // We've transferred the ownership to MsgExprs. Null out the argument in
1566 // the original expression, since we will delete it below.
1567 Exp->setArg(i, 0);
1568 }
Steve Naroff0744c472007-11-04 22:37:50 +00001569 // Generate the funky cast.
1570 CastExpr *cast;
1571 llvm::SmallVector<QualType, 8> ArgTypes;
1572 QualType returnType;
1573
1574 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001575 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1576 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1577 else
1578 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001579 ArgTypes.push_back(Context->getObjcSelType());
1580 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1581 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001582 for (int i = 0; i < mDecl->getNumParams(); i++) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001583 QualType t = mDecl->getParamDecl(i)->getType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001584 ? Context->getObjcIdType()
1585 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001586 ArgTypes.push_back(t);
1587 }
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001588 returnType = mDecl->getResultType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001589 ? Context->getObjcIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001590 } else {
1591 returnType = Context->getObjcIdType();
1592 }
1593 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001594 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001595
1596 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001597 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1598 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001599
1600 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1601 // If we don't do this cast, we get the following bizarre warning/note:
1602 // xx.m:13: warning: function called through a non-compatible type
1603 // xx.m:13: note: if this code is reached, the program will abort
1604 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1605 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001606
Steve Naroff0744c472007-11-04 22:37:50 +00001607 // Now do the "normal" pointer to function cast.
1608 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001609 &ArgTypes[0], ArgTypes.size(),
1610 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001611 castType = Context->getPointerType(castType);
1612 cast = new CastExpr(castType, cast, SourceLocation());
1613
1614 // Don't forget the parens to enforce the proper binding.
1615 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1616
1617 const FunctionType *FT = msgSendType->getAsFunctionType();
1618 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1619 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001620 if (MsgSendStretFlavor) {
1621 // We have the method which returns a struct/union. Must also generate
1622 // call to objc_msgSend_stret and hang both varieties on a conditional
1623 // expression which dictate which one to envoke depending on size of
1624 // method's return type.
1625
1626 // Create a reference to the objc_msgSend_stret() declaration.
1627 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1628 SourceLocation());
1629 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1630 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1631 SourceLocation());
1632 // Now do the "normal" pointer to function cast.
1633 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001634 &ArgTypes[0], ArgTypes.size(),
1635 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001636 castType = Context->getPointerType(castType);
1637 cast = new CastExpr(castType, cast, SourceLocation());
1638
1639 // Don't forget the parens to enforce the proper binding.
1640 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1641
1642 FT = msgSendType->getAsFunctionType();
1643 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1644 FT->getResultType(), SourceLocation());
1645
1646 // Build sizeof(returnType)
1647 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1648 returnType, Context->getSizeType(),
1649 SourceLocation(), SourceLocation());
1650 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1651 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1652 // For X86 it is more complicated and some kind of target specific routine
1653 // is needed to decide what to do.
1654 unsigned IntSize = static_cast<unsigned>(
1655 Context->getTypeSize(Context->IntTy, SourceLocation()));
1656
1657 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1658 Context->IntTy,
1659 SourceLocation());
1660 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1661 BinaryOperator::LE,
1662 Context->IntTy,
1663 SourceLocation());
1664 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1665 ConditionalOperator *CondExpr =
1666 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1667 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1668 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001669 if (Rewrite.ReplaceStmt(Exp, PE)) {
1670 // replacement failed.
1671 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
1672 "rewriter could not replace sub-expression due to macros");
1673 SourceRange Range = Exp->getSourceRange();
1674 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
1675 delete PE;
1676 return Exp;
1677 }
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001678 delete Exp;
1679 return PE;
1680 }
Steve Naroff71226032007-10-24 22:48:43 +00001681 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001682 if (Rewrite.ReplaceStmt(Exp, CE)) {
1683 // replacement failed.
1684 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
1685 "rewriter could not replace sub-expression due to macros");
1686 SourceRange Range = Exp->getSourceRange();
1687 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
1688 delete CE;
1689 return Exp;
1690 }
Steve Naroff71226032007-10-24 22:48:43 +00001691
Chris Lattner0021f452007-10-24 16:57:36 +00001692 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001693 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001694}
1695
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001696/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1697/// call to objc_getProtocol("proto-name").
1698Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1699 if (!GetProtocolFunctionDecl)
1700 SynthGetProtocolFunctionDecl();
1701 // Create a call to objc_getProtocol("ProtocolName").
1702 llvm::SmallVector<Expr*, 8> ProtoExprs;
1703 QualType argType = Context->getPointerType(Context->CharTy);
1704 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1705 strlen(Exp->getProtocol()->getName()),
1706 false, argType, SourceLocation(),
1707 SourceLocation()));
1708 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1709 &ProtoExprs[0],
1710 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001711 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1712 // replacement failed.
1713 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
1714 "rewriter could not replace sub-expression due to macros");
1715 SourceRange Range = Exp->getSourceRange();
1716 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
1717 delete ProtoExp;
1718 return Exp;
1719 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001720 delete Exp;
1721 return ProtoExp;
1722
1723}
1724
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001725/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1726/// an objective-c class with ivars.
1727void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1728 std::string &Result) {
1729 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1730 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001731 // Do not synthesize more than once.
1732 if (ObjcSynthesizedStructs.count(CDecl))
1733 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001734 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001735 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001736 SourceLocation LocStart = CDecl->getLocStart();
1737 SourceLocation LocEnd = CDecl->getLocEnd();
1738
1739 const char *startBuf = SM->getCharacterData(LocStart);
1740 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001741 // If no ivars and no root or if its root, directly or indirectly,
1742 // have no ivars (thus not synthesized) then no need to synthesize this class.
1743 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001744 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1745 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1746 Result.c_str(), Result.size());
1747 return;
1748 }
1749
1750 // FIXME: This has potential of causing problem. If
1751 // SynthesizeObjcInternalStruct is ever called recursively.
1752 Result += "\nstruct ";
1753 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001754
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001755 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001756 const char *cursor = strchr(startBuf, '{');
1757 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001758 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001759
1760 // rewrite the original header *without* disturbing the '{'
1761 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1762 Result.c_str(), Result.size());
1763 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1764 Result = "\n struct ";
1765 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001766 // Note: We don't name the field decl. This simplifies the "codegen" for
1767 // accessing a superclasses instance variables (and is similar to what gcc
1768 // does internally). The unnamed struct field feature is enabled with
1769 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1770 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001771 Result += ";\n";
1772
1773 // insert the super class structure definition.
1774 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1775 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1776 }
1777 cursor++; // past '{'
1778
1779 // Now comment out any visibility specifiers.
1780 while (cursor < endBuf) {
1781 if (*cursor == '@') {
1782 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001783 // Skip whitespace.
1784 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1785 /*scan*/;
1786
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001787 // FIXME: presence of @public, etc. inside comment results in
1788 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001789 if (!strncmp(cursor, "public", strlen("public")) ||
1790 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001791 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001792 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001793 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001794 // FIXME: If there are cases where '<' is used in ivar declaration part
1795 // of user code, then scan the ivar list and use needToScanForQualifiers
1796 // for type checking.
1797 else if (*cursor == '<') {
1798 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1799 Rewrite.InsertText(atLoc, "/* ", 3);
1800 cursor = strchr(cursor, '>');
1801 cursor++;
1802 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1803 Rewrite.InsertText(atLoc, " */", 3);
1804 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001805 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001806 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001807 // Don't forget to add a ';'!!
1808 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1809 } else { // we don't have any instance variables - insert super struct.
1810 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1811 Result += " {\n struct ";
1812 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001813 // Note: We don't name the field decl. This simplifies the "codegen" for
1814 // accessing a superclasses instance variables (and is similar to what gcc
1815 // does internally). The unnamed struct field feature is enabled with
1816 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1817 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001818 Result += ";\n};\n";
1819 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1820 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001821 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001822 // Mark this struct as having been generated.
1823 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001824 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001825}
1826
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001827// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1828/// class methods.
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001829void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1830 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001831 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001832 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001833 const char *ClassName,
1834 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001835 if (MethodBegin == MethodEnd) return;
1836
Fariborz Jahanian04455192007-10-22 21:41:37 +00001837 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001838 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001839 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001840 SEL _cmd;
1841 char *method_types;
1842 void *_imp;
1843 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001844 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001845 Result += "\nstruct _objc_method {\n";
1846 Result += "\tSEL _cmd;\n";
1847 Result += "\tchar *method_types;\n";
1848 Result += "\tvoid *_imp;\n";
1849 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001850
1851 /* struct _objc_method_list {
1852 struct _objc_method_list *next_method;
1853 int method_count;
1854 struct _objc_method method_list[];
1855 }
1856 */
1857 Result += "\nstruct _objc_method_list {\n";
1858 Result += "\tstruct _objc_method_list *next_method;\n";
1859 Result += "\tint method_count;\n";
1860 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001861 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001862 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001863
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001864 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001865 Result += "\nstatic struct _objc_method_list _OBJC_";
1866 Result += prefix;
1867 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1868 Result += "_METHODS_";
1869 Result += ClassName;
1870 Result += " __attribute__ ((section (\"__OBJC, __";
1871 Result += IsInstanceMethod ? "inst" : "cls";
1872 Result += "_meth\")))= ";
1873 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001874
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001875 Result += "\t,{{(SEL)\"";
1876 Result += (*MethodBegin)->getSelector().getName().c_str();
1877 std::string MethodTypeString;
1878 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1879 Result += "\", \"";
1880 Result += MethodTypeString;
1881 Result += "\", ";
1882 Result += MethodInternalNames[*MethodBegin];
1883 Result += "}\n";
1884 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1885 Result += "\t ,{(SEL)\"";
1886 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001887 std::string MethodTypeString;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001888 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001889 Result += "\", \"";
1890 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001891 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001892 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001893 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001894 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001895 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001896}
1897
1898/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1899void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1900 int NumProtocols,
1901 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001902 const char *ClassName,
1903 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001904 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001905 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001906 for (int i = 0; i < NumProtocols; i++) {
1907 ObjcProtocolDecl *PDecl = Protocols[i];
1908 // Output struct protocol_methods holder of method selector and type.
1909 if (!objc_protocol_methods &&
1910 (PDecl->getNumInstanceMethods() > 0
1911 || PDecl->getNumClassMethods() > 0)) {
1912 /* struct protocol_methods {
1913 SEL _cmd;
1914 char *method_types;
1915 }
1916 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001917 Result += "\nstruct protocol_methods {\n";
1918 Result += "\tSEL _cmd;\n";
1919 Result += "\tchar *method_types;\n";
1920 Result += "};\n";
1921
1922 /* struct _objc_protocol_method_list {
1923 int protocol_method_count;
1924 struct protocol_methods protocols[];
1925 }
1926 */
1927 Result += "\nstruct _objc_protocol_method_list {\n";
1928 Result += "\tint protocol_method_count;\n";
1929 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001930 objc_protocol_methods = true;
1931 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001932
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001933 int NumMethods = PDecl->getNumInstanceMethods();
1934 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001935 Result += "\nstatic struct _objc_protocol_method_list "
1936 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1937 Result += PDecl->getName();
1938 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1939 "{\n\t" + utostr(NumMethods) + "\n";
1940
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001941 // Output instance methods declared in this protocol.
1942 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1943 E = PDecl->instmeth_end(); I != E; ++I) {
1944 if (I == PDecl->instmeth_begin())
1945 Result += "\t ,{{(SEL)\"";
1946 else
1947 Result += "\t ,{(SEL)\"";
1948 Result += (*I)->getSelector().getName().c_str();
1949 std::string MethodTypeString;
1950 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
1951 Result += "\", \"";
1952 Result += MethodTypeString;
1953 Result += "\"}\n";
1954 }
1955 Result += "\t }\n};\n";
1956 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001957
1958 // Output class methods declared in this protocol.
1959 NumMethods = PDecl->getNumClassMethods();
1960 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001961 Result += "\nstatic struct _objc_protocol_method_list "
1962 "_OBJC_PROTOCOL_CLASS_METHODS_";
1963 Result += PDecl->getName();
1964 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1965 "{\n\t";
1966 Result += utostr(NumMethods);
1967 Result += "\n";
1968
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00001969 // Output instance methods declared in this protocol.
1970 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
1971 E = PDecl->classmeth_end(); I != E; ++I) {
1972 if (I == PDecl->classmeth_begin())
1973 Result += "\t ,{{(SEL)\"";
1974 else
1975 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00001976 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001977 std::string MethodTypeString;
Steve Naroff2ce399a2007-12-14 23:37:57 +00001978 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001979 Result += "\", \"";
1980 Result += MethodTypeString;
1981 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001982 }
1983 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001984 }
1985 // Output:
1986 /* struct _objc_protocol {
1987 // Objective-C 1.0 extensions
1988 struct _objc_protocol_extension *isa;
1989 char *protocol_name;
1990 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001991 struct _objc_protocol_method_list *instance_methods;
1992 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001993 };
1994 */
1995 static bool objc_protocol = false;
1996 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001997 Result += "\nstruct _objc_protocol {\n";
1998 Result += "\tstruct _objc_protocol_extension *isa;\n";
1999 Result += "\tchar *protocol_name;\n";
2000 Result += "\tstruct _objc_protocol **protocol_list;\n";
2001 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2002 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2003 Result += "};\n";
2004
2005 /* struct _objc_protocol_list {
2006 struct _objc_protocol_list *next;
2007 int protocol_count;
2008 struct _objc_protocol *class_protocols[];
2009 }
2010 */
2011 Result += "\nstruct _objc_protocol_list {\n";
2012 Result += "\tstruct _objc_protocol_list *next;\n";
2013 Result += "\tint protocol_count;\n";
2014 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2015 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002016 objc_protocol = true;
2017 }
2018
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002019 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2020 Result += PDecl->getName();
2021 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2022 "{\n\t0, \"";
2023 Result += PDecl->getName();
2024 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002025 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002026 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2027 Result += PDecl->getName();
2028 Result += ", ";
2029 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002030 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002031 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002032 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002033 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2034 Result += PDecl->getName();
2035 Result += "\n";
2036 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002037 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002038 Result += "0\n";
2039 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002040 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002041 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002042 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2043 Result += prefix;
2044 Result += "_PROTOCOLS_";
2045 Result += ClassName;
2046 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2047 "{\n\t0, ";
2048 Result += utostr(NumProtocols);
2049 Result += "\n";
2050
2051 Result += "\t,{&_OBJC_PROTOCOL_";
2052 Result += Protocols[0]->getName();
2053 Result += " \n";
2054
2055 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002056 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002057 Result += "\t ,&_OBJC_PROTOCOL_";
2058 Result += PDecl->getName();
2059 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002060 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002061 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002062 }
2063}
2064
2065/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
2066/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002067void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
2068 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002069 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
2070 // Find category declaration for this implementation.
2071 ObjcCategoryDecl *CDecl;
2072 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2073 CDecl = CDecl->getNextClassCategory())
2074 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2075 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002076
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002077 char *FullCategoryName = (char*)alloca(
2078 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
2079 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
2080
2081 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002082 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2083 true, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002084
2085 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002086 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2087 false, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002088
2089 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002090 // Null CDecl is case of a category implementation with no category interface
2091 if (CDecl)
2092 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2093 CDecl->getNumReferencedProtocols(),
2094 "CATEGORY",
2095 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002096
2097 /* struct _objc_category {
2098 char *category_name;
2099 char *class_name;
2100 struct _objc_method_list *instance_methods;
2101 struct _objc_method_list *class_methods;
2102 struct _objc_protocol_list *protocols;
2103 // Objective-C 1.0 extensions
2104 uint32_t size; // sizeof (struct _objc_category)
2105 struct _objc_property_list *instance_properties; // category's own
2106 // @property decl.
2107 };
2108 */
2109
2110 static bool objc_category = false;
2111 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002112 Result += "\nstruct _objc_category {\n";
2113 Result += "\tchar *category_name;\n";
2114 Result += "\tchar *class_name;\n";
2115 Result += "\tstruct _objc_method_list *instance_methods;\n";
2116 Result += "\tstruct _objc_method_list *class_methods;\n";
2117 Result += "\tstruct _objc_protocol_list *protocols;\n";
2118 Result += "\tunsigned int size;\n";
2119 Result += "\tstruct _objc_property_list *instance_properties;\n";
2120 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002121 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002122 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002123 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2124 Result += FullCategoryName;
2125 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2126 Result += IDecl->getName();
2127 Result += "\"\n\t, \"";
2128 Result += ClassDecl->getName();
2129 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002130
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002131 if (IDecl->getNumInstanceMethods() > 0) {
2132 Result += "\t, (struct _objc_method_list *)"
2133 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2134 Result += FullCategoryName;
2135 Result += "\n";
2136 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002137 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002138 Result += "\t, 0\n";
2139 if (IDecl->getNumClassMethods() > 0) {
2140 Result += "\t, (struct _objc_method_list *)"
2141 "&_OBJC_CATEGORY_CLASS_METHODS_";
2142 Result += FullCategoryName;
2143 Result += "\n";
2144 }
2145 else
2146 Result += "\t, 0\n";
2147
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002148 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002149 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2150 Result += FullCategoryName;
2151 Result += "\n";
2152 }
2153 else
2154 Result += "\t, 0\n";
2155 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002156}
2157
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002158/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2159/// ivar offset.
2160void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2161 ObjcIvarDecl *ivar,
2162 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002163 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002164 Result += IDecl->getName();
2165 Result += ", ";
2166 Result += ivar->getName();
2167 Result += ")";
2168}
2169
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002170//===----------------------------------------------------------------------===//
2171// Meta Data Emission
2172//===----------------------------------------------------------------------===//
2173
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002174void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2175 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002176 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2177
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002178 // Explictly declared @interface's are already synthesized.
2179 if (CDecl->ImplicitInterfaceDecl()) {
2180 // FIXME: Implementation of a class with no @interface (legacy) doese not
2181 // produce correct synthesis as yet.
2182 SynthesizeObjcInternalStruct(CDecl, Result);
2183 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002184
Chris Lattnerc7b06752007-12-12 07:56:42 +00002185 // Build _objc_ivar_list metadata for classes ivars if needed
2186 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2187 ? IDecl->getImplDeclNumIvars()
2188 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002189 if (NumIvars > 0) {
2190 static bool objc_ivar = false;
2191 if (!objc_ivar) {
2192 /* struct _objc_ivar {
2193 char *ivar_name;
2194 char *ivar_type;
2195 int ivar_offset;
2196 };
2197 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002198 Result += "\nstruct _objc_ivar {\n";
2199 Result += "\tchar *ivar_name;\n";
2200 Result += "\tchar *ivar_type;\n";
2201 Result += "\tint ivar_offset;\n";
2202 Result += "};\n";
2203
2204 /* struct _objc_ivar_list {
2205 int ivar_count;
2206 struct _objc_ivar ivar_list[];
2207 };
2208 */
2209 Result += "\nstruct _objc_ivar_list {\n";
2210 Result += "\tint ivar_count;\n";
2211 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002212 objc_ivar = true;
2213 }
2214
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002215 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2216 Result += IDecl->getName();
2217 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2218 "{\n\t";
2219 Result += utostr(NumIvars);
2220 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002221
2222 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2223 if (IDecl->getImplDeclNumIvars() > 0) {
2224 IVI = IDecl->ivar_begin();
2225 IVE = IDecl->ivar_end();
2226 } else {
2227 IVI = CDecl->ivar_begin();
2228 IVE = CDecl->ivar_end();
2229 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002230 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002231 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002232 Result += "\", \"";
2233 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002234 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002235 Result += StrEncoding;
2236 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002237 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002238 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002239 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002240 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002241 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002242 Result += "\", \"";
2243 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002244 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002245 Result += StrEncoding;
2246 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002247 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002248 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002249 }
2250
2251 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002252 }
2253
2254 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002255 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2256 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002257
2258 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002259 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2260 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002261
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002262 // Protocols referenced in class declaration?
2263 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2264 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002265 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002266
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002267
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002268 // Declaration of class/meta-class metadata
2269 /* struct _objc_class {
2270 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002271 const char *super_class_name;
2272 char *name;
2273 long version;
2274 long info;
2275 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002276 struct _objc_ivar_list *ivars;
2277 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002278 struct objc_cache *cache;
2279 struct objc_protocol_list *protocols;
2280 const char *ivar_layout;
2281 struct _objc_class_ext *ext;
2282 };
2283 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002284 static bool objc_class = false;
2285 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002286 Result += "\nstruct _objc_class {\n";
2287 Result += "\tstruct _objc_class *isa;\n";
2288 Result += "\tconst char *super_class_name;\n";
2289 Result += "\tchar *name;\n";
2290 Result += "\tlong version;\n";
2291 Result += "\tlong info;\n";
2292 Result += "\tlong instance_size;\n";
2293 Result += "\tstruct _objc_ivar_list *ivars;\n";
2294 Result += "\tstruct _objc_method_list *methods;\n";
2295 Result += "\tstruct objc_cache *cache;\n";
2296 Result += "\tstruct _objc_protocol_list *protocols;\n";
2297 Result += "\tconst char *ivar_layout;\n";
2298 Result += "\tstruct _objc_class_ext *ext;\n";
2299 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002300 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002301 }
2302
2303 // Meta-class metadata generation.
2304 ObjcInterfaceDecl *RootClass = 0;
2305 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2306 while (SuperClass) {
2307 RootClass = SuperClass;
2308 SuperClass = SuperClass->getSuperClass();
2309 }
2310 SuperClass = CDecl->getSuperClass();
2311
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002312 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2313 Result += CDecl->getName();
2314 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2315 "{\n\t(struct _objc_class *)\"";
2316 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2317 Result += "\"";
2318
2319 if (SuperClass) {
2320 Result += ", \"";
2321 Result += SuperClass->getName();
2322 Result += "\", \"";
2323 Result += CDecl->getName();
2324 Result += "\"";
2325 }
2326 else {
2327 Result += ", 0, \"";
2328 Result += CDecl->getName();
2329 Result += "\"";
2330 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002331 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002332 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002333 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002334 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002335 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002336 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002337 Result += "\n";
2338 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002339 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002340 Result += ", 0\n";
2341 if (CDecl->getNumIntfRefProtocols() > 0) {
2342 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2343 Result += CDecl->getName();
2344 Result += ",0,0\n";
2345 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002346 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002347 Result += "\t,0,0,0,0\n";
2348 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002349
2350 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002351 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2352 Result += CDecl->getName();
2353 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2354 "{\n\t&_OBJC_METACLASS_";
2355 Result += CDecl->getName();
2356 if (SuperClass) {
2357 Result += ", \"";
2358 Result += SuperClass->getName();
2359 Result += "\", \"";
2360 Result += CDecl->getName();
2361 Result += "\"";
2362 }
2363 else {
2364 Result += ", 0, \"";
2365 Result += CDecl->getName();
2366 Result += "\"";
2367 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002368 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002369 Result += ", 0,1";
2370 if (!ObjcSynthesizedStructs.count(CDecl))
2371 Result += ",0";
2372 else {
2373 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002374 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002375 Result += CDecl->getName();
2376 Result += ")";
2377 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002378 if (NumIvars > 0) {
2379 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2380 Result += CDecl->getName();
2381 Result += "\n\t";
2382 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002383 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002384 Result += ",0";
2385 if (IDecl->getNumInstanceMethods() > 0) {
2386 Result += ", &_OBJC_INSTANCE_METHODS_";
2387 Result += CDecl->getName();
2388 Result += ", 0\n\t";
2389 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002390 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002391 Result += ",0,0";
2392 if (CDecl->getNumIntfRefProtocols() > 0) {
2393 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2394 Result += CDecl->getName();
2395 Result += ", 0,0\n";
2396 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002397 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002398 Result += ",0,0,0\n";
2399 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002400}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002401
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002402/// RewriteImplementations - This routine rewrites all method implementations
2403/// and emits meta-data.
2404
2405void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002406 int ClsDefCount = ClassImplementation.size();
2407 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002408
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002409 if (ClsDefCount == 0 && CatDefCount == 0)
2410 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002411 // Rewrite implemented methods
2412 for (int i = 0; i < ClsDefCount; i++)
2413 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002414
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002415 for (int i = 0; i < CatDefCount; i++)
2416 RewriteImplementationDecl(CategoryImplementation[i]);
2417
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002418 // This is needed for use of offsetof
2419 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002420
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002421 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002422 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002423 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002424
2425 // For each implemented category, write out all its meta data.
2426 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002427 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002428
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002429 // Write objc_symtab metadata
2430 /*
2431 struct _objc_symtab
2432 {
2433 long sel_ref_cnt;
2434 SEL *refs;
2435 short cls_def_cnt;
2436 short cat_def_cnt;
2437 void *defs[cls_def_cnt + cat_def_cnt];
2438 };
2439 */
2440
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002441 Result += "\nstruct _objc_symtab {\n";
2442 Result += "\tlong sel_ref_cnt;\n";
2443 Result += "\tSEL *refs;\n";
2444 Result += "\tshort cls_def_cnt;\n";
2445 Result += "\tshort cat_def_cnt;\n";
2446 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2447 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002448
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002449 Result += "static struct _objc_symtab "
2450 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2451 Result += "\t0, 0, " + utostr(ClsDefCount)
2452 + ", " + utostr(CatDefCount) + "\n";
2453 for (int i = 0; i < ClsDefCount; i++) {
2454 Result += "\t,&_OBJC_CLASS_";
2455 Result += ClassImplementation[i]->getName();
2456 Result += "\n";
2457 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002458
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002459 for (int i = 0; i < CatDefCount; i++) {
2460 Result += "\t,&_OBJC_CATEGORY_";
2461 Result += CategoryImplementation[i]->getClassInterface()->getName();
2462 Result += "_";
2463 Result += CategoryImplementation[i]->getName();
2464 Result += "\n";
2465 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002466
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002467 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002468
2469 // Write objc_module metadata
2470
2471 /*
2472 struct _objc_module {
2473 long version;
2474 long size;
2475 const char *name;
2476 struct _objc_symtab *symtab;
2477 }
2478 */
2479
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002480 Result += "\nstruct _objc_module {\n";
2481 Result += "\tlong version;\n";
2482 Result += "\tlong size;\n";
2483 Result += "\tconst char *name;\n";
2484 Result += "\tstruct _objc_symtab *symtab;\n";
2485 Result += "};\n\n";
2486 Result += "static struct _objc_module "
2487 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002488 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2489 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002490 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002491
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002492}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002493