blob: 2b743f91354578707b432ef1778488085e49520b [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb429ae42007-10-11 00:43:27 +00007//
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;
Ted Kremenek42730c52008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 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.
Ted Kremenek42730c52008-01-07 19:49:32 +000060 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000061 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:
Ted Kremenek17861c52007-12-19 22:51:13 +000065 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000066 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.
Ted Kremenek17861c52007-12-19 22:51:13 +000084 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +000085 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
Ted Kremenek17861c52007-12-19 22:51:13 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroff0744c472007-11-04 22:37:50 +0000127 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();
Ted Kremenek42730c52008-01-07 19:49:32 +0000140 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
141 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000143 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
144 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
145 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
146 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
147 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
148 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000150 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000152 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000153 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);
Ted Kremenek42730c52008-01-07 19:49:32 +0000163 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
164 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
165 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
166 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000167 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000170 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000171 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000172 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000173 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000174 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000175 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000176 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000177 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000178 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000179 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000180
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000181 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000182 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000183 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000184
Ted Kremenek42730c52008-01-07 19:49:32 +0000185 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000186 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000187
Ted Kremenek42730c52008-01-07 19:49:32 +0000188 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
189 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000190 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000191 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000192 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000193 const char *ClassName,
194 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000195
Ted Kremenek42730c52008-01-07 19:49:32 +0000196 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000197 int NumProtocols,
198 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000199 const char *ClassName,
200 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000201 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000202 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000203 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
204 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000205 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000206 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000207 };
208}
209
Chris Lattner258f26c2007-11-30 22:25:36 +0000210ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
211 return new RewriteTest(Diags);
212}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000213
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000214//===----------------------------------------------------------------------===//
215// Top Level Driver Code
216//===----------------------------------------------------------------------===//
217
Chris Lattner569faa62007-10-11 18:38:32 +0000218void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000219 // Two cases: either the decl could be in the main file, or it could be in a
220 // #included file. If the former, rewrite it now. If the later, check to see
221 // if we rewrote the #include/#import.
222 SourceLocation Loc = D->getLocation();
223 Loc = SM->getLogicalLoc(Loc);
224
225 // If this is for a builtin, ignore it.
226 if (Loc.isInvalid()) return;
227
Steve Naroffe9780582007-10-23 23:50:29 +0000228 // Look for built-in declarations that we need to refer during the rewrite.
229 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000230 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000231 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
232 // declared in <Foundation/NSString.h>
233 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
234 ConstantStringClassReference = FVD;
235 return;
236 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000237 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000238 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000239 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000240 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000241 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000242 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000243 } else if (ObjCForwardProtocolDecl *FP =
244 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000245 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000246 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000247 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000248 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
249 return HandleDeclInMainFile(D);
250
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000251 // Otherwise, see if there is a #import in the main file that should be
252 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000253 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000254}
255
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000256/// HandleDeclInMainFile - This is called for each top-level decl defined in the
257/// main file of the input.
258void RewriteTest::HandleDeclInMainFile(Decl *D) {
259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
260 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000261 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000262
Ted Kremenek42730c52008-01-07 19:49:32 +0000263 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000264 if (Stmt *Body = MD->getBody()) {
265 //Body->dump();
266 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000267 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000268 CurMethodDecl = 0;
269 }
Steve Naroff18c83382007-11-13 23:01:27 +0000270 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000271 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000272 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000273 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000274 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000275 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000276 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000277 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000278 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000279 if (VD->getInit())
280 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
281 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000282 // Nothing yet.
283}
284
285RewriteTest::~RewriteTest() {
286 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000287
288 // Rewrite tabs if we care.
289 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000290
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000291 // Rewrite Objective-c meta data*
292 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000293 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000294
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000295 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
296 // we are done.
297 if (const RewriteBuffer *RewriteBuf =
298 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000299 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000300 std::string S(RewriteBuf->begin(), RewriteBuf->end());
301 printf("%s\n", S.c_str());
302 } else {
303 printf("No changes\n");
304 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000305 // Emit metadata.
306 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000307}
308
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000309//===----------------------------------------------------------------------===//
310// Syntactic (non-AST) Rewriting Code
311//===----------------------------------------------------------------------===//
312
Chris Lattner74db1682007-10-16 21:07:07 +0000313void RewriteTest::RewriteInclude(SourceLocation Loc) {
314 // Rip up the #include stack to the main file.
315 SourceLocation IncLoc = Loc, NextLoc = Loc;
316 do {
317 IncLoc = Loc;
318 Loc = SM->getLogicalLoc(NextLoc);
319 NextLoc = SM->getIncludeLoc(Loc);
320 } while (!NextLoc.isInvalid());
321
322 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
323 // IncLoc indicates the header that was included if it is useful.
324 IncLoc = SM->getLogicalLoc(IncLoc);
325 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
326 Loc == LastIncLoc)
327 return;
328 LastIncLoc = Loc;
329
330 unsigned IncCol = SM->getColumnNumber(Loc);
331 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
332
333 // Replace the #import with #include.
334 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
335}
336
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000337void RewriteTest::RewriteTabs() {
338 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
339 const char *MainBufStart = MainBuf.first;
340 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000341
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000342 // Loop over the whole file, looking for tabs.
343 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
344 if (*BufPtr != '\t')
345 continue;
346
347 // Okay, we found a tab. This tab will turn into at least one character,
348 // but it depends on which 'virtual column' it is in. Compute that now.
349 unsigned VCol = 0;
350 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
351 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
352 ++VCol;
353
354 // Okay, now that we know the virtual column, we know how many spaces to
355 // insert. We assume 8-character tab-stops.
356 unsigned Spaces = 8-(VCol & 7);
357
358 // Get the location of the tab.
359 SourceLocation TabLoc =
360 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
361
362 // Rewrite the single tab character into a sequence of spaces.
363 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
364 }
Chris Lattner569faa62007-10-11 18:38:32 +0000365}
366
367
Ted Kremenek42730c52008-01-07 19:49:32 +0000368void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000369 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000370 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000371
372 // Get the start location and compute the semi location.
373 SourceLocation startLoc = ClassDecl->getLocation();
374 const char *startBuf = SM->getCharacterData(startLoc);
375 const char *semiPtr = strchr(startBuf, ';');
376
377 // Translate to typedef's that forward reference structs with the same name
378 // as the class. As a convenience, we include the original declaration
379 // as a comment.
380 std::string typedefString;
381 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000382 typedefString.append(startBuf, semiPtr-startBuf+1);
383 typedefString += "\n";
384 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000385 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000386 typedefString += "#ifndef _REWRITER_typedef_";
387 typedefString += ForwardDecl->getName();
388 typedefString += "\n";
389 typedefString += "#define _REWRITER_typedef_";
390 typedefString += ForwardDecl->getName();
391 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000392 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000393 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000394 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000395 }
396
397 // Replace the @class with typedefs corresponding to the classes.
398 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
399 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000400}
401
Ted Kremenek42730c52008-01-07 19:49:32 +0000402void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000405
Steve Naroff2ce399a2007-12-14 23:37:57 +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);
Steve Naroff667f1682007-10-30 13:30:57 +0000411 }
412}
413
Ted Kremenek42730c52008-01-07 19:49:32 +0000414void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000415{
416 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000417 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000418 SourceLocation Loc = Property->getLocation();
419
420 Rewrite.ReplaceText(Loc, 0, "// ", 3);
421
422 // FIXME: handle properties that are declared across multiple lines.
423 }
424}
425
Ted Kremenek42730c52008-01-07 19:49:32 +0000426void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000427 SourceLocation LocStart = CatDecl->getLocStart();
428
429 // FIXME: handle category headers that are declared across multiple lines.
430 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
431
Ted Kremenek42730c52008-01-07 19:49:32 +0000432 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000433 E = CatDecl->instmeth_end(); I != E; ++I)
434 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000435 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000436 E = CatDecl->classmeth_end(); I != E; ++I)
437 RewriteMethodDeclaration(*I);
438
Steve Naroff667f1682007-10-30 13:30:57 +0000439 // Lastly, comment out the @end.
440 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
441}
442
Ted Kremenek42730c52008-01-07 19:49:32 +0000443void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000444 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000445
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000446 SourceLocation LocStart = PDecl->getLocStart();
447
448 // FIXME: handle protocol headers that are declared across multiple lines.
449 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
450
Ted Kremenek42730c52008-01-07 19:49:32 +0000451 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000452 E = PDecl->instmeth_end(); I != E; ++I)
453 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000454 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000455 E = PDecl->classmeth_end(); I != E; ++I)
456 RewriteMethodDeclaration(*I);
457
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000458 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000459 SourceLocation LocEnd = PDecl->getAtEndLoc();
460 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000461
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000462 // Must comment out @optional/@required
463 const char *startBuf = SM->getCharacterData(LocStart);
464 const char *endBuf = SM->getCharacterData(LocEnd);
465 for (const char *p = startBuf; p < endBuf; p++) {
466 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
467 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000468 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000469 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
470 CommentedOptional.c_str(), CommentedOptional.size());
471
472 }
473 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
474 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000475 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000476 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
477 CommentedRequired.c_str(), CommentedRequired.size());
478
479 }
480 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000481}
482
Ted Kremenek42730c52008-01-07 19:49:32 +0000483void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000484 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000485 if (LocStart.isInvalid())
486 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000487 // FIXME: handle forward protocol that are declared across multiple lines.
488 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
489}
490
Ted Kremenek42730c52008-01-07 19:49:32 +0000491void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000492 std::string &ResultStr) {
493 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000494 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000495 ResultStr += "id";
496 else
497 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000498 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000499
500 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000501 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000502
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000503 if (OMD->isInstance())
504 NameStr += "_I_";
505 else
506 NameStr += "_C_";
507
508 NameStr += OMD->getClassInterface()->getName();
509 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000510
511 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000512 if (ObjCCategoryImplDecl *CID =
513 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000514 NameStr += CID->getName();
515 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000516 }
517 // Append selector names, replacing ':' with '_'
518 const char *selName = OMD->getSelector().getName().c_str();
519 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000520 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000521 else {
522 std::string selString = OMD->getSelector().getName();
523 int len = selString.size();
524 for (int i = 0; i < len; i++)
525 if (selString[i] == ':')
526 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000527 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000528 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000529 // Remember this name for metadata emission
530 MethodInternalNames[OMD] = NameStr;
531 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000532
533 // Rewrite arguments
534 ResultStr += "(";
535
536 // invisible arguments
537 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000538 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000539 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000540 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000541 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000542 ResultStr += selfTy.getAsString();
543 }
544 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000545 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000546
547 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000548 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000549 ResultStr += " _cmd";
550
551 // Method arguments.
552 for (int i = 0; i < OMD->getNumParams(); i++) {
553 ParmVarDecl *PDecl = OMD->getParamDecl(i);
554 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000556 ResultStr += "id";
557 else
558 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000559 ResultStr += " ";
560 ResultStr += PDecl->getName();
561 }
562 ResultStr += ")";
563
564}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000565void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000566 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
567 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000568
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000569 if (IMD)
570 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
571 else
572 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000573
Ted Kremenek42730c52008-01-07 19:49:32 +0000574 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000575 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
576 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000577 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000578 ObjCMethodDecl *OMD = *I;
579 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000580 SourceLocation LocStart = OMD->getLocStart();
581 SourceLocation LocEnd = OMD->getBody()->getLocStart();
582
583 const char *startBuf = SM->getCharacterData(LocStart);
584 const char *endBuf = SM->getCharacterData(LocEnd);
585 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
586 ResultStr.c_str(), ResultStr.size());
587 }
588
Ted Kremenek42730c52008-01-07 19:49:32 +0000589 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000590 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
591 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000592 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000593 ObjCMethodDecl *OMD = *I;
594 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000595 SourceLocation LocStart = OMD->getLocStart();
596 SourceLocation LocEnd = OMD->getBody()->getLocStart();
597
598 const char *startBuf = SM->getCharacterData(LocStart);
599 const char *endBuf = SM->getCharacterData(LocEnd);
600 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
601 ResultStr.c_str(), ResultStr.size());
602 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000603 if (IMD)
604 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
605 else
606 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000607}
608
Ted Kremenek42730c52008-01-07 19:49:32 +0000609void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000610 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000611 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000612 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000613 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
616 ResultStr += "#define _REWRITER_typedef_";
617 ResultStr += ClassDecl->getName();
618 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000619 ResultStr += "typedef struct ";
620 ResultStr += ClassDecl->getName();
621 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000622 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000623 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000624
625 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000626 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000627 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000628 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000629
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000630 RewriteProperties(ClassDecl->getNumPropertyDecl(),
631 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000632 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000633 E = ClassDecl->instmeth_end(); I != E; ++I)
634 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000635 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000636 E = ClassDecl->classmeth_end(); I != E; ++I)
637 RewriteMethodDeclaration(*I);
638
Steve Naroff1ccf4632007-10-30 03:43:13 +0000639 // Lastly, comment out the @end.
640 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000641}
642
Steve Naroff6b759ce2007-11-15 02:58:25 +0000643Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000644 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000645 if (IV->isFreeIvar()) {
646 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
647 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000648 if (Rewrite.ReplaceStmt(IV, Replacement)) {
649 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000650 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
651 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000652 SourceRange Range = IV->getSourceRange();
653 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000654 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000655 delete IV;
656 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000657 } else {
658 if (CurMethodDecl) {
659 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000660 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000661 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
662 IdentifierInfo *II = intT->getDecl()->getIdentifier();
663 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
664 II, 0);
665 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
666
667 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
668 // Don't forget the parens to enforce the proper binding.
669 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000670 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
671 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000672 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
673 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000674 SourceRange Range = IV->getBase()->getSourceRange();
675 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000676 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000677 delete IV->getBase();
678 return PE;
679 }
680 }
681 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000682 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000683 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000684}
685
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000686//===----------------------------------------------------------------------===//
687// Function Body / Expression rewriting
688//===----------------------------------------------------------------------===//
689
Steve Naroff334fbc22007-11-09 15:20:18 +0000690Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000691 // Otherwise, just rewrite all children.
692 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
693 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000694 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000695 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000696 if (newStmt)
697 *CI = newStmt;
698 }
Steve Naroffe9780582007-10-23 23:50:29 +0000699
700 // Handle specific things.
701 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
702 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000703
704 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
705 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000706
707 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
708 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000709
710 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
711 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000712
Steve Naroff71226032007-10-24 22:48:43 +0000713 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
714 // Before we rewrite it, put the original message expression in a comment.
715 SourceLocation startLoc = MessExpr->getLocStart();
716 SourceLocation endLoc = MessExpr->getLocEnd();
717
718 const char *startBuf = SM->getCharacterData(startLoc);
719 const char *endBuf = SM->getCharacterData(endLoc);
720
721 std::string messString;
722 messString += "// ";
723 messString.append(startBuf, endBuf-startBuf+1);
724 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000725
Steve Naroff71226032007-10-24 22:48:43 +0000726 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
727 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
728 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000729 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000730 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000731 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000732
Ted Kremenek42730c52008-01-07 19:49:32 +0000733 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
734 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000735
Ted Kremenek42730c52008-01-07 19:49:32 +0000736 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
737 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000738
739 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
740 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000741
742 if (ObjCForCollectionStmt *StmtForCollection =
743 dyn_cast<ObjCForCollectionStmt>(S))
744 return RewriteObjCForCollectionStmt(StmtForCollection);
745
Steve Naroff764c1ae2007-11-15 10:28:18 +0000746#if 0
747 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
748 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
749 // Get the new text.
750 std::ostringstream Buf;
751 Replacement->printPretty(Buf);
752 const std::string &Str = Buf.str();
753
754 printf("CAST = %s\n", &Str[0]);
755 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
756 delete S;
757 return Replacement;
758 }
759#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000760 // Return this stmt unmodified.
761 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000762}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000763
764
765/// RewriteObjCTryStmt - Rewriter for ObjC2's feareach statement.
766/// It rewrites:
767/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000768
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000769/// Into:
770/// {
771/// type elem;
772/// __objcFastEnumerationState enumState = { 0 };
773/// id items[16];
774/// unsigned long limit = [collection countByEnumeratingWithState:&enumState
775/// objects:items count:16];
776/// if (limit) {
777/// unsigned long startMutations = *enumState.mutationsPtr;
778/// do {
779/// unsigned long counter = 0;
780/// do {
781/// if (startMutations != *enumState.mutationsPtr)
782/// objc_enumerationMutation(collection);
783/// elem = enumState.itemsPtr[counter++];
784/// stmts;
785/// } while (counter < limit);
786/// } while (limit = [collection countByEnumeratingWithState:&enumState
787/// objects:items count:16]);
788/// }
789/// else
790/// elem = nil;
791/// }
792///
793Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
794 return S;
795}
796
Ted Kremenek42730c52008-01-07 19:49:32 +0000797Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000798 // Get the start location and compute the semi location.
799 SourceLocation startLoc = S->getLocStart();
800 const char *startBuf = SM->getCharacterData(startLoc);
801
802 assert((*startBuf == '@') && "bogus @try location");
803
804 std::string buf;
805 // declare a new scope with two variables, _stack and _rethrow.
806 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
807 buf += "int buf[18/*32-bit i386*/];\n";
808 buf += "char *pointers[4];} _stack;\n";
809 buf += "id volatile _rethrow = 0;\n";
810 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000811 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000812
813 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
814
815 startLoc = S->getTryBody()->getLocEnd();
816 startBuf = SM->getCharacterData(startLoc);
817
818 assert((*startBuf == '}') && "bogus @try block");
819
820 SourceLocation lastCurlyLoc = startLoc;
821
822 startLoc = startLoc.getFileLocWithOffset(1);
823 buf = " /* @catch begin */ else {\n";
824 buf += " id _caught = objc_exception_extract(&_stack);\n";
825 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000826 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000827 buf += " _rethrow = objc_exception_extract(&_stack);\n";
828 buf += " else { /* @catch continue */";
829
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000830 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000831
832 bool sawIdTypedCatch = false;
833 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000834 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +0000835 while (catchList) {
836 Stmt *catchStmt = catchList->getCatchParamStmt();
837
838 if (catchList == S->getCatchStmts())
839 buf = "if ("; // we are generating code for the first catch clause
840 else
841 buf = "else if (";
842 startLoc = catchList->getLocStart();
843 startBuf = SM->getCharacterData(startLoc);
844
845 assert((*startBuf == '@') && "bogus @catch location");
846
847 const char *lParenLoc = strchr(startBuf, '(');
848
849 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
850 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000851 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000852 buf += "1) { ";
853 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
854 buf.c_str(), buf.size());
855 sawIdTypedCatch = true;
856 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000857 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +0000858
Ted Kremenek42730c52008-01-07 19:49:32 +0000859 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +0000860 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000861 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000862 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000863 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000864 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
865 buf.c_str(), buf.size());
866 }
867 }
868 // Now rewrite the body...
869 lastCatchBody = catchList->getCatchBody();
870 SourceLocation rParenLoc = catchList->getRParenLoc();
871 SourceLocation bodyLoc = lastCatchBody->getLocStart();
872 const char *bodyBuf = SM->getCharacterData(bodyLoc);
873 const char *rParenBuf = SM->getCharacterData(rParenLoc);
874 assert((*rParenBuf == ')') && "bogus @catch paren location");
875 assert((*bodyBuf == '{') && "bogus @catch body location");
876
877 buf = " = _caught;";
878 // Here we replace ") {" with "= _caught;" (which initializes and
879 // declares the @catch parameter).
880 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
881 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000882 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000883 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000884 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000885 catchList = catchList->getNextCatchStmt();
886 }
887 // Complete the catch list...
888 if (lastCatchBody) {
889 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
890 const char *bodyBuf = SM->getCharacterData(bodyLoc);
891 assert((*bodyBuf == '}') && "bogus @catch body location");
892 bodyLoc = bodyLoc.getFileLocWithOffset(1);
893 buf = " } } /* @catch end */\n";
894
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000895 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000896
897 // Set lastCurlyLoc
898 lastCurlyLoc = lastCatchBody->getLocEnd();
899 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000900 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000901 startLoc = finalStmt->getLocStart();
902 startBuf = SM->getCharacterData(startLoc);
903 assert((*startBuf == '@') && "bogus @finally start");
904
905 buf = "/* @finally */";
906 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
907
908 Stmt *body = finalStmt->getFinallyBody();
909 SourceLocation startLoc = body->getLocStart();
910 SourceLocation endLoc = body->getLocEnd();
911 const char *startBuf = SM->getCharacterData(startLoc);
912 const char *endBuf = SM->getCharacterData(endLoc);
913 assert((*startBuf == '{') && "bogus @finally body location");
914 assert((*endBuf == '}') && "bogus @finally body location");
915
916 startLoc = startLoc.getFileLocWithOffset(1);
917 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000918 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000919 endLoc = endLoc.getFileLocWithOffset(-1);
920 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000921 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000922
923 // Set lastCurlyLoc
924 lastCurlyLoc = body->getLocEnd();
925 }
926 // Now emit the final closing curly brace...
927 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
928 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000929 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000930 return 0;
931}
932
Ted Kremenek42730c52008-01-07 19:49:32 +0000933Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000934 return 0;
935}
936
Ted Kremenek42730c52008-01-07 19:49:32 +0000937Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000938 return 0;
939}
940
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000941// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
942// the throw expression is typically a message expression that's already
943// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +0000944Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000945 // Get the start location and compute the semi location.
946 SourceLocation startLoc = S->getLocStart();
947 const char *startBuf = SM->getCharacterData(startLoc);
948
949 assert((*startBuf == '@') && "bogus @throw location");
950
951 std::string buf;
952 /* void objc_exception_throw(id) __attribute__((noreturn)); */
953 buf = "objc_exception_throw(";
954 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
955 const char *semiBuf = strchr(startBuf, ';');
956 assert((*semiBuf == ';') && "@throw: can't find ';'");
957 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
958 buf = ");";
959 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
960 return 0;
961}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000962
Chris Lattner0021f452007-10-24 16:57:36 +0000963Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000964 // Create a new string expression.
965 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000966 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +0000967 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000968 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
969 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000970 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000971 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
972 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000973 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
974 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner217df512007-12-02 01:09:57 +0000975 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000976 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +0000977 }
978
Chris Lattner4478db92007-11-30 22:53:43 +0000979 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000980 delete Exp;
981 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000982}
983
Steve Naroff296b74f2007-11-05 14:50:49 +0000984Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
985 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
986 // Create a call to sel_registerName("selName").
987 llvm::SmallVector<Expr*, 8> SelExprs;
988 QualType argType = Context->getPointerType(Context->CharTy);
989 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
990 Exp->getSelector().getName().size(),
991 false, argType, SourceLocation(),
992 SourceLocation()));
993 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
994 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000995 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
996 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000997 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
998 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000999 SourceRange Range = Exp->getSourceRange();
1000 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001001 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001002 delete Exp;
1003 return SelExp;
1004}
1005
Steve Naroff71226032007-10-24 22:48:43 +00001006CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1007 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001008 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001009 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001010
1011 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001012 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001013
1014 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001015 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001016 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1017
1018 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001019
Steve Naroff71226032007-10-24 22:48:43 +00001020 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1021}
1022
Steve Naroffc8a92d12007-11-01 13:24:47 +00001023static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1024 const char *&startRef, const char *&endRef) {
1025 while (startBuf < endBuf) {
1026 if (*startBuf == '<')
1027 startRef = startBuf; // mark the start.
1028 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001029 if (startRef && *startRef == '<') {
1030 endRef = startBuf; // mark the end.
1031 return true;
1032 }
1033 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001034 }
1035 startBuf++;
1036 }
1037 return false;
1038}
1039
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001040static void scanToNextArgument(const char *&argRef) {
1041 int angle = 0;
1042 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1043 if (*argRef == '<')
1044 angle++;
1045 else if (*argRef == '>')
1046 angle--;
1047 argRef++;
1048 }
1049 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1050}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001051
Steve Naroffc8a92d12007-11-01 13:24:47 +00001052bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001053
Ted Kremenek42730c52008-01-07 19:49:32 +00001054 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001055 return true;
1056
Ted Kremenek42730c52008-01-07 19:49:32 +00001057 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001058 return true;
1059
Steve Naroffc8a92d12007-11-01 13:24:47 +00001060 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001061 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001062 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001063 return true; // we have "Class <Protocol> *".
1064 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001065 return false;
1066}
1067
Ted Kremenek42730c52008-01-07 19:49:32 +00001068void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001069 SourceLocation Loc;
1070 QualType Type;
1071 const FunctionTypeProto *proto = 0;
1072 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1073 Loc = VD->getLocation();
1074 Type = VD->getType();
1075 }
1076 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1077 Loc = FD->getLocation();
1078 // Check for ObjC 'id' and class types that have been adorned with protocol
1079 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1080 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1081 assert(funcType && "missing function type");
1082 proto = dyn_cast<FunctionTypeProto>(funcType);
1083 if (!proto)
1084 return;
1085 Type = proto->getResultType();
1086 }
1087 else
1088 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001089
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001090 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001091 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001092
1093 const char *endBuf = SM->getCharacterData(Loc);
1094 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001095 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001096 startBuf--; // scan backward (from the decl location) for return type.
1097 const char *startRef = 0, *endRef = 0;
1098 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1099 // Get the locations of the startRef, endRef.
1100 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1101 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1102 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001103 Rewrite.InsertText(LessLoc, "/*", 2);
1104 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001105 }
1106 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001107 if (!proto)
1108 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001109 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001110 const char *startBuf = SM->getCharacterData(Loc);
1111 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001112 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1113 if (needToScanForQualifiers(proto->getArgType(i))) {
1114 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001115
Steve Naroffc8a92d12007-11-01 13:24:47 +00001116 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001117 // scan forward (from the decl location) for argument types.
1118 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001119 const char *startRef = 0, *endRef = 0;
1120 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1121 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001122 SourceLocation LessLoc =
1123 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1124 SourceLocation GreaterLoc =
1125 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001126 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001127 Rewrite.InsertText(LessLoc, "/*", 2);
1128 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001129 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001130 startBuf = ++endBuf;
1131 }
1132 else {
1133 while (*startBuf != ')' && *startBuf != ',')
1134 startBuf++; // scan forward (from the decl location) for argument types.
1135 startBuf++;
1136 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001137 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001138}
1139
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001140// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1141void RewriteTest::SynthSelGetUidFunctionDecl() {
1142 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1143 llvm::SmallVector<QualType, 16> ArgTys;
1144 ArgTys.push_back(Context->getPointerType(
1145 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001146 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001147 &ArgTys[0], ArgTys.size(),
1148 false /*isVariadic*/);
1149 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1150 SelGetUidIdent, getFuncType,
1151 FunctionDecl::Extern, false, 0);
1152}
1153
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001154// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1155void RewriteTest::SynthGetProtocolFunctionDecl() {
1156 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1157 llvm::SmallVector<QualType, 16> ArgTys;
1158 ArgTys.push_back(Context->getPointerType(
1159 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001160 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001161 &ArgTys[0], ArgTys.size(),
1162 false /*isVariadic*/);
1163 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1164 SelGetProtoIdent, getFuncType,
1165 FunctionDecl::Extern, false, 0);
1166}
1167
Steve Naroff02a82aa2007-10-30 23:14:51 +00001168void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1169 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001170 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001171 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001172 return;
1173 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001174 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001175}
1176
1177// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1178void RewriteTest::SynthMsgSendFunctionDecl() {
1179 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1180 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001181 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001182 assert(!argT.isNull() && "Can't find 'id' type");
1183 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001184 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001185 assert(!argT.isNull() && "Can't find 'SEL' type");
1186 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001187 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001188 &ArgTys[0], ArgTys.size(),
1189 true /*isVariadic*/);
1190 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1191 msgSendIdent, msgSendType,
1192 FunctionDecl::Extern, false, 0);
1193}
1194
Steve Naroff764c1ae2007-11-15 10:28:18 +00001195// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1196void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1197 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1198 llvm::SmallVector<QualType, 16> ArgTys;
1199 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1200 &Context->Idents.get("objc_super"), 0);
1201 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1202 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1203 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001204 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001205 assert(!argT.isNull() && "Can't find 'SEL' type");
1206 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001207 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001208 &ArgTys[0], ArgTys.size(),
1209 true /*isVariadic*/);
1210 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1211 msgSendIdent, msgSendType,
1212 FunctionDecl::Extern, false, 0);
1213}
1214
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001215// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1216void RewriteTest::SynthMsgSendStretFunctionDecl() {
1217 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1218 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001219 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001220 assert(!argT.isNull() && "Can't find 'id' type");
1221 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001222 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001223 assert(!argT.isNull() && "Can't find 'SEL' type");
1224 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001225 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001226 &ArgTys[0], ArgTys.size(),
1227 true /*isVariadic*/);
1228 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1229 msgSendIdent, msgSendType,
1230 FunctionDecl::Extern, false, 0);
1231}
1232
1233// SynthMsgSendSuperStretFunctionDecl -
1234// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1235void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1236 IdentifierInfo *msgSendIdent =
1237 &Context->Idents.get("objc_msgSendSuper_stret");
1238 llvm::SmallVector<QualType, 16> ArgTys;
1239 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1240 &Context->Idents.get("objc_super"), 0);
1241 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1242 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1243 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001244 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001245 assert(!argT.isNull() && "Can't find 'SEL' type");
1246 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001247 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001248 &ArgTys[0], ArgTys.size(),
1249 true /*isVariadic*/);
1250 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1251 msgSendIdent, msgSendType,
1252 FunctionDecl::Extern, false, 0);
1253}
1254
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001255// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1256void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1257 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1258 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001259 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001260 assert(!argT.isNull() && "Can't find 'id' type");
1261 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001262 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001263 assert(!argT.isNull() && "Can't find 'SEL' type");
1264 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001265 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001266 &ArgTys[0], ArgTys.size(),
1267 true /*isVariadic*/);
1268 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1269 msgSendIdent, msgSendType,
1270 FunctionDecl::Extern, false, 0);
1271}
1272
Steve Naroff02a82aa2007-10-30 23:14:51 +00001273// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1274void RewriteTest::SynthGetClassFunctionDecl() {
1275 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1276 llvm::SmallVector<QualType, 16> ArgTys;
1277 ArgTys.push_back(Context->getPointerType(
1278 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001279 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001280 &ArgTys[0], ArgTys.size(),
1281 false /*isVariadic*/);
1282 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1283 getClassIdent, getClassType,
1284 FunctionDecl::Extern, false, 0);
1285}
1286
Steve Naroff3b1caac2007-12-07 03:50:46 +00001287// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1288void RewriteTest::SynthGetMetaClassFunctionDecl() {
1289 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1290 llvm::SmallVector<QualType, 16> ArgTys;
1291 ArgTys.push_back(Context->getPointerType(
1292 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001293 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001294 &ArgTys[0], ArgTys.size(),
1295 false /*isVariadic*/);
1296 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1297 getClassIdent, getClassType,
1298 FunctionDecl::Extern, false, 0);
1299}
1300
Steve Naroffabb96362007-11-08 14:30:50 +00001301// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1302void RewriteTest::SynthCFStringFunctionDecl() {
1303 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1304 llvm::SmallVector<QualType, 16> ArgTys;
1305 ArgTys.push_back(Context->getPointerType(
1306 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001307 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001308 &ArgTys[0], ArgTys.size(),
1309 false /*isVariadic*/);
1310 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1311 getClassIdent, getClassType,
1312 FunctionDecl::Extern, false, 0);
1313}
1314
Steve Naroff0add5d22007-11-03 11:27:19 +00001315Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001316#if 1
1317 // This rewrite is specific to GCC, which has builtin support for CFString.
1318 if (!CFStringFunctionDecl)
1319 SynthCFStringFunctionDecl();
1320 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1321 llvm::SmallVector<Expr*, 8> StrExpr;
1322 StrExpr.push_back(Exp->getString());
1323 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1324 &StrExpr[0], StrExpr.size());
1325 // cast to NSConstantString *
1326 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001327 if (Rewrite.ReplaceStmt(Exp, cast)) {
1328 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001329 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1330 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001331 SourceRange Range = Exp->getSourceRange();
1332 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001333 }
Steve Naroffabb96362007-11-08 14:30:50 +00001334 delete Exp;
1335 return cast;
1336#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001337 assert(ConstantStringClassReference && "Can't find constant string reference");
1338 llvm::SmallVector<Expr*, 4> InitExprs;
1339
1340 // Synthesize "(Class)&_NSConstantStringClassReference"
1341 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1342 ConstantStringClassReference->getType(),
1343 SourceLocation());
1344 QualType expType = Context->getPointerType(ClsRef->getType());
1345 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1346 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001347 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001348 SourceLocation());
1349 InitExprs.push_back(cast); // set the 'isa'.
1350 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1351 unsigned IntSize = static_cast<unsigned>(
1352 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1353 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1354 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1355 Exp->getLocStart());
1356 InitExprs.push_back(len); // set "int numBytes".
1357
1358 // struct NSConstantString
1359 QualType CFConstantStrType = Context->getCFConstantStringType();
1360 // (struct NSConstantString) { <exprs from above> }
1361 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1362 &InitExprs[0], InitExprs.size(),
1363 SourceLocation());
1364 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1365 // struct NSConstantString *
1366 expType = Context->getPointerType(StrRep->getType());
1367 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1368 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001369 // cast to NSConstantString *
1370 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001371 Rewrite.ReplaceStmt(Exp, cast);
1372 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001373 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001374#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001375}
1376
Ted Kremenek42730c52008-01-07 19:49:32 +00001377ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001378 // check if we are sending a message to 'super'
1379 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001380 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1381 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1382 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1383 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001384 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001385 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001386 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001387 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001388 if (ObjCInterfaceType *IT =
1389 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001390 if (IT->getDecl() ==
1391 CurMethodDecl->getClassInterface()->getSuperClass())
1392 return IT->getDecl();
1393 }
1394 }
1395 }
1396 }
1397 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001398 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001399 }
1400 return 0;
1401}
1402
1403// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1404QualType RewriteTest::getSuperStructType() {
1405 if (!SuperStructDecl) {
1406 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1407 &Context->Idents.get("objc_super"), 0);
1408 QualType FieldTypes[2];
1409
1410 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001411 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001412 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001413 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001414 // Create fields
1415 FieldDecl *FieldDecls[2];
1416
1417 for (unsigned i = 0; i < 2; ++i)
1418 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1419
1420 SuperStructDecl->defineBody(FieldDecls, 4);
1421 }
1422 return Context->getTagDeclType(SuperStructDecl);
1423}
1424
Steve Naroff71226032007-10-24 22:48:43 +00001425Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001426 if (!SelGetUidFunctionDecl)
1427 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001428 if (!MsgSendFunctionDecl)
1429 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001430 if (!MsgSendSuperFunctionDecl)
1431 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001432 if (!MsgSendStretFunctionDecl)
1433 SynthMsgSendStretFunctionDecl();
1434 if (!MsgSendSuperStretFunctionDecl)
1435 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001436 if (!MsgSendFpretFunctionDecl)
1437 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001438 if (!GetClassFunctionDecl)
1439 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001440 if (!GetMetaClassFunctionDecl)
1441 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001442
Steve Naroff764c1ae2007-11-15 10:28:18 +00001443 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001444 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1445 // May need to use objc_msgSend_stret() as well.
1446 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001447 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001448 QualType resultType = mDecl->getResultType();
1449 if (resultType.getCanonicalType()->isStructureType()
1450 || resultType.getCanonicalType()->isUnionType())
1451 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001452 else if (resultType.getCanonicalType()->isRealFloatingType())
1453 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001454 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001455
Steve Naroff71226032007-10-24 22:48:43 +00001456 // Synthesize a call to objc_msgSend().
1457 llvm::SmallVector<Expr*, 8> MsgExprs;
1458 IdentifierInfo *clsName = Exp->getClassName();
1459
1460 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1461 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001462 if (!strcmp(clsName->getName(), "super")) {
1463 MsgSendFlavor = MsgSendSuperFunctionDecl;
1464 if (MsgSendStretFlavor)
1465 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1466 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1467
Ted Kremenek42730c52008-01-07 19:49:32 +00001468 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001469 CurMethodDecl->getClassInterface()->getSuperClass();
1470
1471 llvm::SmallVector<Expr*, 4> InitExprs;
1472
1473 // set the receiver to self, the first argument to all methods.
1474 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001475 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001476 SourceLocation()));
1477 llvm::SmallVector<Expr*, 8> ClsExprs;
1478 QualType argType = Context->getPointerType(Context->CharTy);
1479 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1480 SuperDecl->getIdentifier()->getLength(),
1481 false, argType, SourceLocation(),
1482 SourceLocation()));
1483 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1484 &ClsExprs[0],
1485 ClsExprs.size());
1486 // To turn off a warning, type-cast to 'id'
1487 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001488 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001489 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1490 // struct objc_super
1491 QualType superType = getSuperStructType();
1492 // (struct objc_super) { <exprs from above> }
1493 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1494 &InitExprs[0], InitExprs.size(),
1495 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001496 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1497 superType, ILE);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001498 // struct objc_super *
1499 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1500 Context->getPointerType(SuperRep->getType()),
1501 SourceLocation());
1502 MsgExprs.push_back(Unop);
1503 } else {
1504 llvm::SmallVector<Expr*, 8> ClsExprs;
1505 QualType argType = Context->getPointerType(Context->CharTy);
1506 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1507 clsName->getLength(),
1508 false, argType, SourceLocation(),
1509 SourceLocation()));
1510 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1511 &ClsExprs[0],
1512 ClsExprs.size());
1513 MsgExprs.push_back(Cls);
1514 }
Steve Naroff885e2122007-11-14 23:54:14 +00001515 } else { // instance message.
1516 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001517
Ted Kremenek42730c52008-01-07 19:49:32 +00001518 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001519 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001520 if (MsgSendStretFlavor)
1521 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001522 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1523
1524 llvm::SmallVector<Expr*, 4> InitExprs;
1525
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001526 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001527 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001528 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001529
1530 llvm::SmallVector<Expr*, 8> ClsExprs;
1531 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001532 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1533 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001534 false, argType, SourceLocation(),
1535 SourceLocation()));
1536 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001537 &ClsExprs[0],
1538 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001539 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001540 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001541 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001542 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001543 // struct objc_super
1544 QualType superType = getSuperStructType();
1545 // (struct objc_super) { <exprs from above> }
1546 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1547 &InitExprs[0], InitExprs.size(),
1548 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001549 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1550 superType, ILE);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001551 // struct objc_super *
1552 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1553 Context->getPointerType(SuperRep->getType()),
1554 SourceLocation());
1555 MsgExprs.push_back(Unop);
1556 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001557 // Remove all type-casts because it may contain objc-style types; e.g.
1558 // Foo<Proto> *.
1559 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1560 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001561 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001562 MsgExprs.push_back(recExpr);
1563 }
Steve Naroff885e2122007-11-14 23:54:14 +00001564 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001565 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001566 llvm::SmallVector<Expr*, 8> SelExprs;
1567 QualType argType = Context->getPointerType(Context->CharTy);
1568 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1569 Exp->getSelector().getName().size(),
1570 false, argType, SourceLocation(),
1571 SourceLocation()));
1572 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1573 &SelExprs[0], SelExprs.size());
1574 MsgExprs.push_back(SelExp);
1575
1576 // Now push any user supplied arguments.
1577 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001578 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001579 // Make all implicit casts explicit...ICE comes in handy:-)
1580 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1581 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001582 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1583 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001584 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001585 }
1586 // Make id<P...> cast into an 'id' cast.
1587 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001588 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001589 while ((CE = dyn_cast<CastExpr>(userExpr)))
1590 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001591 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001592 userExpr, SourceLocation());
1593 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001594 }
Steve Naroff885e2122007-11-14 23:54:14 +00001595 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001596 // We've transferred the ownership to MsgExprs. Null out the argument in
1597 // the original expression, since we will delete it below.
1598 Exp->setArg(i, 0);
1599 }
Steve Naroff0744c472007-11-04 22:37:50 +00001600 // Generate the funky cast.
1601 CastExpr *cast;
1602 llvm::SmallVector<QualType, 8> ArgTypes;
1603 QualType returnType;
1604
1605 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001606 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1607 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1608 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001609 ArgTypes.push_back(Context->getObjCIdType());
1610 ArgTypes.push_back(Context->getObjCSelType());
1611 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001612 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001613 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001614 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1615 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001616 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001617 ArgTypes.push_back(t);
1618 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001619 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1620 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001621 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001622 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001623 }
1624 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001625 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001626
1627 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001628 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1629 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001630
1631 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1632 // If we don't do this cast, we get the following bizarre warning/note:
1633 // xx.m:13: warning: function called through a non-compatible type
1634 // xx.m:13: note: if this code is reached, the program will abort
1635 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1636 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001637
Steve Naroff0744c472007-11-04 22:37:50 +00001638 // Now do the "normal" pointer to function cast.
1639 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001640 &ArgTypes[0], ArgTypes.size(),
1641 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001642 castType = Context->getPointerType(castType);
1643 cast = new CastExpr(castType, cast, SourceLocation());
1644
1645 // Don't forget the parens to enforce the proper binding.
1646 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1647
1648 const FunctionType *FT = msgSendType->getAsFunctionType();
1649 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1650 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001651 if (MsgSendStretFlavor) {
1652 // We have the method which returns a struct/union. Must also generate
1653 // call to objc_msgSend_stret and hang both varieties on a conditional
1654 // expression which dictate which one to envoke depending on size of
1655 // method's return type.
1656
1657 // Create a reference to the objc_msgSend_stret() declaration.
1658 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1659 SourceLocation());
1660 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1661 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1662 SourceLocation());
1663 // Now do the "normal" pointer to function cast.
1664 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001665 &ArgTypes[0], ArgTypes.size(),
1666 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001667 castType = Context->getPointerType(castType);
1668 cast = new CastExpr(castType, cast, SourceLocation());
1669
1670 // Don't forget the parens to enforce the proper binding.
1671 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1672
1673 FT = msgSendType->getAsFunctionType();
1674 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1675 FT->getResultType(), SourceLocation());
1676
1677 // Build sizeof(returnType)
1678 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1679 returnType, Context->getSizeType(),
1680 SourceLocation(), SourceLocation());
1681 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1682 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1683 // For X86 it is more complicated and some kind of target specific routine
1684 // is needed to decide what to do.
1685 unsigned IntSize = static_cast<unsigned>(
1686 Context->getTypeSize(Context->IntTy, SourceLocation()));
1687
1688 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1689 Context->IntTy,
1690 SourceLocation());
1691 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1692 BinaryOperator::LE,
1693 Context->IntTy,
1694 SourceLocation());
1695 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1696 ConditionalOperator *CondExpr =
1697 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1698 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1699 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001700 if (Rewrite.ReplaceStmt(Exp, PE)) {
1701 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001702 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1703 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001704 SourceRange Range = Exp->getSourceRange();
1705 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001706 }
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001707 delete Exp;
1708 return PE;
1709 }
Steve Naroff71226032007-10-24 22:48:43 +00001710 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001711 if (Rewrite.ReplaceStmt(Exp, CE)) {
1712 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001713 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1714 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001715 SourceRange Range = Exp->getSourceRange();
1716 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001717 }
Steve Naroff71226032007-10-24 22:48:43 +00001718
Chris Lattner0021f452007-10-24 16:57:36 +00001719 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001720 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001721}
1722
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001723/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1724/// call to objc_getProtocol("proto-name").
1725Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1726 if (!GetProtocolFunctionDecl)
1727 SynthGetProtocolFunctionDecl();
1728 // Create a call to objc_getProtocol("ProtocolName").
1729 llvm::SmallVector<Expr*, 8> ProtoExprs;
1730 QualType argType = Context->getPointerType(Context->CharTy);
1731 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1732 strlen(Exp->getProtocol()->getName()),
1733 false, argType, SourceLocation(),
1734 SourceLocation()));
1735 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1736 &ProtoExprs[0],
1737 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001738 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1739 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001740 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1741 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001742 SourceRange Range = Exp->getSourceRange();
1743 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001744 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001745 delete Exp;
1746 return ProtoExp;
1747
1748}
1749
Ted Kremenek42730c52008-01-07 19:49:32 +00001750/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001751/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00001752void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001753 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001754 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1755 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001756 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00001757 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001758 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001759 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001760 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001761 SourceLocation LocStart = CDecl->getLocStart();
1762 SourceLocation LocEnd = CDecl->getLocEnd();
1763
1764 const char *startBuf = SM->getCharacterData(LocStart);
1765 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001766 // If no ivars and no root or if its root, directly or indirectly,
1767 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00001768 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001769 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1770 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1771 Result.c_str(), Result.size());
1772 return;
1773 }
1774
1775 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00001776 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001777 Result += "\nstruct ";
1778 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001779
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001780 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001781 const char *cursor = strchr(startBuf, '{');
1782 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00001783 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001784
1785 // rewrite the original header *without* disturbing the '{'
1786 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1787 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00001788 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001789 Result = "\n struct ";
1790 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001791 // Note: We don't name the field decl. This simplifies the "codegen" for
1792 // accessing a superclasses instance variables (and is similar to what gcc
1793 // does internally). The unnamed struct field feature is enabled with
1794 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1795 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001796 Result += ";\n";
1797
1798 // insert the super class structure definition.
1799 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1800 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1801 }
1802 cursor++; // past '{'
1803
1804 // Now comment out any visibility specifiers.
1805 while (cursor < endBuf) {
1806 if (*cursor == '@') {
1807 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001808 // Skip whitespace.
1809 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1810 /*scan*/;
1811
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001812 // FIXME: presence of @public, etc. inside comment results in
1813 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001814 if (!strncmp(cursor, "public", strlen("public")) ||
1815 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001816 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001817 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001818 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001819 // FIXME: If there are cases where '<' is used in ivar declaration part
1820 // of user code, then scan the ivar list and use needToScanForQualifiers
1821 // for type checking.
1822 else if (*cursor == '<') {
1823 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1824 Rewrite.InsertText(atLoc, "/* ", 3);
1825 cursor = strchr(cursor, '>');
1826 cursor++;
1827 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1828 Rewrite.InsertText(atLoc, " */", 3);
1829 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001830 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001831 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001832 // Don't forget to add a ';'!!
1833 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1834 } else { // we don't have any instance variables - insert super struct.
1835 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1836 Result += " {\n struct ";
1837 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001838 // Note: We don't name the field decl. This simplifies the "codegen" for
1839 // accessing a superclasses instance variables (and is similar to what gcc
1840 // does internally). The unnamed struct field feature is enabled with
1841 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1842 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001843 Result += ";\n};\n";
1844 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1845 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001846 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001847 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001848 if (!ObjCSynthesizedStructs.insert(CDecl))
1849 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001850}
1851
Ted Kremenek42730c52008-01-07 19:49:32 +00001852// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001853/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00001854void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001855 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001856 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001857 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001858 const char *ClassName,
1859 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001860 if (MethodBegin == MethodEnd) return;
1861
Fariborz Jahanian04455192007-10-22 21:41:37 +00001862 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001863 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001864 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001865 SEL _cmd;
1866 char *method_types;
1867 void *_imp;
1868 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001869 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001870 Result += "\nstruct _objc_method {\n";
1871 Result += "\tSEL _cmd;\n";
1872 Result += "\tchar *method_types;\n";
1873 Result += "\tvoid *_imp;\n";
1874 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001875
1876 /* struct _objc_method_list {
1877 struct _objc_method_list *next_method;
1878 int method_count;
1879 struct _objc_method method_list[];
1880 }
1881 */
1882 Result += "\nstruct _objc_method_list {\n";
1883 Result += "\tstruct _objc_method_list *next_method;\n";
1884 Result += "\tint method_count;\n";
1885 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001886 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001887 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001888
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001889 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001890 Result += "\nstatic struct _objc_method_list _OBJC_";
1891 Result += prefix;
1892 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1893 Result += "_METHODS_";
1894 Result += ClassName;
1895 Result += " __attribute__ ((section (\"__OBJC, __";
1896 Result += IsInstanceMethod ? "inst" : "cls";
1897 Result += "_meth\")))= ";
1898 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001899
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001900 Result += "\t,{{(SEL)\"";
1901 Result += (*MethodBegin)->getSelector().getName().c_str();
1902 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00001903 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001904 Result += "\", \"";
1905 Result += MethodTypeString;
1906 Result += "\", ";
1907 Result += MethodInternalNames[*MethodBegin];
1908 Result += "}\n";
1909 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1910 Result += "\t ,{(SEL)\"";
1911 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001912 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00001913 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001914 Result += "\", \"";
1915 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001916 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001917 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001918 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001919 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001920 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001921}
1922
Ted Kremenek42730c52008-01-07 19:49:32 +00001923/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
1924void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001925 int NumProtocols,
1926 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001927 const char *ClassName,
1928 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001929 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001930 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001931 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001932 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00001933 // Output struct protocol_methods holder of method selector and type.
1934 if (!objc_protocol_methods &&
1935 (PDecl->getNumInstanceMethods() > 0
1936 || PDecl->getNumClassMethods() > 0)) {
1937 /* struct protocol_methods {
1938 SEL _cmd;
1939 char *method_types;
1940 }
1941 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001942 Result += "\nstruct protocol_methods {\n";
1943 Result += "\tSEL _cmd;\n";
1944 Result += "\tchar *method_types;\n";
1945 Result += "};\n";
1946
1947 /* struct _objc_protocol_method_list {
1948 int protocol_method_count;
1949 struct protocol_methods protocols[];
1950 }
1951 */
1952 Result += "\nstruct _objc_protocol_method_list {\n";
1953 Result += "\tint protocol_method_count;\n";
1954 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001955 objc_protocol_methods = true;
1956 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001957
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001958 int NumMethods = PDecl->getNumInstanceMethods();
1959 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001960 Result += "\nstatic struct _objc_protocol_method_list "
1961 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1962 Result += PDecl->getName();
1963 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1964 "{\n\t" + utostr(NumMethods) + "\n";
1965
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001966 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001967 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001968 E = PDecl->instmeth_end(); I != E; ++I) {
1969 if (I == PDecl->instmeth_begin())
1970 Result += "\t ,{{(SEL)\"";
1971 else
1972 Result += "\t ,{(SEL)\"";
1973 Result += (*I)->getSelector().getName().c_str();
1974 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00001975 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001976 Result += "\", \"";
1977 Result += MethodTypeString;
1978 Result += "\"}\n";
1979 }
1980 Result += "\t }\n};\n";
1981 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001982
1983 // Output class methods declared in this protocol.
1984 NumMethods = PDecl->getNumClassMethods();
1985 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001986 Result += "\nstatic struct _objc_protocol_method_list "
1987 "_OBJC_PROTOCOL_CLASS_METHODS_";
1988 Result += PDecl->getName();
1989 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1990 "{\n\t";
1991 Result += utostr(NumMethods);
1992 Result += "\n";
1993
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00001994 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001995 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00001996 E = PDecl->classmeth_end(); I != E; ++I) {
1997 if (I == PDecl->classmeth_begin())
1998 Result += "\t ,{{(SEL)\"";
1999 else
2000 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002001 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002002 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002003 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002004 Result += "\", \"";
2005 Result += MethodTypeString;
2006 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002007 }
2008 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002009 }
2010 // Output:
2011 /* struct _objc_protocol {
2012 // Objective-C 1.0 extensions
2013 struct _objc_protocol_extension *isa;
2014 char *protocol_name;
2015 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002016 struct _objc_protocol_method_list *instance_methods;
2017 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002018 };
2019 */
2020 static bool objc_protocol = false;
2021 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002022 Result += "\nstruct _objc_protocol {\n";
2023 Result += "\tstruct _objc_protocol_extension *isa;\n";
2024 Result += "\tchar *protocol_name;\n";
2025 Result += "\tstruct _objc_protocol **protocol_list;\n";
2026 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2027 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2028 Result += "};\n";
2029
2030 /* struct _objc_protocol_list {
2031 struct _objc_protocol_list *next;
2032 int protocol_count;
2033 struct _objc_protocol *class_protocols[];
2034 }
2035 */
2036 Result += "\nstruct _objc_protocol_list {\n";
2037 Result += "\tstruct _objc_protocol_list *next;\n";
2038 Result += "\tint protocol_count;\n";
2039 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2040 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002041 objc_protocol = true;
2042 }
2043
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002044 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2045 Result += PDecl->getName();
2046 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2047 "{\n\t0, \"";
2048 Result += PDecl->getName();
2049 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002050 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002051 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2052 Result += PDecl->getName();
2053 Result += ", ";
2054 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002055 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002056 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002057 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002058 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2059 Result += PDecl->getName();
2060 Result += "\n";
2061 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002062 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002063 Result += "0\n";
2064 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002065 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002066 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002067 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2068 Result += prefix;
2069 Result += "_PROTOCOLS_";
2070 Result += ClassName;
2071 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2072 "{\n\t0, ";
2073 Result += utostr(NumProtocols);
2074 Result += "\n";
2075
2076 Result += "\t,{&_OBJC_PROTOCOL_";
2077 Result += Protocols[0]->getName();
2078 Result += " \n";
2079
2080 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002081 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002082 Result += "\t ,&_OBJC_PROTOCOL_";
2083 Result += PDecl->getName();
2084 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002085 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002086 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002087 }
2088}
2089
Ted Kremenek42730c52008-01-07 19:49:32 +00002090/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002091/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002092void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002093 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002094 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002095 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002096 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002097 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2098 CDecl = CDecl->getNextClassCategory())
2099 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2100 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002101
Chris Lattnera661a4d2007-12-23 01:40:15 +00002102 std::string FullCategoryName = ClassDecl->getName();
2103 FullCategoryName += '_';
2104 FullCategoryName += IDecl->getName();
2105
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002106 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002107 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002108 true, "CATEGORY_", FullCategoryName.c_str(),
2109 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002110
2111 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002112 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002113 false, "CATEGORY_", FullCategoryName.c_str(),
2114 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002115
2116 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002117 // Null CDecl is case of a category implementation with no category interface
2118 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002119 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002120 CDecl->getNumReferencedProtocols(),
2121 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002122 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002123
2124 /* struct _objc_category {
2125 char *category_name;
2126 char *class_name;
2127 struct _objc_method_list *instance_methods;
2128 struct _objc_method_list *class_methods;
2129 struct _objc_protocol_list *protocols;
2130 // Objective-C 1.0 extensions
2131 uint32_t size; // sizeof (struct _objc_category)
2132 struct _objc_property_list *instance_properties; // category's own
2133 // @property decl.
2134 };
2135 */
2136
2137 static bool objc_category = false;
2138 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002139 Result += "\nstruct _objc_category {\n";
2140 Result += "\tchar *category_name;\n";
2141 Result += "\tchar *class_name;\n";
2142 Result += "\tstruct _objc_method_list *instance_methods;\n";
2143 Result += "\tstruct _objc_method_list *class_methods;\n";
2144 Result += "\tstruct _objc_protocol_list *protocols;\n";
2145 Result += "\tunsigned int size;\n";
2146 Result += "\tstruct _objc_property_list *instance_properties;\n";
2147 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002148 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002149 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002150 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2151 Result += FullCategoryName;
2152 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2153 Result += IDecl->getName();
2154 Result += "\"\n\t, \"";
2155 Result += ClassDecl->getName();
2156 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002157
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002158 if (IDecl->getNumInstanceMethods() > 0) {
2159 Result += "\t, (struct _objc_method_list *)"
2160 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2161 Result += FullCategoryName;
2162 Result += "\n";
2163 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002164 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002165 Result += "\t, 0\n";
2166 if (IDecl->getNumClassMethods() > 0) {
2167 Result += "\t, (struct _objc_method_list *)"
2168 "&_OBJC_CATEGORY_CLASS_METHODS_";
2169 Result += FullCategoryName;
2170 Result += "\n";
2171 }
2172 else
2173 Result += "\t, 0\n";
2174
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002175 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002176 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2177 Result += FullCategoryName;
2178 Result += "\n";
2179 }
2180 else
2181 Result += "\t, 0\n";
2182 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002183}
2184
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002185/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2186/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002187void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2188 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002189 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002190 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002191 Result += IDecl->getName();
2192 Result += ", ";
2193 Result += ivar->getName();
2194 Result += ")";
2195}
2196
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002197//===----------------------------------------------------------------------===//
2198// Meta Data Emission
2199//===----------------------------------------------------------------------===//
2200
Ted Kremenek42730c52008-01-07 19:49:32 +00002201void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002202 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002203 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002204
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002205 // Explictly declared @interface's are already synthesized.
2206 if (CDecl->ImplicitInterfaceDecl()) {
2207 // FIXME: Implementation of a class with no @interface (legacy) doese not
2208 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002209 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002210 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002211
Chris Lattnerc7b06752007-12-12 07:56:42 +00002212 // Build _objc_ivar_list metadata for classes ivars if needed
2213 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2214 ? IDecl->getImplDeclNumIvars()
2215 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002216 if (NumIvars > 0) {
2217 static bool objc_ivar = false;
2218 if (!objc_ivar) {
2219 /* struct _objc_ivar {
2220 char *ivar_name;
2221 char *ivar_type;
2222 int ivar_offset;
2223 };
2224 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002225 Result += "\nstruct _objc_ivar {\n";
2226 Result += "\tchar *ivar_name;\n";
2227 Result += "\tchar *ivar_type;\n";
2228 Result += "\tint ivar_offset;\n";
2229 Result += "};\n";
2230
2231 /* struct _objc_ivar_list {
2232 int ivar_count;
2233 struct _objc_ivar ivar_list[];
2234 };
2235 */
2236 Result += "\nstruct _objc_ivar_list {\n";
2237 Result += "\tint ivar_count;\n";
2238 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002239 objc_ivar = true;
2240 }
2241
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002242 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2243 Result += IDecl->getName();
2244 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2245 "{\n\t";
2246 Result += utostr(NumIvars);
2247 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002248
Ted Kremenek42730c52008-01-07 19:49:32 +00002249 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002250 if (IDecl->getImplDeclNumIvars() > 0) {
2251 IVI = IDecl->ivar_begin();
2252 IVE = IDecl->ivar_end();
2253 } else {
2254 IVI = CDecl->ivar_begin();
2255 IVE = CDecl->ivar_end();
2256 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002257 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002258 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002259 Result += "\", \"";
2260 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +00002261 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002262 Result += StrEncoding;
2263 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002264 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002265 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002266 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002267 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002268 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002269 Result += "\", \"";
2270 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +00002271 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002272 Result += StrEncoding;
2273 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002274 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002275 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002276 }
2277
2278 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002279 }
2280
2281 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002282 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002283 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002284
2285 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002286 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002287 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002288
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002289 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002290 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002291 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002292 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002293
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002294
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002295 // Declaration of class/meta-class metadata
2296 /* struct _objc_class {
2297 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002298 const char *super_class_name;
2299 char *name;
2300 long version;
2301 long info;
2302 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002303 struct _objc_ivar_list *ivars;
2304 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002305 struct objc_cache *cache;
2306 struct objc_protocol_list *protocols;
2307 const char *ivar_layout;
2308 struct _objc_class_ext *ext;
2309 };
2310 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002311 static bool objc_class = false;
2312 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002313 Result += "\nstruct _objc_class {\n";
2314 Result += "\tstruct _objc_class *isa;\n";
2315 Result += "\tconst char *super_class_name;\n";
2316 Result += "\tchar *name;\n";
2317 Result += "\tlong version;\n";
2318 Result += "\tlong info;\n";
2319 Result += "\tlong instance_size;\n";
2320 Result += "\tstruct _objc_ivar_list *ivars;\n";
2321 Result += "\tstruct _objc_method_list *methods;\n";
2322 Result += "\tstruct objc_cache *cache;\n";
2323 Result += "\tstruct _objc_protocol_list *protocols;\n";
2324 Result += "\tconst char *ivar_layout;\n";
2325 Result += "\tstruct _objc_class_ext *ext;\n";
2326 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002327 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002328 }
2329
2330 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002331 ObjCInterfaceDecl *RootClass = 0;
2332 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002333 while (SuperClass) {
2334 RootClass = SuperClass;
2335 SuperClass = SuperClass->getSuperClass();
2336 }
2337 SuperClass = CDecl->getSuperClass();
2338
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002339 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2340 Result += CDecl->getName();
2341 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2342 "{\n\t(struct _objc_class *)\"";
2343 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2344 Result += "\"";
2345
2346 if (SuperClass) {
2347 Result += ", \"";
2348 Result += SuperClass->getName();
2349 Result += "\", \"";
2350 Result += CDecl->getName();
2351 Result += "\"";
2352 }
2353 else {
2354 Result += ", 0, \"";
2355 Result += CDecl->getName();
2356 Result += "\"";
2357 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002358 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002359 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002360 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002361 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002362 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002363 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002364 Result += "\n";
2365 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002366 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002367 Result += ", 0\n";
2368 if (CDecl->getNumIntfRefProtocols() > 0) {
2369 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2370 Result += CDecl->getName();
2371 Result += ",0,0\n";
2372 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002373 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002374 Result += "\t,0,0,0,0\n";
2375 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002376
2377 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002378 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2379 Result += CDecl->getName();
2380 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2381 "{\n\t&_OBJC_METACLASS_";
2382 Result += CDecl->getName();
2383 if (SuperClass) {
2384 Result += ", \"";
2385 Result += SuperClass->getName();
2386 Result += "\", \"";
2387 Result += CDecl->getName();
2388 Result += "\"";
2389 }
2390 else {
2391 Result += ", 0, \"";
2392 Result += CDecl->getName();
2393 Result += "\"";
2394 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002395 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002396 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002397 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002398 Result += ",0";
2399 else {
2400 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002401 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002402 Result += CDecl->getName();
2403 Result += ")";
2404 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002405 if (NumIvars > 0) {
2406 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2407 Result += CDecl->getName();
2408 Result += "\n\t";
2409 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002410 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002411 Result += ",0";
2412 if (IDecl->getNumInstanceMethods() > 0) {
2413 Result += ", &_OBJC_INSTANCE_METHODS_";
2414 Result += CDecl->getName();
2415 Result += ", 0\n\t";
2416 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002417 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002418 Result += ",0,0";
2419 if (CDecl->getNumIntfRefProtocols() > 0) {
2420 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2421 Result += CDecl->getName();
2422 Result += ", 0,0\n";
2423 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002424 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002425 Result += ",0,0,0\n";
2426 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002427}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002428
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002429/// RewriteImplementations - This routine rewrites all method implementations
2430/// and emits meta-data.
2431
2432void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002433 int ClsDefCount = ClassImplementation.size();
2434 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002435
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002436 if (ClsDefCount == 0 && CatDefCount == 0)
2437 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002438 // Rewrite implemented methods
2439 for (int i = 0; i < ClsDefCount; i++)
2440 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002441
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002442 for (int i = 0; i < CatDefCount; i++)
2443 RewriteImplementationDecl(CategoryImplementation[i]);
2444
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002445 // This is needed for use of offsetof
2446 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002447
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002448 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002449 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002450 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002451
2452 // For each implemented category, write out all its meta data.
2453 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002454 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002455
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002456 // Write objc_symtab metadata
2457 /*
2458 struct _objc_symtab
2459 {
2460 long sel_ref_cnt;
2461 SEL *refs;
2462 short cls_def_cnt;
2463 short cat_def_cnt;
2464 void *defs[cls_def_cnt + cat_def_cnt];
2465 };
2466 */
2467
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002468 Result += "\nstruct _objc_symtab {\n";
2469 Result += "\tlong sel_ref_cnt;\n";
2470 Result += "\tSEL *refs;\n";
2471 Result += "\tshort cls_def_cnt;\n";
2472 Result += "\tshort cat_def_cnt;\n";
2473 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2474 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002475
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002476 Result += "static struct _objc_symtab "
2477 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2478 Result += "\t0, 0, " + utostr(ClsDefCount)
2479 + ", " + utostr(CatDefCount) + "\n";
2480 for (int i = 0; i < ClsDefCount; i++) {
2481 Result += "\t,&_OBJC_CLASS_";
2482 Result += ClassImplementation[i]->getName();
2483 Result += "\n";
2484 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002485
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002486 for (int i = 0; i < CatDefCount; i++) {
2487 Result += "\t,&_OBJC_CATEGORY_";
2488 Result += CategoryImplementation[i]->getClassInterface()->getName();
2489 Result += "_";
2490 Result += CategoryImplementation[i]->getName();
2491 Result += "\n";
2492 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002493
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002494 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002495
2496 // Write objc_module metadata
2497
2498 /*
2499 struct _objc_module {
2500 long version;
2501 long size;
2502 const char *name;
2503 struct _objc_symtab *symtab;
2504 }
2505 */
2506
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002507 Result += "\nstruct _objc_module {\n";
2508 Result += "\tlong version;\n";
2509 Result += "\tlong size;\n";
2510 Result += "\tconst char *name;\n";
2511 Result += "\tstruct _objc_symtab *symtab;\n";
2512 Result += "};\n\n";
2513 Result += "static struct _objc_module "
2514 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002515 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2516 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002517 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002518
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002519}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002520