blob: 6edfcb17d759e2f8ac027af28de358db82db1c84 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000054
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000058
Steve Naroff874e2322007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 public:
Chris Lattner01c57482007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattner26de4652007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-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 Naroffe3abbf52007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-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 Jahanianacb49772007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroff21867b12007-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 Jahanian95673922007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000125
Steve Naroffab972d32007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000147 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane66894c2007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000187 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
189 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194
195 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
196 int NumProtocols,
197 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000200 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
201 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000202 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
203 ObjcIvarDecl *ivar,
204 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattnere365c502007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner8a12c272007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffebf2b562007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Steve Naroffbef11852007-10-26 20:53:56 +0000236 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
237 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000238 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
239 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000240 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
241 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000242 } else if (ObjcForwardProtocolDecl *FP =
243 dyn_cast<ObjcForwardProtocolDecl>(D)){
244 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000245 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000253}
254
Chris Lattnerf04da132007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000261
262 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000269 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000270 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
271 ClassImplementation.push_back(CI);
272 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
273 CategoryImplementation.push_back(CI);
274 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
275 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000277 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000289
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000293
Chris Lattnerf04da132007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306}
307
Chris Lattnerf04da132007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerf04da132007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000340
Chris Lattnerf04da132007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000364}
365
366
Chris Lattnerf04da132007-10-24 17:06:59 +0000367void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
368 int numDecls = ClassDecl->getNumForwardDecls();
369 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
384 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000399}
400
Steve Naroff71c0a952007-11-13 23:01:27 +0000401void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000402 for (int i = 0; i < nMethods; i++) {
403 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000404 SourceLocation LocStart = Method->getLocStart();
405 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000406
Steve Naroff1d098f62007-11-14 14:34:23 +0000407 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
408 Rewrite.InsertText(LocStart, "/* ", 3);
409 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
410 } else {
411 Rewrite.InsertText(LocStart, "// ", 3);
412 }
Steve Naroff423cb562007-10-30 13:30:57 +0000413 }
414}
415
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000416void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
417{
418 for (int i = 0; i < nProperties; i++) {
419 ObjcPropertyDecl *Property = Properties[i];
420 SourceLocation Loc = Property->getLocation();
421
422 Rewrite.ReplaceText(Loc, 0, "// ", 3);
423
424 // FIXME: handle properties that are declared across multiple lines.
425 }
426}
427
Steve Naroff423cb562007-10-30 13:30:57 +0000428void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
429 SourceLocation LocStart = CatDecl->getLocStart();
430
431 // FIXME: handle category headers that are declared across multiple lines.
432 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
433
Steve Naroff71c0a952007-11-13 23:01:27 +0000434 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
435 CatDecl->getInstanceMethods());
436 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
437 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Steve Naroff752d6ef2007-10-30 16:42:30 +0000442void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000444
Steve Naroff752d6ef2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Steve Naroff71c0a952007-11-13 23:01:27 +0000450 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
451 PDecl->getInstanceMethods());
452 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
453 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000454 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000455 SourceLocation LocEnd = PDecl->getAtEndLoc();
456 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000457
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000458 // Must comment out @optional/@required
459 const char *startBuf = SM->getCharacterData(LocStart);
460 const char *endBuf = SM->getCharacterData(LocEnd);
461 for (const char *p = startBuf; p < endBuf; p++) {
462 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
463 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000464 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000465 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
466 CommentedOptional.c_str(), CommentedOptional.size());
467
468 }
469 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
470 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000471 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000472 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
473 CommentedRequired.c_str(), CommentedRequired.size());
474
475 }
476 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000477}
478
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000479void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
480 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000481 if (LocStart.isInvalid())
482 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000483 // FIXME: handle forward protocol that are declared across multiple lines.
484 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
485}
486
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000487void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
488 std::string &ResultStr) {
489 ResultStr += "\nstatic ";
490 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000491 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000492
493 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000494 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000495
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000496 if (OMD->isInstance())
497 NameStr += "_I_";
498 else
499 NameStr += "_C_";
500
501 NameStr += OMD->getClassInterface()->getName();
502 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000503
504 NamedDecl *MethodContext = OMD->getMethodContext();
505 if (ObjcCategoryImplDecl *CID =
506 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000507 NameStr += CID->getName();
508 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509 }
510 // Append selector names, replacing ':' with '_'
511 const char *selName = OMD->getSelector().getName().c_str();
512 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000513 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000514 else {
515 std::string selString = OMD->getSelector().getName();
516 int len = selString.size();
517 for (int i = 0; i < len; i++)
518 if (selString[i] == ':')
519 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000520 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000521 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000522 // Remember this name for metadata emission
523 MethodInternalNames[OMD] = NameStr;
524 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000525
526 // Rewrite arguments
527 ResultStr += "(";
528
529 // invisible arguments
530 if (OMD->isInstance()) {
531 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
532 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000533 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
534 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000535 ResultStr += selfTy.getAsString();
536 }
537 else
538 ResultStr += Context->getObjcIdType().getAsString();
539
540 ResultStr += " self, ";
541 ResultStr += Context->getObjcSelType().getAsString();
542 ResultStr += " _cmd";
543
544 // Method arguments.
545 for (int i = 0; i < OMD->getNumParams(); i++) {
546 ParmVarDecl *PDecl = OMD->getParamDecl(i);
547 ResultStr += ", ";
548 ResultStr += PDecl->getType().getAsString();
549 ResultStr += " ";
550 ResultStr += PDecl->getName();
551 }
552 ResultStr += ")";
553
554}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000555void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
556 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
557 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000559 if (IMD)
560 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
561 else
562 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000563
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000564 for (ObjcCategoryImplDecl::instmeth_iterator
565 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
566 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000568 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000569 RewriteObjcMethodDecl(OMD, ResultStr);
570 SourceLocation LocStart = OMD->getLocStart();
571 SourceLocation LocEnd = OMD->getBody()->getLocStart();
572
573 const char *startBuf = SM->getCharacterData(LocStart);
574 const char *endBuf = SM->getCharacterData(LocEnd);
575 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
576 ResultStr.c_str(), ResultStr.size());
577 }
578
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000579 for (ObjcCategoryImplDecl::classmeth_iterator
580 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
581 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000582 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000583 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000584 RewriteObjcMethodDecl(OMD, ResultStr);
585 SourceLocation LocStart = OMD->getLocStart();
586 SourceLocation LocEnd = OMD->getBody()->getLocStart();
587
588 const char *startBuf = SM->getCharacterData(LocStart);
589 const char *endBuf = SM->getCharacterData(LocEnd);
590 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
591 ResultStr.c_str(), ResultStr.size());
592 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000593 if (IMD)
594 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
595 else
596 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000597}
598
Steve Naroffbef11852007-10-26 20:53:56 +0000599void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000600 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000601 if (!ObjcForwardDecls.count(ClassDecl)) {
602 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000603 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000604 ResultStr += ClassDecl->getName();
605 ResultStr += "\n";
606 ResultStr += "#define _REWRITER_typedef_";
607 ResultStr += ClassDecl->getName();
608 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000609 ResultStr += "typedef struct ";
610 ResultStr += ClassDecl->getName();
611 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000612 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000613 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000614
615 // Mark this typedef as having been generated.
616 ObjcForwardDecls.insert(ClassDecl);
617 }
Steve Narofff908a872007-10-30 02:23:23 +0000618 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
619
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000620 RewriteProperties(ClassDecl->getNumPropertyDecl(),
621 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000622 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
623 ClassDecl->getInstanceMethods());
624 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
625 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000626
Steve Naroff2feac5e2007-10-30 03:43:13 +0000627 // Lastly, comment out the @end.
628 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000629}
630
Steve Naroff7e3411b2007-11-15 02:58:25 +0000631Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
632 ObjcIvarDecl *D = IV->getDecl();
633 if (IV->isFreeIvar()) {
634 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
635 IV->getLocation());
636 Rewrite.ReplaceStmt(IV, Replacement);
637 delete IV;
638 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000639 } else {
640 if (CurMethodDecl) {
641 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
642 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
643 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
644 IdentifierInfo *II = intT->getDecl()->getIdentifier();
645 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
646 II, 0);
647 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
648
649 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
650 // Don't forget the parens to enforce the proper binding.
651 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
652 Rewrite.ReplaceStmt(IV->getBase(), PE);
653 delete IV->getBase();
654 return PE;
655 }
656 }
657 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000658 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000659 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000660}
661
Chris Lattnerf04da132007-10-24 17:06:59 +0000662//===----------------------------------------------------------------------===//
663// Function Body / Expression rewriting
664//===----------------------------------------------------------------------===//
665
Steve Narofff3473a72007-11-09 15:20:18 +0000666Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000667 // Otherwise, just rewrite all children.
668 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
669 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000670 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000671 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000672 if (newStmt)
673 *CI = newStmt;
674 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000675
676 // Handle specific things.
677 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
678 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000679
680 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
681 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000682
683 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
684 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000685
686 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
687 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000688
Steve Naroff934f2762007-10-24 22:48:43 +0000689 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
690 // Before we rewrite it, put the original message expression in a comment.
691 SourceLocation startLoc = MessExpr->getLocStart();
692 SourceLocation endLoc = MessExpr->getLocEnd();
693
694 const char *startBuf = SM->getCharacterData(startLoc);
695 const char *endBuf = SM->getCharacterData(endLoc);
696
697 std::string messString;
698 messString += "// ";
699 messString.append(startBuf, endBuf-startBuf+1);
700 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000701
Steve Naroff934f2762007-10-24 22:48:43 +0000702 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
703 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
704 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000705 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000706 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000707 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000708
709 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
710 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000711
712 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
713 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000714
715 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
716 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000717#if 0
718 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
719 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
720 // Get the new text.
721 std::ostringstream Buf;
722 Replacement->printPretty(Buf);
723 const std::string &Str = Buf.str();
724
725 printf("CAST = %s\n", &Str[0]);
726 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
727 delete S;
728 return Replacement;
729 }
730#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000731 // Return this stmt unmodified.
732 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000733}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000734
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000735Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000736 // Get the start location and compute the semi location.
737 SourceLocation startLoc = S->getLocStart();
738 const char *startBuf = SM->getCharacterData(startLoc);
739
740 assert((*startBuf == '@') && "bogus @try location");
741
742 std::string buf;
743 // declare a new scope with two variables, _stack and _rethrow.
744 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
745 buf += "int buf[18/*32-bit i386*/];\n";
746 buf += "char *pointers[4];} _stack;\n";
747 buf += "id volatile _rethrow = 0;\n";
748 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000749 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000750
751 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
752
753 startLoc = S->getTryBody()->getLocEnd();
754 startBuf = SM->getCharacterData(startLoc);
755
756 assert((*startBuf == '}') && "bogus @try block");
757
758 SourceLocation lastCurlyLoc = startLoc;
759
760 startLoc = startLoc.getFileLocWithOffset(1);
761 buf = " /* @catch begin */ else {\n";
762 buf += " id _caught = objc_exception_extract(&_stack);\n";
763 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000764 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000765 buf += " _rethrow = objc_exception_extract(&_stack);\n";
766 buf += " else { /* @catch continue */";
767
Chris Lattner28d1fe82007-11-08 04:41:51 +0000768 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000769
770 bool sawIdTypedCatch = false;
771 Stmt *lastCatchBody = 0;
772 ObjcAtCatchStmt *catchList = S->getCatchStmts();
773 while (catchList) {
774 Stmt *catchStmt = catchList->getCatchParamStmt();
775
776 if (catchList == S->getCatchStmts())
777 buf = "if ("; // we are generating code for the first catch clause
778 else
779 buf = "else if (";
780 startLoc = catchList->getLocStart();
781 startBuf = SM->getCharacterData(startLoc);
782
783 assert((*startBuf == '@') && "bogus @catch location");
784
785 const char *lParenLoc = strchr(startBuf, '(');
786
787 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
788 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
789 if (t == Context->getObjcIdType()) {
790 buf += "1) { ";
791 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
792 buf.c_str(), buf.size());
793 sawIdTypedCatch = true;
794 } else if (const PointerType *pType = t->getAsPointerType()) {
795 ObjcInterfaceType *cls; // Should be a pointer to a class.
796
797 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
798 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000799 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000800 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000801 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000802 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
803 buf.c_str(), buf.size());
804 }
805 }
806 // Now rewrite the body...
807 lastCatchBody = catchList->getCatchBody();
808 SourceLocation rParenLoc = catchList->getRParenLoc();
809 SourceLocation bodyLoc = lastCatchBody->getLocStart();
810 const char *bodyBuf = SM->getCharacterData(bodyLoc);
811 const char *rParenBuf = SM->getCharacterData(rParenLoc);
812 assert((*rParenBuf == ')') && "bogus @catch paren location");
813 assert((*bodyBuf == '{') && "bogus @catch body location");
814
815 buf = " = _caught;";
816 // Here we replace ") {" with "= _caught;" (which initializes and
817 // declares the @catch parameter).
818 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
819 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000820 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000821 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000822 }
Steve Naroff75730982007-11-07 04:08:17 +0000823 catchList = catchList->getNextCatchStmt();
824 }
825 // Complete the catch list...
826 if (lastCatchBody) {
827 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
828 const char *bodyBuf = SM->getCharacterData(bodyLoc);
829 assert((*bodyBuf == '}') && "bogus @catch body location");
830 bodyLoc = bodyLoc.getFileLocWithOffset(1);
831 buf = " } } /* @catch end */\n";
832
Chris Lattner28d1fe82007-11-08 04:41:51 +0000833 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000834
835 // Set lastCurlyLoc
836 lastCurlyLoc = lastCatchBody->getLocEnd();
837 }
838 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
839 startLoc = finalStmt->getLocStart();
840 startBuf = SM->getCharacterData(startLoc);
841 assert((*startBuf == '@') && "bogus @finally start");
842
843 buf = "/* @finally */";
844 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
845
846 Stmt *body = finalStmt->getFinallyBody();
847 SourceLocation startLoc = body->getLocStart();
848 SourceLocation endLoc = body->getLocEnd();
849 const char *startBuf = SM->getCharacterData(startLoc);
850 const char *endBuf = SM->getCharacterData(endLoc);
851 assert((*startBuf == '{') && "bogus @finally body location");
852 assert((*endBuf == '}') && "bogus @finally body location");
853
854 startLoc = startLoc.getFileLocWithOffset(1);
855 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000856 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000857 endLoc = endLoc.getFileLocWithOffset(-1);
858 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000859 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000860
861 // Set lastCurlyLoc
862 lastCurlyLoc = body->getLocEnd();
863 }
864 // Now emit the final closing curly brace...
865 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
866 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000867 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000868 return 0;
869}
870
871Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
872 return 0;
873}
874
875Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
876 return 0;
877}
878
Steve Naroff2bd03922007-11-07 15:32:26 +0000879// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
880// the throw expression is typically a message expression that's already
881// been rewritten! (which implies the SourceLocation's are invalid).
882Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
883 // Get the start location and compute the semi location.
884 SourceLocation startLoc = S->getLocStart();
885 const char *startBuf = SM->getCharacterData(startLoc);
886
887 assert((*startBuf == '@') && "bogus @throw location");
888
889 std::string buf;
890 /* void objc_exception_throw(id) __attribute__((noreturn)); */
891 buf = "objc_exception_throw(";
892 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
893 const char *semiBuf = strchr(startBuf, ';');
894 assert((*semiBuf == ';') && "@throw: can't find ';'");
895 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
896 buf = ");";
897 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
898 return 0;
899}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000900
Chris Lattnere64b7772007-10-24 16:57:36 +0000901Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000902 // Create a new string expression.
903 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000904 std::string StrEncoding;
905 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
906 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
907 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000908 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000909 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
910 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000911 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
912 "rewriter could not replace sub-expression due to macros");
913 SourceRange Range = Exp->getSourceRange();
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000914 Diags.Report(Exp->getAtLoc(), DiagID, Context->getSourceManager(),
915 0, 0, &Range, 1);
Chris Lattner182745a2007-12-02 01:09:57 +0000916 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000917 return Exp;
918 }
919
Chris Lattner07506182007-11-30 22:53:43 +0000920 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000921 delete Exp;
922 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000923}
924
Steve Naroffb42f8412007-11-05 14:50:49 +0000925Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
926 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
927 // Create a call to sel_registerName("selName").
928 llvm::SmallVector<Expr*, 8> SelExprs;
929 QualType argType = Context->getPointerType(Context->CharTy);
930 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
931 Exp->getSelector().getName().size(),
932 false, argType, SourceLocation(),
933 SourceLocation()));
934 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
935 &SelExprs[0], SelExprs.size());
936 Rewrite.ReplaceStmt(Exp, SelExp);
937 delete Exp;
938 return SelExp;
939}
940
Steve Naroff934f2762007-10-24 22:48:43 +0000941CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
942 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000943 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000944 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000945
946 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000947 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000948
949 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000950 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000951 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
952
953 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000954
Steve Naroff934f2762007-10-24 22:48:43 +0000955 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
956}
957
Steve Naroffd5255f52007-11-01 13:24:47 +0000958static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
959 const char *&startRef, const char *&endRef) {
960 while (startBuf < endBuf) {
961 if (*startBuf == '<')
962 startRef = startBuf; // mark the start.
963 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000964 if (startRef && *startRef == '<') {
965 endRef = startBuf; // mark the end.
966 return true;
967 }
968 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000969 }
970 startBuf++;
971 }
972 return false;
973}
974
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000975static void scanToNextArgument(const char *&argRef) {
976 int angle = 0;
977 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
978 if (*argRef == '<')
979 angle++;
980 else if (*argRef == '>')
981 angle--;
982 argRef++;
983 }
984 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
985}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +0000986
Steve Naroffd5255f52007-11-01 13:24:47 +0000987bool RewriteTest::needToScanForQualifiers(QualType T) {
988 // FIXME: we don't currently represent "id <Protocol>" in the type system.
989 if (T == Context->getObjcIdType())
990 return true;
991
992 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000993 Type *pointeeType = pType->getPointeeType().getTypePtr();
994 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
995 return true; // we have "Class <Protocol> *".
996 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000997 return false;
998}
999
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001000void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001001 SourceLocation Loc;
1002 QualType Type;
1003 const FunctionTypeProto *proto = 0;
1004 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1005 Loc = VD->getLocation();
1006 Type = VD->getType();
1007 }
1008 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1009 Loc = FD->getLocation();
1010 // Check for ObjC 'id' and class types that have been adorned with protocol
1011 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1012 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1013 assert(funcType && "missing function type");
1014 proto = dyn_cast<FunctionTypeProto>(funcType);
1015 if (!proto)
1016 return;
1017 Type = proto->getResultType();
1018 }
1019 else
1020 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001021
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001022 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001023 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001024
1025 const char *endBuf = SM->getCharacterData(Loc);
1026 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001027 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001028 startBuf--; // scan backward (from the decl location) for return type.
1029 const char *startRef = 0, *endRef = 0;
1030 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1031 // Get the locations of the startRef, endRef.
1032 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1033 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1034 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001035 Rewrite.InsertText(LessLoc, "/*", 2);
1036 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001037 }
1038 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001039 if (!proto)
1040 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001041 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001042 const char *startBuf = SM->getCharacterData(Loc);
1043 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001044 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1045 if (needToScanForQualifiers(proto->getArgType(i))) {
1046 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001047
Steve Naroffd5255f52007-11-01 13:24:47 +00001048 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001049 // scan forward (from the decl location) for argument types.
1050 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001051 const char *startRef = 0, *endRef = 0;
1052 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1053 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001054 SourceLocation LessLoc =
1055 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1056 SourceLocation GreaterLoc =
1057 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001058 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001059 Rewrite.InsertText(LessLoc, "/*", 2);
1060 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001061 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001062 startBuf = ++endBuf;
1063 }
1064 else {
1065 while (*startBuf != ')' && *startBuf != ',')
1066 startBuf++; // scan forward (from the decl location) for argument types.
1067 startBuf++;
1068 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001069 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001070}
1071
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001072// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1073void RewriteTest::SynthSelGetUidFunctionDecl() {
1074 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1075 llvm::SmallVector<QualType, 16> ArgTys;
1076 ArgTys.push_back(Context->getPointerType(
1077 Context->CharTy.getQualifiedType(QualType::Const)));
1078 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1079 &ArgTys[0], ArgTys.size(),
1080 false /*isVariadic*/);
1081 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1082 SelGetUidIdent, getFuncType,
1083 FunctionDecl::Extern, false, 0);
1084}
1085
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001086// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1087void RewriteTest::SynthGetProtocolFunctionDecl() {
1088 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1089 llvm::SmallVector<QualType, 16> ArgTys;
1090 ArgTys.push_back(Context->getPointerType(
1091 Context->CharTy.getQualifiedType(QualType::Const)));
1092 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1093 &ArgTys[0], ArgTys.size(),
1094 false /*isVariadic*/);
1095 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1096 SelGetProtoIdent, getFuncType,
1097 FunctionDecl::Extern, false, 0);
1098}
1099
Steve Naroff09b266e2007-10-30 23:14:51 +00001100void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1101 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001102 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001103 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001104 return;
1105 }
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001106 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001107}
1108
1109// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1110void RewriteTest::SynthMsgSendFunctionDecl() {
1111 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1112 llvm::SmallVector<QualType, 16> ArgTys;
1113 QualType argT = Context->getObjcIdType();
1114 assert(!argT.isNull() && "Can't find 'id' type");
1115 ArgTys.push_back(argT);
1116 argT = Context->getObjcSelType();
1117 assert(!argT.isNull() && "Can't find 'SEL' type");
1118 ArgTys.push_back(argT);
1119 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1120 &ArgTys[0], ArgTys.size(),
1121 true /*isVariadic*/);
1122 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1123 msgSendIdent, msgSendType,
1124 FunctionDecl::Extern, false, 0);
1125}
1126
Steve Naroff874e2322007-11-15 10:28:18 +00001127// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1128void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1129 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1130 llvm::SmallVector<QualType, 16> ArgTys;
1131 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1132 &Context->Idents.get("objc_super"), 0);
1133 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1134 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1135 ArgTys.push_back(argT);
1136 argT = Context->getObjcSelType();
1137 assert(!argT.isNull() && "Can't find 'SEL' type");
1138 ArgTys.push_back(argT);
1139 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1140 &ArgTys[0], ArgTys.size(),
1141 true /*isVariadic*/);
1142 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1143 msgSendIdent, msgSendType,
1144 FunctionDecl::Extern, false, 0);
1145}
1146
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001147// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1148void RewriteTest::SynthMsgSendStretFunctionDecl() {
1149 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1150 llvm::SmallVector<QualType, 16> ArgTys;
1151 QualType argT = Context->getObjcIdType();
1152 assert(!argT.isNull() && "Can't find 'id' type");
1153 ArgTys.push_back(argT);
1154 argT = Context->getObjcSelType();
1155 assert(!argT.isNull() && "Can't find 'SEL' type");
1156 ArgTys.push_back(argT);
1157 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1158 &ArgTys[0], ArgTys.size(),
1159 true /*isVariadic*/);
1160 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1161 msgSendIdent, msgSendType,
1162 FunctionDecl::Extern, false, 0);
1163}
1164
1165// SynthMsgSendSuperStretFunctionDecl -
1166// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1167void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1168 IdentifierInfo *msgSendIdent =
1169 &Context->Idents.get("objc_msgSendSuper_stret");
1170 llvm::SmallVector<QualType, 16> ArgTys;
1171 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1172 &Context->Idents.get("objc_super"), 0);
1173 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1174 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1175 ArgTys.push_back(argT);
1176 argT = Context->getObjcSelType();
1177 assert(!argT.isNull() && "Can't find 'SEL' type");
1178 ArgTys.push_back(argT);
1179 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1180 &ArgTys[0], ArgTys.size(),
1181 true /*isVariadic*/);
1182 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1183 msgSendIdent, msgSendType,
1184 FunctionDecl::Extern, false, 0);
1185}
1186
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001187// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1188void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1189 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1190 llvm::SmallVector<QualType, 16> ArgTys;
1191 QualType argT = Context->getObjcIdType();
1192 assert(!argT.isNull() && "Can't find 'id' type");
1193 ArgTys.push_back(argT);
1194 argT = Context->getObjcSelType();
1195 assert(!argT.isNull() && "Can't find 'SEL' type");
1196 ArgTys.push_back(argT);
1197 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1198 &ArgTys[0], ArgTys.size(),
1199 true /*isVariadic*/);
1200 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1201 msgSendIdent, msgSendType,
1202 FunctionDecl::Extern, false, 0);
1203}
1204
Steve Naroff09b266e2007-10-30 23:14:51 +00001205// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1206void RewriteTest::SynthGetClassFunctionDecl() {
1207 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1208 llvm::SmallVector<QualType, 16> ArgTys;
1209 ArgTys.push_back(Context->getPointerType(
1210 Context->CharTy.getQualifiedType(QualType::Const)));
1211 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1212 &ArgTys[0], ArgTys.size(),
1213 false /*isVariadic*/);
1214 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1215 getClassIdent, getClassType,
1216 FunctionDecl::Extern, false, 0);
1217}
1218
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001219// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1220void RewriteTest::SynthGetMetaClassFunctionDecl() {
1221 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1222 llvm::SmallVector<QualType, 16> ArgTys;
1223 ArgTys.push_back(Context->getPointerType(
1224 Context->CharTy.getQualifiedType(QualType::Const)));
1225 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1226 &ArgTys[0], ArgTys.size(),
1227 false /*isVariadic*/);
1228 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1229 getClassIdent, getClassType,
1230 FunctionDecl::Extern, false, 0);
1231}
1232
Steve Naroff96984642007-11-08 14:30:50 +00001233// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1234void RewriteTest::SynthCFStringFunctionDecl() {
1235 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1236 llvm::SmallVector<QualType, 16> ArgTys;
1237 ArgTys.push_back(Context->getPointerType(
1238 Context->CharTy.getQualifiedType(QualType::Const)));
1239 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1240 &ArgTys[0], ArgTys.size(),
1241 false /*isVariadic*/);
1242 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1243 getClassIdent, getClassType,
1244 FunctionDecl::Extern, false, 0);
1245}
1246
Steve Naroffbeaf2992007-11-03 11:27:19 +00001247Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001248#if 1
1249 // This rewrite is specific to GCC, which has builtin support for CFString.
1250 if (!CFStringFunctionDecl)
1251 SynthCFStringFunctionDecl();
1252 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1253 llvm::SmallVector<Expr*, 8> StrExpr;
1254 StrExpr.push_back(Exp->getString());
1255 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1256 &StrExpr[0], StrExpr.size());
1257 // cast to NSConstantString *
1258 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1259 Rewrite.ReplaceStmt(Exp, cast);
1260 delete Exp;
1261 return cast;
1262#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001263 assert(ConstantStringClassReference && "Can't find constant string reference");
1264 llvm::SmallVector<Expr*, 4> InitExprs;
1265
1266 // Synthesize "(Class)&_NSConstantStringClassReference"
1267 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1268 ConstantStringClassReference->getType(),
1269 SourceLocation());
1270 QualType expType = Context->getPointerType(ClsRef->getType());
1271 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1272 expType, SourceLocation());
1273 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1274 SourceLocation());
1275 InitExprs.push_back(cast); // set the 'isa'.
1276 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1277 unsigned IntSize = static_cast<unsigned>(
1278 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1279 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1280 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1281 Exp->getLocStart());
1282 InitExprs.push_back(len); // set "int numBytes".
1283
1284 // struct NSConstantString
1285 QualType CFConstantStrType = Context->getCFConstantStringType();
1286 // (struct NSConstantString) { <exprs from above> }
1287 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1288 &InitExprs[0], InitExprs.size(),
1289 SourceLocation());
1290 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1291 // struct NSConstantString *
1292 expType = Context->getPointerType(StrRep->getType());
1293 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1294 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001295 // cast to NSConstantString *
1296 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001297 Rewrite.ReplaceStmt(Exp, cast);
1298 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001299 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001300#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001301}
1302
Steve Naroff874e2322007-11-15 10:28:18 +00001303ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001304 // check if we are sending a message to 'super'
1305 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001306 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1307 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1308 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1309 if (!strcmp(PVD->getName(), "self")) {
1310 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1311 if (ObjcInterfaceType *IT =
1312 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1313 if (IT->getDecl() ==
1314 CurMethodDecl->getClassInterface()->getSuperClass())
1315 return IT->getDecl();
1316 }
1317 }
1318 }
1319 }
1320 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001321 }
Steve Naroff874e2322007-11-15 10:28:18 +00001322 }
1323 return 0;
1324}
1325
1326// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1327QualType RewriteTest::getSuperStructType() {
1328 if (!SuperStructDecl) {
1329 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1330 &Context->Idents.get("objc_super"), 0);
1331 QualType FieldTypes[2];
1332
1333 // struct objc_object *receiver;
1334 FieldTypes[0] = Context->getObjcIdType();
1335 // struct objc_class *super;
1336 FieldTypes[1] = Context->getObjcClassType();
1337 // Create fields
1338 FieldDecl *FieldDecls[2];
1339
1340 for (unsigned i = 0; i < 2; ++i)
1341 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1342
1343 SuperStructDecl->defineBody(FieldDecls, 4);
1344 }
1345 return Context->getTagDeclType(SuperStructDecl);
1346}
1347
Steve Naroff934f2762007-10-24 22:48:43 +00001348Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001349 if (!SelGetUidFunctionDecl)
1350 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001351 if (!MsgSendFunctionDecl)
1352 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001353 if (!MsgSendSuperFunctionDecl)
1354 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001355 if (!MsgSendStretFunctionDecl)
1356 SynthMsgSendStretFunctionDecl();
1357 if (!MsgSendSuperStretFunctionDecl)
1358 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001359 if (!MsgSendFpretFunctionDecl)
1360 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001361 if (!GetClassFunctionDecl)
1362 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001363 if (!GetMetaClassFunctionDecl)
1364 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001365
Steve Naroff874e2322007-11-15 10:28:18 +00001366 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001367 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1368 // May need to use objc_msgSend_stret() as well.
1369 FunctionDecl *MsgSendStretFlavor = 0;
1370 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1371 QualType resultType = mDecl->getResultType();
1372 if (resultType.getCanonicalType()->isStructureType()
1373 || resultType.getCanonicalType()->isUnionType())
1374 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001375 else if (resultType.getCanonicalType()->isRealFloatingType())
1376 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001377 }
Steve Naroff874e2322007-11-15 10:28:18 +00001378
Steve Naroff934f2762007-10-24 22:48:43 +00001379 // Synthesize a call to objc_msgSend().
1380 llvm::SmallVector<Expr*, 8> MsgExprs;
1381 IdentifierInfo *clsName = Exp->getClassName();
1382
1383 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1384 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001385 if (!strcmp(clsName->getName(), "super")) {
1386 MsgSendFlavor = MsgSendSuperFunctionDecl;
1387 if (MsgSendStretFlavor)
1388 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1389 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1390
1391 ObjcInterfaceDecl *SuperDecl =
1392 CurMethodDecl->getClassInterface()->getSuperClass();
1393
1394 llvm::SmallVector<Expr*, 4> InitExprs;
1395
1396 // set the receiver to self, the first argument to all methods.
1397 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1398 Context->getObjcIdType(),
1399 SourceLocation()));
1400 llvm::SmallVector<Expr*, 8> ClsExprs;
1401 QualType argType = Context->getPointerType(Context->CharTy);
1402 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1403 SuperDecl->getIdentifier()->getLength(),
1404 false, argType, SourceLocation(),
1405 SourceLocation()));
1406 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1407 &ClsExprs[0],
1408 ClsExprs.size());
1409 // To turn off a warning, type-cast to 'id'
1410 InitExprs.push_back(
1411 new CastExpr(Context->getObjcIdType(),
1412 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1413 // struct objc_super
1414 QualType superType = getSuperStructType();
1415 // (struct objc_super) { <exprs from above> }
1416 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1417 &InitExprs[0], InitExprs.size(),
1418 SourceLocation());
1419 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1420 // struct objc_super *
1421 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1422 Context->getPointerType(SuperRep->getType()),
1423 SourceLocation());
1424 MsgExprs.push_back(Unop);
1425 } else {
1426 llvm::SmallVector<Expr*, 8> ClsExprs;
1427 QualType argType = Context->getPointerType(Context->CharTy);
1428 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1429 clsName->getLength(),
1430 false, argType, SourceLocation(),
1431 SourceLocation()));
1432 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1433 &ClsExprs[0],
1434 ClsExprs.size());
1435 MsgExprs.push_back(Cls);
1436 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001437 } else { // instance message.
1438 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001439
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001440 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001441 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001442 if (MsgSendStretFlavor)
1443 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001444 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1445
1446 llvm::SmallVector<Expr*, 4> InitExprs;
1447
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001448 InitExprs.push_back(
1449 new CastExpr(Context->getObjcIdType(),
1450 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001451
1452 llvm::SmallVector<Expr*, 8> ClsExprs;
1453 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001454 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1455 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001456 false, argType, SourceLocation(),
1457 SourceLocation()));
1458 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001459 &ClsExprs[0],
1460 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001461 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001462 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001463 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001464 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001465 // struct objc_super
1466 QualType superType = getSuperStructType();
1467 // (struct objc_super) { <exprs from above> }
1468 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1469 &InitExprs[0], InitExprs.size(),
1470 SourceLocation());
1471 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1472 // struct objc_super *
1473 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1474 Context->getPointerType(SuperRep->getType()),
1475 SourceLocation());
1476 MsgExprs.push_back(Unop);
1477 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001478 // Remove all type-casts because it may contain objc-style types; e.g.
1479 // Foo<Proto> *.
1480 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1481 recExpr = CE->getSubExpr();
Steve Naroff874e2322007-11-15 10:28:18 +00001482 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1483 MsgExprs.push_back(recExpr);
1484 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001485 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001486 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001487 llvm::SmallVector<Expr*, 8> SelExprs;
1488 QualType argType = Context->getPointerType(Context->CharTy);
1489 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1490 Exp->getSelector().getName().size(),
1491 false, argType, SourceLocation(),
1492 SourceLocation()));
1493 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1494 &SelExprs[0], SelExprs.size());
1495 MsgExprs.push_back(SelExp);
1496
1497 // Now push any user supplied arguments.
1498 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001499 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001500 // Make all implicit casts explicit...ICE comes in handy:-)
1501 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1502 // Reuse the ICE type, it is exactly what the doctor ordered.
1503 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1504 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001505 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001506 // We've transferred the ownership to MsgExprs. Null out the argument in
1507 // the original expression, since we will delete it below.
1508 Exp->setArg(i, 0);
1509 }
Steve Naroffab972d32007-11-04 22:37:50 +00001510 // Generate the funky cast.
1511 CastExpr *cast;
1512 llvm::SmallVector<QualType, 8> ArgTypes;
1513 QualType returnType;
1514
1515 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001516 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1517 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1518 else
1519 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001520 ArgTypes.push_back(Context->getObjcSelType());
1521 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1522 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001523 for (int i = 0; i < mDecl->getNumParams(); i++) {
1524 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001525 ArgTypes.push_back(t);
1526 }
Steve Naroffab972d32007-11-04 22:37:50 +00001527 returnType = mDecl->getResultType();
1528 } else {
1529 returnType = Context->getObjcIdType();
1530 }
1531 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001532 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001533
1534 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001535 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1536 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001537
1538 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1539 // If we don't do this cast, we get the following bizarre warning/note:
1540 // xx.m:13: warning: function called through a non-compatible type
1541 // xx.m:13: note: if this code is reached, the program will abort
1542 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1543 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001544
Steve Naroffab972d32007-11-04 22:37:50 +00001545 // Now do the "normal" pointer to function cast.
1546 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001547 &ArgTypes[0], ArgTypes.size(),
1548 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001549 castType = Context->getPointerType(castType);
1550 cast = new CastExpr(castType, cast, SourceLocation());
1551
1552 // Don't forget the parens to enforce the proper binding.
1553 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1554
1555 const FunctionType *FT = msgSendType->getAsFunctionType();
1556 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1557 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001558 if (MsgSendStretFlavor) {
1559 // We have the method which returns a struct/union. Must also generate
1560 // call to objc_msgSend_stret and hang both varieties on a conditional
1561 // expression which dictate which one to envoke depending on size of
1562 // method's return type.
1563
1564 // Create a reference to the objc_msgSend_stret() declaration.
1565 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1566 SourceLocation());
1567 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1568 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1569 SourceLocation());
1570 // Now do the "normal" pointer to function cast.
1571 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001572 &ArgTypes[0], ArgTypes.size(),
1573 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001574 castType = Context->getPointerType(castType);
1575 cast = new CastExpr(castType, cast, SourceLocation());
1576
1577 // Don't forget the parens to enforce the proper binding.
1578 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1579
1580 FT = msgSendType->getAsFunctionType();
1581 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1582 FT->getResultType(), SourceLocation());
1583
1584 // Build sizeof(returnType)
1585 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1586 returnType, Context->getSizeType(),
1587 SourceLocation(), SourceLocation());
1588 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1589 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1590 // For X86 it is more complicated and some kind of target specific routine
1591 // is needed to decide what to do.
1592 unsigned IntSize = static_cast<unsigned>(
1593 Context->getTypeSize(Context->IntTy, SourceLocation()));
1594
1595 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1596 Context->IntTy,
1597 SourceLocation());
1598 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1599 BinaryOperator::LE,
1600 Context->IntTy,
1601 SourceLocation());
1602 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1603 ConditionalOperator *CondExpr =
1604 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1605 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1606 // Now do the actual rewrite.
1607 Rewrite.ReplaceStmt(Exp, PE);
1608 delete Exp;
1609 return PE;
1610 }
Steve Naroff934f2762007-10-24 22:48:43 +00001611 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001612 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001613
Chris Lattnere64b7772007-10-24 16:57:36 +00001614 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001615 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001616}
1617
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001618/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1619/// call to objc_getProtocol("proto-name").
1620Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1621 if (!GetProtocolFunctionDecl)
1622 SynthGetProtocolFunctionDecl();
1623 // Create a call to objc_getProtocol("ProtocolName").
1624 llvm::SmallVector<Expr*, 8> ProtoExprs;
1625 QualType argType = Context->getPointerType(Context->CharTy);
1626 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1627 strlen(Exp->getProtocol()->getName()),
1628 false, argType, SourceLocation(),
1629 SourceLocation()));
1630 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1631 &ProtoExprs[0],
1632 ProtoExprs.size());
1633 Rewrite.ReplaceStmt(Exp, ProtoExp);
1634 delete Exp;
1635 return ProtoExp;
1636
1637}
1638
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001639/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1640/// an objective-c class with ivars.
1641void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1642 std::string &Result) {
1643 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1644 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001645 // Do not synthesize more than once.
1646 if (ObjcSynthesizedStructs.count(CDecl))
1647 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001648 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001649 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001650 SourceLocation LocStart = CDecl->getLocStart();
1651 SourceLocation LocEnd = CDecl->getLocEnd();
1652
1653 const char *startBuf = SM->getCharacterData(LocStart);
1654 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001655 // If no ivars and no root or if its root, directly or indirectly,
1656 // have no ivars (thus not synthesized) then no need to synthesize this class.
1657 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001658 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1659 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1660 Result.c_str(), Result.size());
1661 return;
1662 }
1663
1664 // FIXME: This has potential of causing problem. If
1665 // SynthesizeObjcInternalStruct is ever called recursively.
1666 Result += "\nstruct ";
1667 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001668
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001669 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001670 const char *cursor = strchr(startBuf, '{');
1671 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001672 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001673
1674 // rewrite the original header *without* disturbing the '{'
1675 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1676 Result.c_str(), Result.size());
1677 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1678 Result = "\n struct ";
1679 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001680 // Note: We don't name the field decl. This simplifies the "codegen" for
1681 // accessing a superclasses instance variables (and is similar to what gcc
1682 // does internally). The unnamed struct field feature is enabled with
1683 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1684 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001685 Result += ";\n";
1686
1687 // insert the super class structure definition.
1688 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1689 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1690 }
1691 cursor++; // past '{'
1692
1693 // Now comment out any visibility specifiers.
1694 while (cursor < endBuf) {
1695 if (*cursor == '@') {
1696 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001697 // Skip whitespace.
1698 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1699 /*scan*/;
1700
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001701 // FIXME: presence of @public, etc. inside comment results in
1702 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001703 if (!strncmp(cursor, "public", strlen("public")) ||
1704 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001705 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001706 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001707 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001708 // FIXME: If there are cases where '<' is used in ivar declaration part
1709 // of user code, then scan the ivar list and use needToScanForQualifiers
1710 // for type checking.
1711 else if (*cursor == '<') {
1712 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1713 Rewrite.InsertText(atLoc, "/* ", 3);
1714 cursor = strchr(cursor, '>');
1715 cursor++;
1716 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1717 Rewrite.InsertText(atLoc, " */", 3);
1718 }
Steve Narofffea763e82007-11-14 19:25:57 +00001719 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001720 }
Steve Narofffea763e82007-11-14 19:25:57 +00001721 // Don't forget to add a ';'!!
1722 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1723 } else { // we don't have any instance variables - insert super struct.
1724 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1725 Result += " {\n struct ";
1726 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001727 // Note: We don't name the field decl. This simplifies the "codegen" for
1728 // accessing a superclasses instance variables (and is similar to what gcc
1729 // does internally). The unnamed struct field feature is enabled with
1730 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1731 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001732 Result += ";\n};\n";
1733 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1734 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001735 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001736 // Mark this struct as having been generated.
1737 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001738 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001739}
1740
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001741// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1742/// class methods.
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001743void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1744 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001745 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001746 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001747 const char *ClassName,
1748 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001749 if (MethodBegin == MethodEnd) return;
1750
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001751 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001752 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001753 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001754 SEL _cmd;
1755 char *method_types;
1756 void *_imp;
1757 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001758 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001759 Result += "\nstruct _objc_method {\n";
1760 Result += "\tSEL _cmd;\n";
1761 Result += "\tchar *method_types;\n";
1762 Result += "\tvoid *_imp;\n";
1763 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001764
1765 /* struct _objc_method_list {
1766 struct _objc_method_list *next_method;
1767 int method_count;
1768 struct _objc_method method_list[];
1769 }
1770 */
1771 Result += "\nstruct _objc_method_list {\n";
1772 Result += "\tstruct _objc_method_list *next_method;\n";
1773 Result += "\tint method_count;\n";
1774 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001775 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001776 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001777
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001778 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001779 Result += "\nstatic struct _objc_method_list _OBJC_";
1780 Result += prefix;
1781 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1782 Result += "_METHODS_";
1783 Result += ClassName;
1784 Result += " __attribute__ ((section (\"__OBJC, __";
1785 Result += IsInstanceMethod ? "inst" : "cls";
1786 Result += "_meth\")))= ";
1787 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001788
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001789 Result += "\t,{{(SEL)\"";
1790 Result += (*MethodBegin)->getSelector().getName().c_str();
1791 std::string MethodTypeString;
1792 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1793 Result += "\", \"";
1794 Result += MethodTypeString;
1795 Result += "\", ";
1796 Result += MethodInternalNames[*MethodBegin];
1797 Result += "}\n";
1798 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1799 Result += "\t ,{(SEL)\"";
1800 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001801 std::string MethodTypeString;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001802 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001803 Result += "\", \"";
1804 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001805 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001806 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001807 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001808 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001809 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001810}
1811
1812/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1813void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1814 int NumProtocols,
1815 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001816 const char *ClassName,
1817 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001818 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001819 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001820 for (int i = 0; i < NumProtocols; i++) {
1821 ObjcProtocolDecl *PDecl = Protocols[i];
1822 // Output struct protocol_methods holder of method selector and type.
1823 if (!objc_protocol_methods &&
1824 (PDecl->getNumInstanceMethods() > 0
1825 || PDecl->getNumClassMethods() > 0)) {
1826 /* struct protocol_methods {
1827 SEL _cmd;
1828 char *method_types;
1829 }
1830 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001831 Result += "\nstruct protocol_methods {\n";
1832 Result += "\tSEL _cmd;\n";
1833 Result += "\tchar *method_types;\n";
1834 Result += "};\n";
1835
1836 /* struct _objc_protocol_method_list {
1837 int protocol_method_count;
1838 struct protocol_methods protocols[];
1839 }
1840 */
1841 Result += "\nstruct _objc_protocol_method_list {\n";
1842 Result += "\tint protocol_method_count;\n";
1843 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001844 objc_protocol_methods = true;
1845 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001846
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001847 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001848 int NumMethods = PDecl->getNumInstanceMethods();
1849 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001850 Result += "\nstatic struct _objc_protocol_method_list "
1851 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1852 Result += PDecl->getName();
1853 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1854 "{\n\t" + utostr(NumMethods) + "\n";
1855
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001856 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001857 Result += "\t,{{(SEL)\"";
1858 Result += Methods[0]->getSelector().getName().c_str();
1859 Result += "\", \"\"}\n";
1860
1861 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001862 Result += "\t ,{(SEL)\"";
1863 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001864 std::string MethodTypeString;
1865 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1866 Result += "\", \"";
1867 Result += MethodTypeString;
1868 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001869 }
1870 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001871 }
1872
1873 // Output class methods declared in this protocol.
1874 NumMethods = PDecl->getNumClassMethods();
1875 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001876 Result += "\nstatic struct _objc_protocol_method_list "
1877 "_OBJC_PROTOCOL_CLASS_METHODS_";
1878 Result += PDecl->getName();
1879 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1880 "{\n\t";
1881 Result += utostr(NumMethods);
1882 Result += "\n";
1883
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001884 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001885 Result += "\t,{{(SEL)\"";
1886 Result += Methods[0]->getSelector().getName().c_str();
1887 Result += "\", \"\"}\n";
1888
1889 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001890 Result += "\t ,{(SEL)\"";
1891 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001892 std::string MethodTypeString;
1893 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1894 Result += "\", \"";
1895 Result += MethodTypeString;
1896 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001897 }
1898 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001899 }
1900 // Output:
1901 /* struct _objc_protocol {
1902 // Objective-C 1.0 extensions
1903 struct _objc_protocol_extension *isa;
1904 char *protocol_name;
1905 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001906 struct _objc_protocol_method_list *instance_methods;
1907 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001908 };
1909 */
1910 static bool objc_protocol = false;
1911 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001912 Result += "\nstruct _objc_protocol {\n";
1913 Result += "\tstruct _objc_protocol_extension *isa;\n";
1914 Result += "\tchar *protocol_name;\n";
1915 Result += "\tstruct _objc_protocol **protocol_list;\n";
1916 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1917 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1918 Result += "};\n";
1919
1920 /* struct _objc_protocol_list {
1921 struct _objc_protocol_list *next;
1922 int protocol_count;
1923 struct _objc_protocol *class_protocols[];
1924 }
1925 */
1926 Result += "\nstruct _objc_protocol_list {\n";
1927 Result += "\tstruct _objc_protocol_list *next;\n";
1928 Result += "\tint protocol_count;\n";
1929 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1930 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001931 objc_protocol = true;
1932 }
1933
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001934 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1935 Result += PDecl->getName();
1936 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1937 "{\n\t0, \"";
1938 Result += PDecl->getName();
1939 Result += "\", 0, ";
1940 if (PDecl->getInstanceMethods() > 0) {
1941 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1942 Result += PDecl->getName();
1943 Result += ", ";
1944 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001945 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001946 Result += "0, ";
1947 if (PDecl->getClassMethods() > 0) {
1948 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1949 Result += PDecl->getName();
1950 Result += "\n";
1951 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001952 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001953 Result += "0\n";
1954 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001955 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001956 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001957 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1958 Result += prefix;
1959 Result += "_PROTOCOLS_";
1960 Result += ClassName;
1961 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1962 "{\n\t0, ";
1963 Result += utostr(NumProtocols);
1964 Result += "\n";
1965
1966 Result += "\t,{&_OBJC_PROTOCOL_";
1967 Result += Protocols[0]->getName();
1968 Result += " \n";
1969
1970 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001971 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001972 Result += "\t ,&_OBJC_PROTOCOL_";
1973 Result += PDecl->getName();
1974 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001975 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001976 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001977 }
1978}
1979
1980/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1981/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001982void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1983 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001984 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1985 // Find category declaration for this implementation.
1986 ObjcCategoryDecl *CDecl;
1987 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1988 CDecl = CDecl->getNextClassCategory())
1989 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1990 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001991
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001992 char *FullCategoryName = (char*)alloca(
1993 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1994 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1995
1996 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001997 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
1998 true, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001999
2000 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002001 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2002 false, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002003
2004 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002005 // Null CDecl is case of a category implementation with no category interface
2006 if (CDecl)
2007 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2008 CDecl->getNumReferencedProtocols(),
2009 "CATEGORY",
2010 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002011
2012 /* struct _objc_category {
2013 char *category_name;
2014 char *class_name;
2015 struct _objc_method_list *instance_methods;
2016 struct _objc_method_list *class_methods;
2017 struct _objc_protocol_list *protocols;
2018 // Objective-C 1.0 extensions
2019 uint32_t size; // sizeof (struct _objc_category)
2020 struct _objc_property_list *instance_properties; // category's own
2021 // @property decl.
2022 };
2023 */
2024
2025 static bool objc_category = false;
2026 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002027 Result += "\nstruct _objc_category {\n";
2028 Result += "\tchar *category_name;\n";
2029 Result += "\tchar *class_name;\n";
2030 Result += "\tstruct _objc_method_list *instance_methods;\n";
2031 Result += "\tstruct _objc_method_list *class_methods;\n";
2032 Result += "\tstruct _objc_protocol_list *protocols;\n";
2033 Result += "\tunsigned int size;\n";
2034 Result += "\tstruct _objc_property_list *instance_properties;\n";
2035 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002036 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002037 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002038 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2039 Result += FullCategoryName;
2040 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2041 Result += IDecl->getName();
2042 Result += "\"\n\t, \"";
2043 Result += ClassDecl->getName();
2044 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002045
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002046 if (IDecl->getNumInstanceMethods() > 0) {
2047 Result += "\t, (struct _objc_method_list *)"
2048 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2049 Result += FullCategoryName;
2050 Result += "\n";
2051 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002052 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002053 Result += "\t, 0\n";
2054 if (IDecl->getNumClassMethods() > 0) {
2055 Result += "\t, (struct _objc_method_list *)"
2056 "&_OBJC_CATEGORY_CLASS_METHODS_";
2057 Result += FullCategoryName;
2058 Result += "\n";
2059 }
2060 else
2061 Result += "\t, 0\n";
2062
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002063 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002064 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2065 Result += FullCategoryName;
2066 Result += "\n";
2067 }
2068 else
2069 Result += "\t, 0\n";
2070 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002071}
2072
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002073/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2074/// ivar offset.
2075void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2076 ObjcIvarDecl *ivar,
2077 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002078 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002079 Result += IDecl->getName();
2080 Result += ", ";
2081 Result += ivar->getName();
2082 Result += ")";
2083}
2084
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002085//===----------------------------------------------------------------------===//
2086// Meta Data Emission
2087//===----------------------------------------------------------------------===//
2088
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002089void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2090 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002091 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2092
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002093 // Explictly declared @interface's are already synthesized.
2094 if (CDecl->ImplicitInterfaceDecl()) {
2095 // FIXME: Implementation of a class with no @interface (legacy) doese not
2096 // produce correct synthesis as yet.
2097 SynthesizeObjcInternalStruct(CDecl, Result);
2098 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002099
Chris Lattnerbe6df082007-12-12 07:56:42 +00002100 // Build _objc_ivar_list metadata for classes ivars if needed
2101 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2102 ? IDecl->getImplDeclNumIvars()
2103 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002104 if (NumIvars > 0) {
2105 static bool objc_ivar = false;
2106 if (!objc_ivar) {
2107 /* struct _objc_ivar {
2108 char *ivar_name;
2109 char *ivar_type;
2110 int ivar_offset;
2111 };
2112 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002113 Result += "\nstruct _objc_ivar {\n";
2114 Result += "\tchar *ivar_name;\n";
2115 Result += "\tchar *ivar_type;\n";
2116 Result += "\tint ivar_offset;\n";
2117 Result += "};\n";
2118
2119 /* struct _objc_ivar_list {
2120 int ivar_count;
2121 struct _objc_ivar ivar_list[];
2122 };
2123 */
2124 Result += "\nstruct _objc_ivar_list {\n";
2125 Result += "\tint ivar_count;\n";
2126 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002127 objc_ivar = true;
2128 }
2129
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002130 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2131 Result += IDecl->getName();
2132 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2133 "{\n\t";
2134 Result += utostr(NumIvars);
2135 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002136
2137 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2138 if (IDecl->getImplDeclNumIvars() > 0) {
2139 IVI = IDecl->ivar_begin();
2140 IVE = IDecl->ivar_end();
2141 } else {
2142 IVI = CDecl->ivar_begin();
2143 IVE = CDecl->ivar_end();
2144 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002145 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002146 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002147 Result += "\", \"";
2148 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002149 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002150 Result += StrEncoding;
2151 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002152 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002153 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002154 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002155 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002156 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002157 Result += "\", \"";
2158 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002159 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002160 Result += StrEncoding;
2161 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002162 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002163 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002164 }
2165
2166 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002167 }
2168
2169 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002170 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2171 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002172
2173 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002174 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2175 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002176
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002177 // Protocols referenced in class declaration?
2178 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2179 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002180 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002181
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002182
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002183 // Declaration of class/meta-class metadata
2184 /* struct _objc_class {
2185 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002186 const char *super_class_name;
2187 char *name;
2188 long version;
2189 long info;
2190 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002191 struct _objc_ivar_list *ivars;
2192 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002193 struct objc_cache *cache;
2194 struct objc_protocol_list *protocols;
2195 const char *ivar_layout;
2196 struct _objc_class_ext *ext;
2197 };
2198 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002199 static bool objc_class = false;
2200 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002201 Result += "\nstruct _objc_class {\n";
2202 Result += "\tstruct _objc_class *isa;\n";
2203 Result += "\tconst char *super_class_name;\n";
2204 Result += "\tchar *name;\n";
2205 Result += "\tlong version;\n";
2206 Result += "\tlong info;\n";
2207 Result += "\tlong instance_size;\n";
2208 Result += "\tstruct _objc_ivar_list *ivars;\n";
2209 Result += "\tstruct _objc_method_list *methods;\n";
2210 Result += "\tstruct objc_cache *cache;\n";
2211 Result += "\tstruct _objc_protocol_list *protocols;\n";
2212 Result += "\tconst char *ivar_layout;\n";
2213 Result += "\tstruct _objc_class_ext *ext;\n";
2214 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002215 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002216 }
2217
2218 // Meta-class metadata generation.
2219 ObjcInterfaceDecl *RootClass = 0;
2220 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2221 while (SuperClass) {
2222 RootClass = SuperClass;
2223 SuperClass = SuperClass->getSuperClass();
2224 }
2225 SuperClass = CDecl->getSuperClass();
2226
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002227 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2228 Result += CDecl->getName();
2229 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2230 "{\n\t(struct _objc_class *)\"";
2231 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2232 Result += "\"";
2233
2234 if (SuperClass) {
2235 Result += ", \"";
2236 Result += SuperClass->getName();
2237 Result += "\", \"";
2238 Result += CDecl->getName();
2239 Result += "\"";
2240 }
2241 else {
2242 Result += ", 0, \"";
2243 Result += CDecl->getName();
2244 Result += "\"";
2245 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002246 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002247 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002248 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002249 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002250 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002251 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002252 Result += "\n";
2253 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002254 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002255 Result += ", 0\n";
2256 if (CDecl->getNumIntfRefProtocols() > 0) {
2257 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2258 Result += CDecl->getName();
2259 Result += ",0,0\n";
2260 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002261 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002262 Result += "\t,0,0,0,0\n";
2263 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002264
2265 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002266 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2267 Result += CDecl->getName();
2268 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2269 "{\n\t&_OBJC_METACLASS_";
2270 Result += CDecl->getName();
2271 if (SuperClass) {
2272 Result += ", \"";
2273 Result += SuperClass->getName();
2274 Result += "\", \"";
2275 Result += CDecl->getName();
2276 Result += "\"";
2277 }
2278 else {
2279 Result += ", 0, \"";
2280 Result += CDecl->getName();
2281 Result += "\"";
2282 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002283 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002284 Result += ", 0,1";
2285 if (!ObjcSynthesizedStructs.count(CDecl))
2286 Result += ",0";
2287 else {
2288 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002289 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002290 Result += CDecl->getName();
2291 Result += ")";
2292 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002293 if (NumIvars > 0) {
2294 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2295 Result += CDecl->getName();
2296 Result += "\n\t";
2297 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002298 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002299 Result += ",0";
2300 if (IDecl->getNumInstanceMethods() > 0) {
2301 Result += ", &_OBJC_INSTANCE_METHODS_";
2302 Result += CDecl->getName();
2303 Result += ", 0\n\t";
2304 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002305 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002306 Result += ",0,0";
2307 if (CDecl->getNumIntfRefProtocols() > 0) {
2308 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2309 Result += CDecl->getName();
2310 Result += ", 0,0\n";
2311 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002312 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002313 Result += ",0,0,0\n";
2314 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002315}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002316
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002317/// RewriteImplementations - This routine rewrites all method implementations
2318/// and emits meta-data.
2319
2320void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002321 int ClsDefCount = ClassImplementation.size();
2322 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002323
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002324 if (ClsDefCount == 0 && CatDefCount == 0)
2325 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002326 // Rewrite implemented methods
2327 for (int i = 0; i < ClsDefCount; i++)
2328 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002329
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002330 for (int i = 0; i < CatDefCount; i++)
2331 RewriteImplementationDecl(CategoryImplementation[i]);
2332
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002333 // This is needed for use of offsetof
2334 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002335
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002336 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002337 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002338 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002339
2340 // For each implemented category, write out all its meta data.
2341 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002342 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002343
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002344 // Write objc_symtab metadata
2345 /*
2346 struct _objc_symtab
2347 {
2348 long sel_ref_cnt;
2349 SEL *refs;
2350 short cls_def_cnt;
2351 short cat_def_cnt;
2352 void *defs[cls_def_cnt + cat_def_cnt];
2353 };
2354 */
2355
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002356 Result += "\nstruct _objc_symtab {\n";
2357 Result += "\tlong sel_ref_cnt;\n";
2358 Result += "\tSEL *refs;\n";
2359 Result += "\tshort cls_def_cnt;\n";
2360 Result += "\tshort cat_def_cnt;\n";
2361 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2362 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002363
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002364 Result += "static struct _objc_symtab "
2365 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2366 Result += "\t0, 0, " + utostr(ClsDefCount)
2367 + ", " + utostr(CatDefCount) + "\n";
2368 for (int i = 0; i < ClsDefCount; i++) {
2369 Result += "\t,&_OBJC_CLASS_";
2370 Result += ClassImplementation[i]->getName();
2371 Result += "\n";
2372 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002373
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002374 for (int i = 0; i < CatDefCount; i++) {
2375 Result += "\t,&_OBJC_CATEGORY_";
2376 Result += CategoryImplementation[i]->getClassInterface()->getName();
2377 Result += "_";
2378 Result += CategoryImplementation[i]->getName();
2379 Result += "\n";
2380 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002381
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002382 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002383
2384 // Write objc_module metadata
2385
2386 /*
2387 struct _objc_module {
2388 long version;
2389 long size;
2390 const char *name;
2391 struct _objc_symtab *symtab;
2392 }
2393 */
2394
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 Result += "\nstruct _objc_module {\n";
2396 Result += "\tlong version;\n";
2397 Result += "\tlong size;\n";
2398 Result += "\tconst char *name;\n";
2399 Result += "\tstruct _objc_symtab *symtab;\n";
2400 Result += "};\n\n";
2401 Result += "static struct _objc_module "
2402 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002403 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2404 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002405 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002406
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002407}
Chris Lattner311ff022007-10-16 22:36:42 +00002408