blob: bb8f772e706696b0f145e7db0e9f92ea75628269 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000054
Steve Naroff0add5d22007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000058
Steve Naroff764c1ae2007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattnerae43eb72007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenekb3ee1932007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000125
Steve Naroff0744c472007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000128 }
Chris Lattner569faa62007-10-11 18:38:32 +0000129
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +0000147 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000154
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000179
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000183
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000186
Steve Naroffb82c50f2007-11-11 17:19:15 +0000187 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000188 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000189 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000190 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000191 const char *ClassName,
192 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000193
194 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
195 int NumProtocols,
196 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000197 const char *ClassName,
198 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000199 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
200 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000201 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
202 ObjcIvarDecl *ivar,
203 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000204 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000205 };
206}
207
Chris Lattner258f26c2007-11-30 22:25:36 +0000208ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
209 return new RewriteTest(Diags);
210}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000211
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000212//===----------------------------------------------------------------------===//
213// Top Level Driver Code
214//===----------------------------------------------------------------------===//
215
Chris Lattner569faa62007-10-11 18:38:32 +0000216void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000217 // Two cases: either the decl could be in the main file, or it could be in a
218 // #included file. If the former, rewrite it now. If the later, check to see
219 // if we rewrote the #include/#import.
220 SourceLocation Loc = D->getLocation();
221 Loc = SM->getLogicalLoc(Loc);
222
223 // If this is for a builtin, ignore it.
224 if (Loc.isInvalid()) return;
225
Steve Naroffe9780582007-10-23 23:50:29 +0000226 // Look for built-in declarations that we need to refer during the rewrite.
227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000228 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000229 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
230 // declared in <Foundation/NSString.h>
231 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
232 ConstantStringClassReference = FVD;
233 return;
234 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000235 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
236 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000237 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
238 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000239 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
240 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000241 } else if (ObjcForwardProtocolDecl *FP =
242 dyn_cast<ObjcForwardProtocolDecl>(D)){
243 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000244 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000245 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000246 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
247 return HandleDeclInMainFile(D);
248
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000249 // Otherwise, see if there is a #import in the main file that should be
250 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000251 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000252}
253
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000254/// HandleDeclInMainFile - This is called for each top-level decl defined in the
255/// main file of the input.
256void RewriteTest::HandleDeclInMainFile(Decl *D) {
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
258 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000259 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000260
261 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000262 if (Stmt *Body = MD->getBody()) {
263 //Body->dump();
264 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000265 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000266 CurMethodDecl = 0;
267 }
Steve Naroff18c83382007-11-13 23:01:27 +0000268 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000269 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
270 ClassImplementation.push_back(CI);
271 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
272 CategoryImplementation.push_back(CI);
273 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
274 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000275 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000276 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000277 if (VD->getInit())
278 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
279 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000280 // Nothing yet.
281}
282
283RewriteTest::~RewriteTest() {
284 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000285
286 // Rewrite tabs if we care.
287 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000288
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000289 // Rewrite Objective-c meta data*
290 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000291 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000292
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000293 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
294 // we are done.
295 if (const RewriteBuffer *RewriteBuf =
296 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000297 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000298 std::string S(RewriteBuf->begin(), RewriteBuf->end());
299 printf("%s\n", S.c_str());
300 } else {
301 printf("No changes\n");
302 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000303 // Emit metadata.
304 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000305}
306
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000307//===----------------------------------------------------------------------===//
308// Syntactic (non-AST) Rewriting Code
309//===----------------------------------------------------------------------===//
310
Chris Lattner74db1682007-10-16 21:07:07 +0000311void RewriteTest::RewriteInclude(SourceLocation Loc) {
312 // Rip up the #include stack to the main file.
313 SourceLocation IncLoc = Loc, NextLoc = Loc;
314 do {
315 IncLoc = Loc;
316 Loc = SM->getLogicalLoc(NextLoc);
317 NextLoc = SM->getIncludeLoc(Loc);
318 } while (!NextLoc.isInvalid());
319
320 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
321 // IncLoc indicates the header that was included if it is useful.
322 IncLoc = SM->getLogicalLoc(IncLoc);
323 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
324 Loc == LastIncLoc)
325 return;
326 LastIncLoc = Loc;
327
328 unsigned IncCol = SM->getColumnNumber(Loc);
329 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
330
331 // Replace the #import with #include.
332 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
333}
334
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000335void RewriteTest::RewriteTabs() {
336 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
337 const char *MainBufStart = MainBuf.first;
338 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000339
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000340 // Loop over the whole file, looking for tabs.
341 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
342 if (*BufPtr != '\t')
343 continue;
344
345 // Okay, we found a tab. This tab will turn into at least one character,
346 // but it depends on which 'virtual column' it is in. Compute that now.
347 unsigned VCol = 0;
348 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
349 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
350 ++VCol;
351
352 // Okay, now that we know the virtual column, we know how many spaces to
353 // insert. We assume 8-character tab-stops.
354 unsigned Spaces = 8-(VCol & 7);
355
356 // Get the location of the tab.
357 SourceLocation TabLoc =
358 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
359
360 // Rewrite the single tab character into a sequence of spaces.
361 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
362 }
Chris Lattner569faa62007-10-11 18:38:32 +0000363}
364
365
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000366void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
367 int numDecls = ClassDecl->getNumForwardDecls();
368 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
369
370 // Get the start location and compute the semi location.
371 SourceLocation startLoc = ClassDecl->getLocation();
372 const char *startBuf = SM->getCharacterData(startLoc);
373 const char *semiPtr = strchr(startBuf, ';');
374
375 // Translate to typedef's that forward reference structs with the same name
376 // as the class. As a convenience, we include the original declaration
377 // as a comment.
378 std::string typedefString;
379 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000380 typedefString.append(startBuf, semiPtr-startBuf+1);
381 typedefString += "\n";
382 for (int i = 0; i < numDecls; i++) {
383 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000384 typedefString += "#ifndef _REWRITER_typedef_";
385 typedefString += ForwardDecl->getName();
386 typedefString += "\n";
387 typedefString += "#define _REWRITER_typedef_";
388 typedefString += ForwardDecl->getName();
389 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000390 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000391 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000392 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000393 }
394
395 // Replace the @class with typedefs corresponding to the classes.
396 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
397 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000398}
399
Steve Naroff18c83382007-11-13 23:01:27 +0000400void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000401 for (int i = 0; i < nMethods; i++) {
402 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000405
Steve Narofffbfb46d2007-11-14 14:34:23 +0000406 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
407 Rewrite.InsertText(LocStart, "/* ", 3);
408 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
409 } else {
410 Rewrite.InsertText(LocStart, "// ", 3);
411 }
Steve Naroff667f1682007-10-30 13:30:57 +0000412 }
413}
414
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000415void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
416{
417 for (int i = 0; i < nProperties; i++) {
418 ObjcPropertyDecl *Property = Properties[i];
419 SourceLocation Loc = Property->getLocation();
420
421 Rewrite.ReplaceText(Loc, 0, "// ", 3);
422
423 // FIXME: handle properties that are declared across multiple lines.
424 }
425}
426
Steve Naroff667f1682007-10-30 13:30:57 +0000427void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
428 SourceLocation LocStart = CatDecl->getLocStart();
429
430 // FIXME: handle category headers that are declared across multiple lines.
431 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
432
Steve Naroff18c83382007-11-13 23:01:27 +0000433 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
434 CatDecl->getInstanceMethods());
435 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
436 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000437 // Lastly, comment out the @end.
438 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
439}
440
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000441void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000442 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000443
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000444 SourceLocation LocStart = PDecl->getLocStart();
445
446 // FIXME: handle protocol headers that are declared across multiple lines.
447 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
448
Steve Naroff18c83382007-11-13 23:01:27 +0000449 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
450 PDecl->getInstanceMethods());
451 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
452 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000453 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000454 SourceLocation LocEnd = PDecl->getAtEndLoc();
455 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000456
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000457 // Must comment out @optional/@required
458 const char *startBuf = SM->getCharacterData(LocStart);
459 const char *endBuf = SM->getCharacterData(LocEnd);
460 for (const char *p = startBuf; p < endBuf; p++) {
461 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
462 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000463 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000464 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
465 CommentedOptional.c_str(), CommentedOptional.size());
466
467 }
468 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
469 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000470 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000471 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
472 CommentedRequired.c_str(), CommentedRequired.size());
473
474 }
475 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000476}
477
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000478void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
479 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000480 if (LocStart.isInvalid())
481 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000482 // FIXME: handle forward protocol that are declared across multiple lines.
483 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
484}
485
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000486void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
487 std::string &ResultStr) {
488 ResultStr += "\nstatic ";
489 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000490 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000491
492 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000493 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000494
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000495 if (OMD->isInstance())
496 NameStr += "_I_";
497 else
498 NameStr += "_C_";
499
500 NameStr += OMD->getClassInterface()->getName();
501 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000502
503 NamedDecl *MethodContext = OMD->getMethodContext();
504 if (ObjcCategoryImplDecl *CID =
505 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000506 NameStr += CID->getName();
507 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000508 }
509 // Append selector names, replacing ':' with '_'
510 const char *selName = OMD->getSelector().getName().c_str();
511 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000512 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000513 else {
514 std::string selString = OMD->getSelector().getName();
515 int len = selString.size();
516 for (int i = 0; i < len; i++)
517 if (selString[i] == ':')
518 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000519 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000520 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000521 // Remember this name for metadata emission
522 MethodInternalNames[OMD] = NameStr;
523 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000524
525 // Rewrite arguments
526 ResultStr += "(";
527
528 // invisible arguments
529 if (OMD->isInstance()) {
530 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
531 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000532 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
533 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000534 ResultStr += selfTy.getAsString();
535 }
536 else
537 ResultStr += Context->getObjcIdType().getAsString();
538
539 ResultStr += " self, ";
540 ResultStr += Context->getObjcSelType().getAsString();
541 ResultStr += " _cmd";
542
543 // Method arguments.
544 for (int i = 0; i < OMD->getNumParams(); i++) {
545 ParmVarDecl *PDecl = OMD->getParamDecl(i);
546 ResultStr += ", ";
547 ResultStr += PDecl->getType().getAsString();
548 ResultStr += " ";
549 ResultStr += PDecl->getName();
550 }
551 ResultStr += ")";
552
553}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000554void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
555 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
556 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000557
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000558 if (IMD)
559 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
560 else
561 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000562
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000563 int numMethods = IMD ? IMD->getNumInstanceMethods()
564 : CID->getNumInstanceMethods();
565
566 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000567 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000568 ObjcMethodDecl *OMD;
569 if (IMD)
570 OMD = IMD->getInstanceMethods()[i];
571 else
572 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000573 RewriteObjcMethodDecl(OMD, ResultStr);
574 SourceLocation LocStart = OMD->getLocStart();
575 SourceLocation LocEnd = OMD->getBody()->getLocStart();
576
577 const char *startBuf = SM->getCharacterData(LocStart);
578 const char *endBuf = SM->getCharacterData(LocEnd);
579 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
580 ResultStr.c_str(), ResultStr.size());
581 }
582
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000583 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
584 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000585 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000586 ObjcMethodDecl *OMD;
587 if (IMD)
588 OMD = IMD->getClassMethods()[i];
589 else
590 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000591 RewriteObjcMethodDecl(OMD, ResultStr);
592 SourceLocation LocStart = OMD->getLocStart();
593 SourceLocation LocEnd = OMD->getBody()->getLocStart();
594
595 const char *startBuf = SM->getCharacterData(LocStart);
596 const char *endBuf = SM->getCharacterData(LocEnd);
597 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
598 ResultStr.c_str(), ResultStr.size());
599 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000600 if (IMD)
601 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
602 else
603 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000604}
605
Steve Naroff3774dd92007-10-26 20:53:56 +0000606void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000607 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000608 if (!ObjcForwardDecls.count(ClassDecl)) {
609 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000610 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000611 ResultStr += ClassDecl->getName();
612 ResultStr += "\n";
613 ResultStr += "#define _REWRITER_typedef_";
614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000616 ResultStr += "typedef struct ";
617 ResultStr += ClassDecl->getName();
618 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000619 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000620 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000621
622 // Mark this typedef as having been generated.
623 ObjcForwardDecls.insert(ClassDecl);
624 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000625 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
626
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000627 RewriteProperties(ClassDecl->getNumPropertyDecl(),
628 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000629 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
630 ClassDecl->getInstanceMethods());
631 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
632 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000633
Steve Naroff1ccf4632007-10-30 03:43:13 +0000634 // Lastly, comment out the @end.
635 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000636}
637
Steve Naroff6b759ce2007-11-15 02:58:25 +0000638Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
639 ObjcIvarDecl *D = IV->getDecl();
640 if (IV->isFreeIvar()) {
641 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
642 IV->getLocation());
643 Rewrite.ReplaceStmt(IV, Replacement);
644 delete IV;
645 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000646 } else {
647 if (CurMethodDecl) {
648 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
649 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
650 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
651 IdentifierInfo *II = intT->getDecl()->getIdentifier();
652 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
653 II, 0);
654 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
655
656 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
657 // Don't forget the parens to enforce the proper binding.
658 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
659 Rewrite.ReplaceStmt(IV->getBase(), PE);
660 delete IV->getBase();
661 return PE;
662 }
663 }
664 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000665 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000666 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000667}
668
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000669//===----------------------------------------------------------------------===//
670// Function Body / Expression rewriting
671//===----------------------------------------------------------------------===//
672
Steve Naroff334fbc22007-11-09 15:20:18 +0000673Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000674 // Otherwise, just rewrite all children.
675 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
676 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000677 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000678 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000679 if (newStmt)
680 *CI = newStmt;
681 }
Steve Naroffe9780582007-10-23 23:50:29 +0000682
683 // Handle specific things.
684 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
685 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000686
687 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
688 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000689
690 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
691 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000692
693 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
694 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000695
Steve Naroff71226032007-10-24 22:48:43 +0000696 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
697 // Before we rewrite it, put the original message expression in a comment.
698 SourceLocation startLoc = MessExpr->getLocStart();
699 SourceLocation endLoc = MessExpr->getLocEnd();
700
701 const char *startBuf = SM->getCharacterData(startLoc);
702 const char *endBuf = SM->getCharacterData(endLoc);
703
704 std::string messString;
705 messString += "// ";
706 messString.append(startBuf, endBuf-startBuf+1);
707 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000708
Steve Naroff71226032007-10-24 22:48:43 +0000709 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
710 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
711 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000712 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000713 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000714 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000715
716 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
717 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000718
719 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
720 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000721
722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
723 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000724#if 0
725 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
726 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
727 // Get the new text.
728 std::ostringstream Buf;
729 Replacement->printPretty(Buf);
730 const std::string &Str = Buf.str();
731
732 printf("CAST = %s\n", &Str[0]);
733 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
734 delete S;
735 return Replacement;
736 }
737#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000738 // Return this stmt unmodified.
739 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000740}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000741
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000742Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000743 // Get the start location and compute the semi location.
744 SourceLocation startLoc = S->getLocStart();
745 const char *startBuf = SM->getCharacterData(startLoc);
746
747 assert((*startBuf == '@') && "bogus @try location");
748
749 std::string buf;
750 // declare a new scope with two variables, _stack and _rethrow.
751 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
752 buf += "int buf[18/*32-bit i386*/];\n";
753 buf += "char *pointers[4];} _stack;\n";
754 buf += "id volatile _rethrow = 0;\n";
755 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000756 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000757
758 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
759
760 startLoc = S->getTryBody()->getLocEnd();
761 startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '}') && "bogus @try block");
764
765 SourceLocation lastCurlyLoc = startLoc;
766
767 startLoc = startLoc.getFileLocWithOffset(1);
768 buf = " /* @catch begin */ else {\n";
769 buf += " id _caught = objc_exception_extract(&_stack);\n";
770 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000771 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000772 buf += " _rethrow = objc_exception_extract(&_stack);\n";
773 buf += " else { /* @catch continue */";
774
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000775 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000776
777 bool sawIdTypedCatch = false;
778 Stmt *lastCatchBody = 0;
779 ObjcAtCatchStmt *catchList = S->getCatchStmts();
780 while (catchList) {
781 Stmt *catchStmt = catchList->getCatchParamStmt();
782
783 if (catchList == S->getCatchStmts())
784 buf = "if ("; // we are generating code for the first catch clause
785 else
786 buf = "else if (";
787 startLoc = catchList->getLocStart();
788 startBuf = SM->getCharacterData(startLoc);
789
790 assert((*startBuf == '@') && "bogus @catch location");
791
792 const char *lParenLoc = strchr(startBuf, '(');
793
794 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
795 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
796 if (t == Context->getObjcIdType()) {
797 buf += "1) { ";
798 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
799 buf.c_str(), buf.size());
800 sawIdTypedCatch = true;
801 } else if (const PointerType *pType = t->getAsPointerType()) {
802 ObjcInterfaceType *cls; // Should be a pointer to a class.
803
804 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
805 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000806 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000807 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000808 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000809 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
810 buf.c_str(), buf.size());
811 }
812 }
813 // Now rewrite the body...
814 lastCatchBody = catchList->getCatchBody();
815 SourceLocation rParenLoc = catchList->getRParenLoc();
816 SourceLocation bodyLoc = lastCatchBody->getLocStart();
817 const char *bodyBuf = SM->getCharacterData(bodyLoc);
818 const char *rParenBuf = SM->getCharacterData(rParenLoc);
819 assert((*rParenBuf == ')') && "bogus @catch paren location");
820 assert((*bodyBuf == '{') && "bogus @catch body location");
821
822 buf = " = _caught;";
823 // Here we replace ") {" with "= _caught;" (which initializes and
824 // declares the @catch parameter).
825 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
826 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000827 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000828 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000829 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000830 catchList = catchList->getNextCatchStmt();
831 }
832 // Complete the catch list...
833 if (lastCatchBody) {
834 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
835 const char *bodyBuf = SM->getCharacterData(bodyLoc);
836 assert((*bodyBuf == '}') && "bogus @catch body location");
837 bodyLoc = bodyLoc.getFileLocWithOffset(1);
838 buf = " } } /* @catch end */\n";
839
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000840 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000841
842 // Set lastCurlyLoc
843 lastCurlyLoc = lastCatchBody->getLocEnd();
844 }
845 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
846 startLoc = finalStmt->getLocStart();
847 startBuf = SM->getCharacterData(startLoc);
848 assert((*startBuf == '@') && "bogus @finally start");
849
850 buf = "/* @finally */";
851 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
852
853 Stmt *body = finalStmt->getFinallyBody();
854 SourceLocation startLoc = body->getLocStart();
855 SourceLocation endLoc = body->getLocEnd();
856 const char *startBuf = SM->getCharacterData(startLoc);
857 const char *endBuf = SM->getCharacterData(endLoc);
858 assert((*startBuf == '{') && "bogus @finally body location");
859 assert((*endBuf == '}') && "bogus @finally body location");
860
861 startLoc = startLoc.getFileLocWithOffset(1);
862 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000863 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000864 endLoc = endLoc.getFileLocWithOffset(-1);
865 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000866 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000867
868 // Set lastCurlyLoc
869 lastCurlyLoc = body->getLocEnd();
870 }
871 // Now emit the final closing curly brace...
872 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
873 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000874 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000875 return 0;
876}
877
878Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
879 return 0;
880}
881
882Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
883 return 0;
884}
885
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000886// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
887// the throw expression is typically a message expression that's already
888// been rewritten! (which implies the SourceLocation's are invalid).
889Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = S->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893
894 assert((*startBuf == '@') && "bogus @throw location");
895
896 std::string buf;
897 /* void objc_exception_throw(id) __attribute__((noreturn)); */
898 buf = "objc_exception_throw(";
899 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
900 const char *semiBuf = strchr(startBuf, ';');
901 assert((*semiBuf == ';') && "@throw: can't find ';'");
902 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
903 buf = ");";
904 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
905 return 0;
906}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000907
Chris Lattner0021f452007-10-24 16:57:36 +0000908Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000909 // Create a new string expression.
910 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000911 std::string StrEncoding;
912 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
913 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
914 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000915 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000916 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
917 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000918 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
919 "rewriter could not replace sub-expression due to macros");
920 SourceRange Range = Exp->getSourceRange();
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000921 Diags.Report(Exp->getAtLoc(), DiagID, Context->getSourceManager(),
922 0, 0, &Range, 1);
Chris Lattner217df512007-12-02 01:09:57 +0000923 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000924 return Exp;
925 }
926
Chris Lattner4478db92007-11-30 22:53:43 +0000927 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000928 delete Exp;
929 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000930}
931
Steve Naroff296b74f2007-11-05 14:50:49 +0000932Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
933 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
934 // Create a call to sel_registerName("selName").
935 llvm::SmallVector<Expr*, 8> SelExprs;
936 QualType argType = Context->getPointerType(Context->CharTy);
937 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
938 Exp->getSelector().getName().size(),
939 false, argType, SourceLocation(),
940 SourceLocation()));
941 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
942 &SelExprs[0], SelExprs.size());
943 Rewrite.ReplaceStmt(Exp, SelExp);
944 delete Exp;
945 return SelExp;
946}
947
Steve Naroff71226032007-10-24 22:48:43 +0000948CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
949 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000950 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000951 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000952
953 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000954 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000955
956 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000957 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000958 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
959
960 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000961
Steve Naroff71226032007-10-24 22:48:43 +0000962 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
963}
964
Steve Naroffc8a92d12007-11-01 13:24:47 +0000965static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
966 const char *&startRef, const char *&endRef) {
967 while (startBuf < endBuf) {
968 if (*startBuf == '<')
969 startRef = startBuf; // mark the start.
970 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000971 if (startRef && *startRef == '<') {
972 endRef = startBuf; // mark the end.
973 return true;
974 }
975 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000976 }
977 startBuf++;
978 }
979 return false;
980}
981
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000982static void scanToNextArgument(const char *&argRef) {
983 int angle = 0;
984 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
985 if (*argRef == '<')
986 angle++;
987 else if (*argRef == '>')
988 angle--;
989 argRef++;
990 }
991 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
992}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +0000993
Steve Naroffc8a92d12007-11-01 13:24:47 +0000994bool RewriteTest::needToScanForQualifiers(QualType T) {
995 // FIXME: we don't currently represent "id <Protocol>" in the type system.
996 if (T == Context->getObjcIdType())
997 return true;
998
999 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001000 Type *pointeeType = pType->getPointeeType().getTypePtr();
1001 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1002 return true; // we have "Class <Protocol> *".
1003 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001004 return false;
1005}
1006
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001007void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001008 SourceLocation Loc;
1009 QualType Type;
1010 const FunctionTypeProto *proto = 0;
1011 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1012 Loc = VD->getLocation();
1013 Type = VD->getType();
1014 }
1015 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1016 Loc = FD->getLocation();
1017 // Check for ObjC 'id' and class types that have been adorned with protocol
1018 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1019 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1020 assert(funcType && "missing function type");
1021 proto = dyn_cast<FunctionTypeProto>(funcType);
1022 if (!proto)
1023 return;
1024 Type = proto->getResultType();
1025 }
1026 else
1027 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001028
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001029 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001030 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001031
1032 const char *endBuf = SM->getCharacterData(Loc);
1033 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001034 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001035 startBuf--; // scan backward (from the decl location) for return type.
1036 const char *startRef = 0, *endRef = 0;
1037 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1038 // Get the locations of the startRef, endRef.
1039 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1040 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1041 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001042 Rewrite.InsertText(LessLoc, "/*", 2);
1043 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001044 }
1045 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001046 if (!proto)
1047 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001048 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001049 const char *startBuf = SM->getCharacterData(Loc);
1050 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001051 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1052 if (needToScanForQualifiers(proto->getArgType(i))) {
1053 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001054
Steve Naroffc8a92d12007-11-01 13:24:47 +00001055 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001056 // scan forward (from the decl location) for argument types.
1057 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001058 const char *startRef = 0, *endRef = 0;
1059 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1060 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001061 SourceLocation LessLoc =
1062 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1063 SourceLocation GreaterLoc =
1064 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001065 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001066 Rewrite.InsertText(LessLoc, "/*", 2);
1067 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001068 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001069 startBuf = ++endBuf;
1070 }
1071 else {
1072 while (*startBuf != ')' && *startBuf != ',')
1073 startBuf++; // scan forward (from the decl location) for argument types.
1074 startBuf++;
1075 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001076 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001077}
1078
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001079// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1080void RewriteTest::SynthSelGetUidFunctionDecl() {
1081 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1082 llvm::SmallVector<QualType, 16> ArgTys;
1083 ArgTys.push_back(Context->getPointerType(
1084 Context->CharTy.getQualifiedType(QualType::Const)));
1085 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1086 &ArgTys[0], ArgTys.size(),
1087 false /*isVariadic*/);
1088 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1089 SelGetUidIdent, getFuncType,
1090 FunctionDecl::Extern, false, 0);
1091}
1092
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001093// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1094void RewriteTest::SynthGetProtocolFunctionDecl() {
1095 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1096 llvm::SmallVector<QualType, 16> ArgTys;
1097 ArgTys.push_back(Context->getPointerType(
1098 Context->CharTy.getQualifiedType(QualType::Const)));
1099 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1100 &ArgTys[0], ArgTys.size(),
1101 false /*isVariadic*/);
1102 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1103 SelGetProtoIdent, getFuncType,
1104 FunctionDecl::Extern, false, 0);
1105}
1106
Steve Naroff02a82aa2007-10-30 23:14:51 +00001107void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1108 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001109 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001110 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001111 return;
1112 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001113 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001114}
1115
1116// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1117void RewriteTest::SynthMsgSendFunctionDecl() {
1118 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1119 llvm::SmallVector<QualType, 16> ArgTys;
1120 QualType argT = Context->getObjcIdType();
1121 assert(!argT.isNull() && "Can't find 'id' type");
1122 ArgTys.push_back(argT);
1123 argT = Context->getObjcSelType();
1124 assert(!argT.isNull() && "Can't find 'SEL' type");
1125 ArgTys.push_back(argT);
1126 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1127 &ArgTys[0], ArgTys.size(),
1128 true /*isVariadic*/);
1129 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1130 msgSendIdent, msgSendType,
1131 FunctionDecl::Extern, false, 0);
1132}
1133
Steve Naroff764c1ae2007-11-15 10:28:18 +00001134// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1135void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1136 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1137 llvm::SmallVector<QualType, 16> ArgTys;
1138 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1139 &Context->Idents.get("objc_super"), 0);
1140 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1141 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1142 ArgTys.push_back(argT);
1143 argT = Context->getObjcSelType();
1144 assert(!argT.isNull() && "Can't find 'SEL' type");
1145 ArgTys.push_back(argT);
1146 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1147 &ArgTys[0], ArgTys.size(),
1148 true /*isVariadic*/);
1149 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1150 msgSendIdent, msgSendType,
1151 FunctionDecl::Extern, false, 0);
1152}
1153
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001154// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1155void RewriteTest::SynthMsgSendStretFunctionDecl() {
1156 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1157 llvm::SmallVector<QualType, 16> ArgTys;
1158 QualType argT = Context->getObjcIdType();
1159 assert(!argT.isNull() && "Can't find 'id' type");
1160 ArgTys.push_back(argT);
1161 argT = Context->getObjcSelType();
1162 assert(!argT.isNull() && "Can't find 'SEL' type");
1163 ArgTys.push_back(argT);
1164 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1165 &ArgTys[0], ArgTys.size(),
1166 true /*isVariadic*/);
1167 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1168 msgSendIdent, msgSendType,
1169 FunctionDecl::Extern, false, 0);
1170}
1171
1172// SynthMsgSendSuperStretFunctionDecl -
1173// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1174void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1175 IdentifierInfo *msgSendIdent =
1176 &Context->Idents.get("objc_msgSendSuper_stret");
1177 llvm::SmallVector<QualType, 16> ArgTys;
1178 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1179 &Context->Idents.get("objc_super"), 0);
1180 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1181 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1182 ArgTys.push_back(argT);
1183 argT = Context->getObjcSelType();
1184 assert(!argT.isNull() && "Can't find 'SEL' type");
1185 ArgTys.push_back(argT);
1186 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1187 &ArgTys[0], ArgTys.size(),
1188 true /*isVariadic*/);
1189 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1190 msgSendIdent, msgSendType,
1191 FunctionDecl::Extern, false, 0);
1192}
1193
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001194// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1195void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1196 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1197 llvm::SmallVector<QualType, 16> ArgTys;
1198 QualType argT = Context->getObjcIdType();
1199 assert(!argT.isNull() && "Can't find 'id' type");
1200 ArgTys.push_back(argT);
1201 argT = Context->getObjcSelType();
1202 assert(!argT.isNull() && "Can't find 'SEL' type");
1203 ArgTys.push_back(argT);
1204 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1205 &ArgTys[0], ArgTys.size(),
1206 true /*isVariadic*/);
1207 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1208 msgSendIdent, msgSendType,
1209 FunctionDecl::Extern, false, 0);
1210}
1211
Steve Naroff02a82aa2007-10-30 23:14:51 +00001212// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1213void RewriteTest::SynthGetClassFunctionDecl() {
1214 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1215 llvm::SmallVector<QualType, 16> ArgTys;
1216 ArgTys.push_back(Context->getPointerType(
1217 Context->CharTy.getQualifiedType(QualType::Const)));
1218 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1219 &ArgTys[0], ArgTys.size(),
1220 false /*isVariadic*/);
1221 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1222 getClassIdent, getClassType,
1223 FunctionDecl::Extern, false, 0);
1224}
1225
Steve Naroff3b1caac2007-12-07 03:50:46 +00001226// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1227void RewriteTest::SynthGetMetaClassFunctionDecl() {
1228 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1229 llvm::SmallVector<QualType, 16> ArgTys;
1230 ArgTys.push_back(Context->getPointerType(
1231 Context->CharTy.getQualifiedType(QualType::Const)));
1232 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1233 &ArgTys[0], ArgTys.size(),
1234 false /*isVariadic*/);
1235 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1236 getClassIdent, getClassType,
1237 FunctionDecl::Extern, false, 0);
1238}
1239
Steve Naroffabb96362007-11-08 14:30:50 +00001240// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1241void RewriteTest::SynthCFStringFunctionDecl() {
1242 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1243 llvm::SmallVector<QualType, 16> ArgTys;
1244 ArgTys.push_back(Context->getPointerType(
1245 Context->CharTy.getQualifiedType(QualType::Const)));
1246 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1247 &ArgTys[0], ArgTys.size(),
1248 false /*isVariadic*/);
1249 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1250 getClassIdent, getClassType,
1251 FunctionDecl::Extern, false, 0);
1252}
1253
Steve Naroff0add5d22007-11-03 11:27:19 +00001254Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001255#if 1
1256 // This rewrite is specific to GCC, which has builtin support for CFString.
1257 if (!CFStringFunctionDecl)
1258 SynthCFStringFunctionDecl();
1259 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1260 llvm::SmallVector<Expr*, 8> StrExpr;
1261 StrExpr.push_back(Exp->getString());
1262 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1263 &StrExpr[0], StrExpr.size());
1264 // cast to NSConstantString *
1265 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1266 Rewrite.ReplaceStmt(Exp, cast);
1267 delete Exp;
1268 return cast;
1269#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001270 assert(ConstantStringClassReference && "Can't find constant string reference");
1271 llvm::SmallVector<Expr*, 4> InitExprs;
1272
1273 // Synthesize "(Class)&_NSConstantStringClassReference"
1274 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1275 ConstantStringClassReference->getType(),
1276 SourceLocation());
1277 QualType expType = Context->getPointerType(ClsRef->getType());
1278 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1279 expType, SourceLocation());
1280 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1281 SourceLocation());
1282 InitExprs.push_back(cast); // set the 'isa'.
1283 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1284 unsigned IntSize = static_cast<unsigned>(
1285 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1286 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1287 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1288 Exp->getLocStart());
1289 InitExprs.push_back(len); // set "int numBytes".
1290
1291 // struct NSConstantString
1292 QualType CFConstantStrType = Context->getCFConstantStringType();
1293 // (struct NSConstantString) { <exprs from above> }
1294 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1295 &InitExprs[0], InitExprs.size(),
1296 SourceLocation());
1297 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1298 // struct NSConstantString *
1299 expType = Context->getPointerType(StrRep->getType());
1300 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1301 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001302 // cast to NSConstantString *
1303 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001304 Rewrite.ReplaceStmt(Exp, cast);
1305 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001306 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001307#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001308}
1309
Steve Naroff764c1ae2007-11-15 10:28:18 +00001310ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001311 // check if we are sending a message to 'super'
1312 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001313 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1314 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1315 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1316 if (!strcmp(PVD->getName(), "self")) {
1317 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1318 if (ObjcInterfaceType *IT =
1319 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1320 if (IT->getDecl() ==
1321 CurMethodDecl->getClassInterface()->getSuperClass())
1322 return IT->getDecl();
1323 }
1324 }
1325 }
1326 }
1327 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001328 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001329 }
1330 return 0;
1331}
1332
1333// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1334QualType RewriteTest::getSuperStructType() {
1335 if (!SuperStructDecl) {
1336 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1337 &Context->Idents.get("objc_super"), 0);
1338 QualType FieldTypes[2];
1339
1340 // struct objc_object *receiver;
1341 FieldTypes[0] = Context->getObjcIdType();
1342 // struct objc_class *super;
1343 FieldTypes[1] = Context->getObjcClassType();
1344 // Create fields
1345 FieldDecl *FieldDecls[2];
1346
1347 for (unsigned i = 0; i < 2; ++i)
1348 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1349
1350 SuperStructDecl->defineBody(FieldDecls, 4);
1351 }
1352 return Context->getTagDeclType(SuperStructDecl);
1353}
1354
Steve Naroff71226032007-10-24 22:48:43 +00001355Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001356 if (!SelGetUidFunctionDecl)
1357 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001358 if (!MsgSendFunctionDecl)
1359 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001360 if (!MsgSendSuperFunctionDecl)
1361 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001362 if (!MsgSendStretFunctionDecl)
1363 SynthMsgSendStretFunctionDecl();
1364 if (!MsgSendSuperStretFunctionDecl)
1365 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001366 if (!MsgSendFpretFunctionDecl)
1367 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001368 if (!GetClassFunctionDecl)
1369 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001370 if (!GetMetaClassFunctionDecl)
1371 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001372
Steve Naroff764c1ae2007-11-15 10:28:18 +00001373 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001374 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1375 // May need to use objc_msgSend_stret() as well.
1376 FunctionDecl *MsgSendStretFlavor = 0;
1377 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1378 QualType resultType = mDecl->getResultType();
1379 if (resultType.getCanonicalType()->isStructureType()
1380 || resultType.getCanonicalType()->isUnionType())
1381 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001382 else if (resultType.getCanonicalType()->isRealFloatingType())
1383 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001384 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001385
Steve Naroff71226032007-10-24 22:48:43 +00001386 // Synthesize a call to objc_msgSend().
1387 llvm::SmallVector<Expr*, 8> MsgExprs;
1388 IdentifierInfo *clsName = Exp->getClassName();
1389
1390 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1391 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001392 if (!strcmp(clsName->getName(), "super")) {
1393 MsgSendFlavor = MsgSendSuperFunctionDecl;
1394 if (MsgSendStretFlavor)
1395 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1396 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1397
1398 ObjcInterfaceDecl *SuperDecl =
1399 CurMethodDecl->getClassInterface()->getSuperClass();
1400
1401 llvm::SmallVector<Expr*, 4> InitExprs;
1402
1403 // set the receiver to self, the first argument to all methods.
1404 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1405 Context->getObjcIdType(),
1406 SourceLocation()));
1407 llvm::SmallVector<Expr*, 8> ClsExprs;
1408 QualType argType = Context->getPointerType(Context->CharTy);
1409 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1410 SuperDecl->getIdentifier()->getLength(),
1411 false, argType, SourceLocation(),
1412 SourceLocation()));
1413 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1414 &ClsExprs[0],
1415 ClsExprs.size());
1416 // To turn off a warning, type-cast to 'id'
1417 InitExprs.push_back(
1418 new CastExpr(Context->getObjcIdType(),
1419 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1420 // struct objc_super
1421 QualType superType = getSuperStructType();
1422 // (struct objc_super) { <exprs from above> }
1423 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1424 &InitExprs[0], InitExprs.size(),
1425 SourceLocation());
1426 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1427 // struct objc_super *
1428 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1429 Context->getPointerType(SuperRep->getType()),
1430 SourceLocation());
1431 MsgExprs.push_back(Unop);
1432 } else {
1433 llvm::SmallVector<Expr*, 8> ClsExprs;
1434 QualType argType = Context->getPointerType(Context->CharTy);
1435 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1436 clsName->getLength(),
1437 false, argType, SourceLocation(),
1438 SourceLocation()));
1439 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1440 &ClsExprs[0],
1441 ClsExprs.size());
1442 MsgExprs.push_back(Cls);
1443 }
Steve Naroff885e2122007-11-14 23:54:14 +00001444 } else { // instance message.
1445 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001446
Steve Naroff3b1caac2007-12-07 03:50:46 +00001447 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001448 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001449 if (MsgSendStretFlavor)
1450 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001451 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1452
1453 llvm::SmallVector<Expr*, 4> InitExprs;
1454
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001455 InitExprs.push_back(
1456 new CastExpr(Context->getObjcIdType(),
1457 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001458
1459 llvm::SmallVector<Expr*, 8> ClsExprs;
1460 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001461 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1462 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001463 false, argType, SourceLocation(),
1464 SourceLocation()));
1465 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001466 &ClsExprs[0],
1467 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001468 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001469 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001470 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001471 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001472 // struct objc_super
1473 QualType superType = getSuperStructType();
1474 // (struct objc_super) { <exprs from above> }
1475 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1476 &InitExprs[0], InitExprs.size(),
1477 SourceLocation());
1478 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1479 // struct objc_super *
1480 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1481 Context->getPointerType(SuperRep->getType()),
1482 SourceLocation());
1483 MsgExprs.push_back(Unop);
1484 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001485 // Remove all type-casts because it may contain objc-style types; e.g.
1486 // Foo<Proto> *.
1487 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1488 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001489 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1490 MsgExprs.push_back(recExpr);
1491 }
Steve Naroff885e2122007-11-14 23:54:14 +00001492 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001493 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001494 llvm::SmallVector<Expr*, 8> SelExprs;
1495 QualType argType = Context->getPointerType(Context->CharTy);
1496 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1497 Exp->getSelector().getName().size(),
1498 false, argType, SourceLocation(),
1499 SourceLocation()));
1500 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1501 &SelExprs[0], SelExprs.size());
1502 MsgExprs.push_back(SelExp);
1503
1504 // Now push any user supplied arguments.
1505 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001506 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001507 // Make all implicit casts explicit...ICE comes in handy:-)
1508 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1509 // Reuse the ICE type, it is exactly what the doctor ordered.
1510 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1511 }
Steve Naroff885e2122007-11-14 23:54:14 +00001512 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001513 // We've transferred the ownership to MsgExprs. Null out the argument in
1514 // the original expression, since we will delete it below.
1515 Exp->setArg(i, 0);
1516 }
Steve Naroff0744c472007-11-04 22:37:50 +00001517 // Generate the funky cast.
1518 CastExpr *cast;
1519 llvm::SmallVector<QualType, 8> ArgTypes;
1520 QualType returnType;
1521
1522 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001523 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1524 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1525 else
1526 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001527 ArgTypes.push_back(Context->getObjcSelType());
1528 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1529 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001530 for (int i = 0; i < mDecl->getNumParams(); i++) {
1531 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001532 ArgTypes.push_back(t);
1533 }
Steve Naroff0744c472007-11-04 22:37:50 +00001534 returnType = mDecl->getResultType();
1535 } else {
1536 returnType = Context->getObjcIdType();
1537 }
1538 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001539 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001540
1541 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001542 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1543 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001544
1545 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1546 // If we don't do this cast, we get the following bizarre warning/note:
1547 // xx.m:13: warning: function called through a non-compatible type
1548 // xx.m:13: note: if this code is reached, the program will abort
1549 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1550 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001551
Steve Naroff0744c472007-11-04 22:37:50 +00001552 // Now do the "normal" pointer to function cast.
1553 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001554 &ArgTypes[0], ArgTypes.size(),
1555 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001556 castType = Context->getPointerType(castType);
1557 cast = new CastExpr(castType, cast, SourceLocation());
1558
1559 // Don't forget the parens to enforce the proper binding.
1560 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1561
1562 const FunctionType *FT = msgSendType->getAsFunctionType();
1563 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1564 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001565 if (MsgSendStretFlavor) {
1566 // We have the method which returns a struct/union. Must also generate
1567 // call to objc_msgSend_stret and hang both varieties on a conditional
1568 // expression which dictate which one to envoke depending on size of
1569 // method's return type.
1570
1571 // Create a reference to the objc_msgSend_stret() declaration.
1572 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1573 SourceLocation());
1574 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1575 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1576 SourceLocation());
1577 // Now do the "normal" pointer to function cast.
1578 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001579 &ArgTypes[0], ArgTypes.size(),
1580 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001581 castType = Context->getPointerType(castType);
1582 cast = new CastExpr(castType, cast, SourceLocation());
1583
1584 // Don't forget the parens to enforce the proper binding.
1585 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1586
1587 FT = msgSendType->getAsFunctionType();
1588 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1589 FT->getResultType(), SourceLocation());
1590
1591 // Build sizeof(returnType)
1592 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1593 returnType, Context->getSizeType(),
1594 SourceLocation(), SourceLocation());
1595 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1596 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1597 // For X86 it is more complicated and some kind of target specific routine
1598 // is needed to decide what to do.
1599 unsigned IntSize = static_cast<unsigned>(
1600 Context->getTypeSize(Context->IntTy, SourceLocation()));
1601
1602 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1603 Context->IntTy,
1604 SourceLocation());
1605 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1606 BinaryOperator::LE,
1607 Context->IntTy,
1608 SourceLocation());
1609 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1610 ConditionalOperator *CondExpr =
1611 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1612 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1613 // Now do the actual rewrite.
1614 Rewrite.ReplaceStmt(Exp, PE);
1615 delete Exp;
1616 return PE;
1617 }
Steve Naroff71226032007-10-24 22:48:43 +00001618 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001619 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001620
Chris Lattner0021f452007-10-24 16:57:36 +00001621 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001622 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001623}
1624
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001625/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1626/// call to objc_getProtocol("proto-name").
1627Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1628 if (!GetProtocolFunctionDecl)
1629 SynthGetProtocolFunctionDecl();
1630 // Create a call to objc_getProtocol("ProtocolName").
1631 llvm::SmallVector<Expr*, 8> ProtoExprs;
1632 QualType argType = Context->getPointerType(Context->CharTy);
1633 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1634 strlen(Exp->getProtocol()->getName()),
1635 false, argType, SourceLocation(),
1636 SourceLocation()));
1637 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1638 &ProtoExprs[0],
1639 ProtoExprs.size());
1640 Rewrite.ReplaceStmt(Exp, ProtoExp);
1641 delete Exp;
1642 return ProtoExp;
1643
1644}
1645
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001646/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1647/// an objective-c class with ivars.
1648void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1649 std::string &Result) {
1650 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1651 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001652 // Do not synthesize more than once.
1653 if (ObjcSynthesizedStructs.count(CDecl))
1654 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001655 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001656 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001657 SourceLocation LocStart = CDecl->getLocStart();
1658 SourceLocation LocEnd = CDecl->getLocEnd();
1659
1660 const char *startBuf = SM->getCharacterData(LocStart);
1661 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001662 // If no ivars and no root or if its root, directly or indirectly,
1663 // have no ivars (thus not synthesized) then no need to synthesize this class.
1664 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001665 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1666 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1667 Result.c_str(), Result.size());
1668 return;
1669 }
1670
1671 // FIXME: This has potential of causing problem. If
1672 // SynthesizeObjcInternalStruct is ever called recursively.
1673 Result += "\nstruct ";
1674 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001675
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001676 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001677 const char *cursor = strchr(startBuf, '{');
1678 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001679 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001680
1681 // rewrite the original header *without* disturbing the '{'
1682 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1683 Result.c_str(), Result.size());
1684 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1685 Result = "\n struct ";
1686 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001687 // Note: We don't name the field decl. This simplifies the "codegen" for
1688 // accessing a superclasses instance variables (and is similar to what gcc
1689 // does internally). The unnamed struct field feature is enabled with
1690 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1691 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001692 Result += ";\n";
1693
1694 // insert the super class structure definition.
1695 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1696 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1697 }
1698 cursor++; // past '{'
1699
1700 // Now comment out any visibility specifiers.
1701 while (cursor < endBuf) {
1702 if (*cursor == '@') {
1703 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001704 // Skip whitespace.
1705 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1706 /*scan*/;
1707
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001708 // FIXME: presence of @public, etc. inside comment results in
1709 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001710 if (!strncmp(cursor, "public", strlen("public")) ||
1711 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001712 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001713 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001714 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001715 // FIXME: If there are cases where '<' is used in ivar declaration part
1716 // of user code, then scan the ivar list and use needToScanForQualifiers
1717 // for type checking.
1718 else if (*cursor == '<') {
1719 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1720 Rewrite.InsertText(atLoc, "/* ", 3);
1721 cursor = strchr(cursor, '>');
1722 cursor++;
1723 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1724 Rewrite.InsertText(atLoc, " */", 3);
1725 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001726 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001727 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001728 // Don't forget to add a ';'!!
1729 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1730 } else { // we don't have any instance variables - insert super struct.
1731 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1732 Result += " {\n struct ";
1733 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001734 // Note: We don't name the field decl. This simplifies the "codegen" for
1735 // accessing a superclasses instance variables (and is similar to what gcc
1736 // does internally). The unnamed struct field feature is enabled with
1737 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1738 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001739 Result += ";\n};\n";
1740 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1741 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001742 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001743 // Mark this struct as having been generated.
1744 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001745 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001746}
1747
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001748// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1749/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001750void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001751 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001752 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001753 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001754 const char *ClassName,
1755 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001756 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001757 if (NumMethods > 0 && !objc_impl_method) {
1758 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001759 SEL _cmd;
1760 char *method_types;
1761 void *_imp;
1762 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001763 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001764 Result += "\nstruct _objc_method {\n";
1765 Result += "\tSEL _cmd;\n";
1766 Result += "\tchar *method_types;\n";
1767 Result += "\tvoid *_imp;\n";
1768 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001769
1770 /* struct _objc_method_list {
1771 struct _objc_method_list *next_method;
1772 int method_count;
1773 struct _objc_method method_list[];
1774 }
1775 */
1776 Result += "\nstruct _objc_method_list {\n";
1777 Result += "\tstruct _objc_method_list *next_method;\n";
1778 Result += "\tint method_count;\n";
1779 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001780 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001781 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001782 // Build _objc_method_list for class's methods if needed
1783 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001784 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001785 Result += prefix;
1786 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1787 Result += "_METHODS_";
1788 Result += ClassName;
1789 Result += " __attribute__ ((section (\"__OBJC, __";
1790 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001791 Result += "_meth\")))= ";
1792 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1793
1794 Result += "\t,{{(SEL)\"";
1795 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001796 std::string MethodTypeString;
1797 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1798 Result += "\", \"";
1799 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001800 Result += "\", ";
1801 Result += MethodInternalNames[Methods[0]];
1802 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001803 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001804 Result += "\t ,{(SEL)\"";
1805 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001806 std::string MethodTypeString;
1807 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1808 Result += "\", \"";
1809 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001810 Result += "\", ";
1811 Result += MethodInternalNames[Methods[i]];
1812 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001813 }
1814 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001815 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001816}
1817
1818/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1819void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1820 int NumProtocols,
1821 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001822 const char *ClassName,
1823 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001824 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001825 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001826 for (int i = 0; i < NumProtocols; i++) {
1827 ObjcProtocolDecl *PDecl = Protocols[i];
1828 // Output struct protocol_methods holder of method selector and type.
1829 if (!objc_protocol_methods &&
1830 (PDecl->getNumInstanceMethods() > 0
1831 || PDecl->getNumClassMethods() > 0)) {
1832 /* struct protocol_methods {
1833 SEL _cmd;
1834 char *method_types;
1835 }
1836 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001837 Result += "\nstruct protocol_methods {\n";
1838 Result += "\tSEL _cmd;\n";
1839 Result += "\tchar *method_types;\n";
1840 Result += "};\n";
1841
1842 /* struct _objc_protocol_method_list {
1843 int protocol_method_count;
1844 struct protocol_methods protocols[];
1845 }
1846 */
1847 Result += "\nstruct _objc_protocol_method_list {\n";
1848 Result += "\tint protocol_method_count;\n";
1849 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001850 objc_protocol_methods = true;
1851 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001852
Fariborz Jahanian04455192007-10-22 21:41:37 +00001853 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001854 int NumMethods = PDecl->getNumInstanceMethods();
1855 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001856 Result += "\nstatic struct _objc_protocol_method_list "
1857 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1858 Result += PDecl->getName();
1859 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1860 "{\n\t" + utostr(NumMethods) + "\n";
1861
Fariborz Jahanian04455192007-10-22 21:41:37 +00001862 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001863 Result += "\t,{{(SEL)\"";
1864 Result += Methods[0]->getSelector().getName().c_str();
1865 Result += "\", \"\"}\n";
1866
1867 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001868 Result += "\t ,{(SEL)\"";
1869 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001870 std::string MethodTypeString;
1871 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1872 Result += "\", \"";
1873 Result += MethodTypeString;
1874 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001875 }
1876 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001877 }
1878
1879 // Output class methods declared in this protocol.
1880 NumMethods = PDecl->getNumClassMethods();
1881 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001882 Result += "\nstatic struct _objc_protocol_method_list "
1883 "_OBJC_PROTOCOL_CLASS_METHODS_";
1884 Result += PDecl->getName();
1885 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1886 "{\n\t";
1887 Result += utostr(NumMethods);
1888 Result += "\n";
1889
Fariborz Jahanian04455192007-10-22 21:41:37 +00001890 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001891 Result += "\t,{{(SEL)\"";
1892 Result += Methods[0]->getSelector().getName().c_str();
1893 Result += "\", \"\"}\n";
1894
1895 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001896 Result += "\t ,{(SEL)\"";
1897 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001898 std::string MethodTypeString;
1899 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1900 Result += "\", \"";
1901 Result += MethodTypeString;
1902 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001903 }
1904 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001905 }
1906 // Output:
1907 /* struct _objc_protocol {
1908 // Objective-C 1.0 extensions
1909 struct _objc_protocol_extension *isa;
1910 char *protocol_name;
1911 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001912 struct _objc_protocol_method_list *instance_methods;
1913 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001914 };
1915 */
1916 static bool objc_protocol = false;
1917 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001918 Result += "\nstruct _objc_protocol {\n";
1919 Result += "\tstruct _objc_protocol_extension *isa;\n";
1920 Result += "\tchar *protocol_name;\n";
1921 Result += "\tstruct _objc_protocol **protocol_list;\n";
1922 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1923 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1924 Result += "};\n";
1925
1926 /* struct _objc_protocol_list {
1927 struct _objc_protocol_list *next;
1928 int protocol_count;
1929 struct _objc_protocol *class_protocols[];
1930 }
1931 */
1932 Result += "\nstruct _objc_protocol_list {\n";
1933 Result += "\tstruct _objc_protocol_list *next;\n";
1934 Result += "\tint protocol_count;\n";
1935 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1936 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001937 objc_protocol = true;
1938 }
1939
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001940 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1941 Result += PDecl->getName();
1942 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1943 "{\n\t0, \"";
1944 Result += PDecl->getName();
1945 Result += "\", 0, ";
1946 if (PDecl->getInstanceMethods() > 0) {
1947 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1948 Result += PDecl->getName();
1949 Result += ", ";
1950 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001951 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001952 Result += "0, ";
1953 if (PDecl->getClassMethods() > 0) {
1954 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1955 Result += PDecl->getName();
1956 Result += "\n";
1957 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001958 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001959 Result += "0\n";
1960 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001961 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001962 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001963 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1964 Result += prefix;
1965 Result += "_PROTOCOLS_";
1966 Result += ClassName;
1967 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1968 "{\n\t0, ";
1969 Result += utostr(NumProtocols);
1970 Result += "\n";
1971
1972 Result += "\t,{&_OBJC_PROTOCOL_";
1973 Result += Protocols[0]->getName();
1974 Result += " \n";
1975
1976 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001977 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001978 Result += "\t ,&_OBJC_PROTOCOL_";
1979 Result += PDecl->getName();
1980 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001981 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001982 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001983 }
1984}
1985
1986/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1987/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001988void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1989 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001990 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1991 // Find category declaration for this implementation.
1992 ObjcCategoryDecl *CDecl;
1993 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1994 CDecl = CDecl->getNextClassCategory())
1995 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1996 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001997
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001998 char *FullCategoryName = (char*)alloca(
1999 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
2000 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
2001
2002 // Build _objc_method_list for class's instance methods if needed
2003 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2004 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002005 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002006 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002007
2008 // Build _objc_method_list for class's class methods if needed
2009 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
2010 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002011 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002012 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002013
2014 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002015 // Null CDecl is case of a category implementation with no category interface
2016 if (CDecl)
2017 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2018 CDecl->getNumReferencedProtocols(),
2019 "CATEGORY",
2020 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002021
2022 /* struct _objc_category {
2023 char *category_name;
2024 char *class_name;
2025 struct _objc_method_list *instance_methods;
2026 struct _objc_method_list *class_methods;
2027 struct _objc_protocol_list *protocols;
2028 // Objective-C 1.0 extensions
2029 uint32_t size; // sizeof (struct _objc_category)
2030 struct _objc_property_list *instance_properties; // category's own
2031 // @property decl.
2032 };
2033 */
2034
2035 static bool objc_category = false;
2036 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002037 Result += "\nstruct _objc_category {\n";
2038 Result += "\tchar *category_name;\n";
2039 Result += "\tchar *class_name;\n";
2040 Result += "\tstruct _objc_method_list *instance_methods;\n";
2041 Result += "\tstruct _objc_method_list *class_methods;\n";
2042 Result += "\tstruct _objc_protocol_list *protocols;\n";
2043 Result += "\tunsigned int size;\n";
2044 Result += "\tstruct _objc_property_list *instance_properties;\n";
2045 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002046 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002047 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002048 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2049 Result += FullCategoryName;
2050 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2051 Result += IDecl->getName();
2052 Result += "\"\n\t, \"";
2053 Result += ClassDecl->getName();
2054 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002055
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002056 if (IDecl->getNumInstanceMethods() > 0) {
2057 Result += "\t, (struct _objc_method_list *)"
2058 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2059 Result += FullCategoryName;
2060 Result += "\n";
2061 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002062 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002063 Result += "\t, 0\n";
2064 if (IDecl->getNumClassMethods() > 0) {
2065 Result += "\t, (struct _objc_method_list *)"
2066 "&_OBJC_CATEGORY_CLASS_METHODS_";
2067 Result += FullCategoryName;
2068 Result += "\n";
2069 }
2070 else
2071 Result += "\t, 0\n";
2072
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002073 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002074 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2075 Result += FullCategoryName;
2076 Result += "\n";
2077 }
2078 else
2079 Result += "\t, 0\n";
2080 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002081}
2082
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002083/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2084/// ivar offset.
2085void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2086 ObjcIvarDecl *ivar,
2087 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002088 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002089 Result += IDecl->getName();
2090 Result += ", ";
2091 Result += ivar->getName();
2092 Result += ")";
2093}
2094
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002095//===----------------------------------------------------------------------===//
2096// Meta Data Emission
2097//===----------------------------------------------------------------------===//
2098
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002099void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2100 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002101 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2102
2103 // Build _objc_ivar_list metadata for classes ivars if needed
2104 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2105 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002106 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002107 // Explictly declared @interface's are already synthesized.
2108 if (CDecl->ImplicitInterfaceDecl()) {
2109 // FIXME: Implementation of a class with no @interface (legacy) doese not
2110 // produce correct synthesis as yet.
2111 SynthesizeObjcInternalStruct(CDecl, Result);
2112 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002113
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002114 if (NumIvars > 0) {
2115 static bool objc_ivar = false;
2116 if (!objc_ivar) {
2117 /* struct _objc_ivar {
2118 char *ivar_name;
2119 char *ivar_type;
2120 int ivar_offset;
2121 };
2122 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002123 Result += "\nstruct _objc_ivar {\n";
2124 Result += "\tchar *ivar_name;\n";
2125 Result += "\tchar *ivar_type;\n";
2126 Result += "\tint ivar_offset;\n";
2127 Result += "};\n";
2128
2129 /* struct _objc_ivar_list {
2130 int ivar_count;
2131 struct _objc_ivar ivar_list[];
2132 };
2133 */
2134 Result += "\nstruct _objc_ivar_list {\n";
2135 Result += "\tint ivar_count;\n";
2136 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002137 objc_ivar = true;
2138 }
2139
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002140 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2141 Result += IDecl->getName();
2142 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2143 "{\n\t";
2144 Result += utostr(NumIvars);
2145 Result += "\n";
2146
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002147 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2148 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002149 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002150 Result += "\t,{{\"";
2151 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002152 Result += "\", \"";
2153 std::string StrEncoding;
2154 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2155 Result += StrEncoding;
2156 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002157 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2158 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002159 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002160 Result += "\t ,{\"";
2161 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002162 Result += "\", \"";
2163 std::string StrEncoding;
2164 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2165 Result += StrEncoding;
2166 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002167 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2168 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002169 }
2170
2171 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002172 }
2173
2174 // Build _objc_method_list for class's instance methods if needed
2175 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2176 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002177 true,
2178 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002179
2180 // Build _objc_method_list for class's class methods if needed
2181 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002182 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002183 false,
2184 "", IDecl->getName(), Result);
2185
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002186 // Protocols referenced in class declaration?
2187 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2188 CDecl->getNumIntfRefProtocols(),
2189 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002190 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002191
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002192
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002193 // Declaration of class/meta-class metadata
2194 /* struct _objc_class {
2195 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002196 const char *super_class_name;
2197 char *name;
2198 long version;
2199 long info;
2200 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002201 struct _objc_ivar_list *ivars;
2202 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002203 struct objc_cache *cache;
2204 struct objc_protocol_list *protocols;
2205 const char *ivar_layout;
2206 struct _objc_class_ext *ext;
2207 };
2208 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002209 static bool objc_class = false;
2210 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002211 Result += "\nstruct _objc_class {\n";
2212 Result += "\tstruct _objc_class *isa;\n";
2213 Result += "\tconst char *super_class_name;\n";
2214 Result += "\tchar *name;\n";
2215 Result += "\tlong version;\n";
2216 Result += "\tlong info;\n";
2217 Result += "\tlong instance_size;\n";
2218 Result += "\tstruct _objc_ivar_list *ivars;\n";
2219 Result += "\tstruct _objc_method_list *methods;\n";
2220 Result += "\tstruct objc_cache *cache;\n";
2221 Result += "\tstruct _objc_protocol_list *protocols;\n";
2222 Result += "\tconst char *ivar_layout;\n";
2223 Result += "\tstruct _objc_class_ext *ext;\n";
2224 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002225 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002226 }
2227
2228 // Meta-class metadata generation.
2229 ObjcInterfaceDecl *RootClass = 0;
2230 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2231 while (SuperClass) {
2232 RootClass = SuperClass;
2233 SuperClass = SuperClass->getSuperClass();
2234 }
2235 SuperClass = CDecl->getSuperClass();
2236
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002237 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2238 Result += CDecl->getName();
2239 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2240 "{\n\t(struct _objc_class *)\"";
2241 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2242 Result += "\"";
2243
2244 if (SuperClass) {
2245 Result += ", \"";
2246 Result += SuperClass->getName();
2247 Result += "\", \"";
2248 Result += CDecl->getName();
2249 Result += "\"";
2250 }
2251 else {
2252 Result += ", 0, \"";
2253 Result += CDecl->getName();
2254 Result += "\"";
2255 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002256 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002257 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002258 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002259 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002260 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002261 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002262 Result += "\n";
2263 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002264 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002265 Result += ", 0\n";
2266 if (CDecl->getNumIntfRefProtocols() > 0) {
2267 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2268 Result += CDecl->getName();
2269 Result += ",0,0\n";
2270 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002271 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002272 Result += "\t,0,0,0,0\n";
2273 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002274
2275 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002276 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2277 Result += CDecl->getName();
2278 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2279 "{\n\t&_OBJC_METACLASS_";
2280 Result += CDecl->getName();
2281 if (SuperClass) {
2282 Result += ", \"";
2283 Result += SuperClass->getName();
2284 Result += "\", \"";
2285 Result += CDecl->getName();
2286 Result += "\"";
2287 }
2288 else {
2289 Result += ", 0, \"";
2290 Result += CDecl->getName();
2291 Result += "\"";
2292 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002293 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002294 Result += ", 0,1";
2295 if (!ObjcSynthesizedStructs.count(CDecl))
2296 Result += ",0";
2297 else {
2298 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002299 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002300 Result += CDecl->getName();
2301 Result += ")";
2302 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002303 if (NumIvars > 0) {
2304 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2305 Result += CDecl->getName();
2306 Result += "\n\t";
2307 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002308 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002309 Result += ",0";
2310 if (IDecl->getNumInstanceMethods() > 0) {
2311 Result += ", &_OBJC_INSTANCE_METHODS_";
2312 Result += CDecl->getName();
2313 Result += ", 0\n\t";
2314 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002315 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002316 Result += ",0,0";
2317 if (CDecl->getNumIntfRefProtocols() > 0) {
2318 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2319 Result += CDecl->getName();
2320 Result += ", 0,0\n";
2321 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002322 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002323 Result += ",0,0,0\n";
2324 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002325}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002326
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002327/// RewriteImplementations - This routine rewrites all method implementations
2328/// and emits meta-data.
2329
2330void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002331 int ClsDefCount = ClassImplementation.size();
2332 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002333
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002334 if (ClsDefCount == 0 && CatDefCount == 0)
2335 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002336 // Rewrite implemented methods
2337 for (int i = 0; i < ClsDefCount; i++)
2338 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002339
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002340 for (int i = 0; i < CatDefCount; i++)
2341 RewriteImplementationDecl(CategoryImplementation[i]);
2342
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002343 // This is needed for use of offsetof
2344 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002345
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002346 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002347 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002348 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002349
2350 // For each implemented category, write out all its meta data.
2351 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002352 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002353
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002354 // Write objc_symtab metadata
2355 /*
2356 struct _objc_symtab
2357 {
2358 long sel_ref_cnt;
2359 SEL *refs;
2360 short cls_def_cnt;
2361 short cat_def_cnt;
2362 void *defs[cls_def_cnt + cat_def_cnt];
2363 };
2364 */
2365
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002366 Result += "\nstruct _objc_symtab {\n";
2367 Result += "\tlong sel_ref_cnt;\n";
2368 Result += "\tSEL *refs;\n";
2369 Result += "\tshort cls_def_cnt;\n";
2370 Result += "\tshort cat_def_cnt;\n";
2371 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2372 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002373
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002374 Result += "static struct _objc_symtab "
2375 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2376 Result += "\t0, 0, " + utostr(ClsDefCount)
2377 + ", " + utostr(CatDefCount) + "\n";
2378 for (int i = 0; i < ClsDefCount; i++) {
2379 Result += "\t,&_OBJC_CLASS_";
2380 Result += ClassImplementation[i]->getName();
2381 Result += "\n";
2382 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002383
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002384 for (int i = 0; i < CatDefCount; i++) {
2385 Result += "\t,&_OBJC_CATEGORY_";
2386 Result += CategoryImplementation[i]->getClassInterface()->getName();
2387 Result += "_";
2388 Result += CategoryImplementation[i]->getName();
2389 Result += "\n";
2390 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002391
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002392 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002393
2394 // Write objc_module metadata
2395
2396 /*
2397 struct _objc_module {
2398 long version;
2399 long size;
2400 const char *name;
2401 struct _objc_symtab *symtab;
2402 }
2403 */
2404
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002405 Result += "\nstruct _objc_module {\n";
2406 Result += "\tlong version;\n";
2407 Result += "\tlong size;\n";
2408 Result += "\tconst char *name;\n";
2409 Result += "\tstruct _objc_symtab *symtab;\n";
2410 Result += "};\n\n";
2411 Result += "static struct _objc_module "
2412 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002413 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2414 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002415 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002416
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002417}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002418