blob: 2a189ad85b34c682d9c966167ab204ef673e1571 [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;
67 SM = &Context->SourceMgr;
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
Chris Lattner01c57482007-10-17 22:35:30 +000090 Rewrite.setSourceMgr(Context->SourceMgr);
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);
Steve Naroffd5255f52007-11-01 13:24:47 +0000150 void RewriteObjcQualifiedInterfaceTypes(
151 const FunctionTypeProto *proto, FunctionDecl *FD);
152 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000153 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
154 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000155
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000157 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000158 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000159 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000160 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000161 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000162 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000163 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000164 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
165 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
166 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000167 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000170 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000171 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000172 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000173 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000174 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000175 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000176 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000177 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000178 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000179 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000180
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000182 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
183 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000184
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000185 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
186 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000187
Steve Naroff0416fb92007-11-11 17:19:15 +0000188 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000189 int NumMethods,
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)) {
277 if (VD->getInit())
278 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
279 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000280 // Nothing yet.
281}
282
283RewriteTest::~RewriteTest() {
284 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000285
286 // Rewrite tabs if we care.
287 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000288
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000289 // Rewrite Objective-c meta data*
290 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000291 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
294 // we are done.
295 if (const RewriteBuffer *RewriteBuf =
296 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000297 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000298 std::string S(RewriteBuf->begin(), RewriteBuf->end());
299 printf("%s\n", S.c_str());
300 } else {
301 printf("No changes\n");
302 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000303 // Emit metadata.
304 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000305}
306
Chris Lattnerf04da132007-10-24 17:06:59 +0000307//===----------------------------------------------------------------------===//
308// Syntactic (non-AST) Rewriting Code
309//===----------------------------------------------------------------------===//
310
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000311void RewriteTest::RewriteInclude(SourceLocation Loc) {
312 // Rip up the #include stack to the main file.
313 SourceLocation IncLoc = Loc, NextLoc = Loc;
314 do {
315 IncLoc = Loc;
316 Loc = SM->getLogicalLoc(NextLoc);
317 NextLoc = SM->getIncludeLoc(Loc);
318 } while (!NextLoc.isInvalid());
319
320 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
321 // IncLoc indicates the header that was included if it is useful.
322 IncLoc = SM->getLogicalLoc(IncLoc);
323 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
324 Loc == LastIncLoc)
325 return;
326 LastIncLoc = Loc;
327
328 unsigned IncCol = SM->getColumnNumber(Loc);
329 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
330
331 // Replace the #import with #include.
332 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
333}
334
Chris Lattnerf04da132007-10-24 17:06:59 +0000335void RewriteTest::RewriteTabs() {
336 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
337 const char *MainBufStart = MainBuf.first;
338 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000339
Chris Lattnerf04da132007-10-24 17:06:59 +0000340 // Loop over the whole file, looking for tabs.
341 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
342 if (*BufPtr != '\t')
343 continue;
344
345 // Okay, we found a tab. This tab will turn into at least one character,
346 // but it depends on which 'virtual column' it is in. Compute that now.
347 unsigned VCol = 0;
348 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
349 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
350 ++VCol;
351
352 // Okay, now that we know the virtual column, we know how many spaces to
353 // insert. We assume 8-character tab-stops.
354 unsigned Spaces = 8-(VCol & 7);
355
356 // Get the location of the tab.
357 SourceLocation TabLoc =
358 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
359
360 // Rewrite the single tab character into a sequence of spaces.
361 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
362 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000363}
364
365
Chris Lattnerf04da132007-10-24 17:06:59 +0000366void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
367 int numDecls = ClassDecl->getNumForwardDecls();
368 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
369
370 // Get the start location and compute the semi location.
371 SourceLocation startLoc = ClassDecl->getLocation();
372 const char *startBuf = SM->getCharacterData(startLoc);
373 const char *semiPtr = strchr(startBuf, ';');
374
375 // Translate to typedef's that forward reference structs with the same name
376 // as the class. As a convenience, we include the original declaration
377 // as a comment.
378 std::string typedefString;
379 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000380 typedefString.append(startBuf, semiPtr-startBuf+1);
381 typedefString += "\n";
382 for (int i = 0; i < numDecls; i++) {
383 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000384 typedefString += "#ifndef _REWRITER_typedef_";
385 typedefString += ForwardDecl->getName();
386 typedefString += "\n";
387 typedefString += "#define _REWRITER_typedef_";
388 typedefString += ForwardDecl->getName();
389 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000390 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000391 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000392 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000393 }
394
395 // Replace the @class with typedefs corresponding to the classes.
396 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
397 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000398}
399
Steve Naroff71c0a952007-11-13 23:01:27 +0000400void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000401 for (int i = 0; i < nMethods; i++) {
402 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000405
Steve Naroff1d098f62007-11-14 14:34:23 +0000406 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
407 Rewrite.InsertText(LocStart, "/* ", 3);
408 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
409 } else {
410 Rewrite.InsertText(LocStart, "// ", 3);
411 }
Steve Naroff423cb562007-10-30 13:30:57 +0000412 }
413}
414
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000415void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
416{
417 for (int i = 0; i < nProperties; i++) {
418 ObjcPropertyDecl *Property = Properties[i];
419 SourceLocation Loc = Property->getLocation();
420
421 Rewrite.ReplaceText(Loc, 0, "// ", 3);
422
423 // FIXME: handle properties that are declared across multiple lines.
424 }
425}
426
Steve Naroff423cb562007-10-30 13:30:57 +0000427void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
428 SourceLocation LocStart = CatDecl->getLocStart();
429
430 // FIXME: handle category headers that are declared across multiple lines.
431 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
432
Steve Naroff71c0a952007-11-13 23:01:27 +0000433 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
434 CatDecl->getInstanceMethods());
435 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
436 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000437 // Lastly, comment out the @end.
438 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
439}
440
Steve Naroff752d6ef2007-10-30 16:42:30 +0000441void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000442 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443
Steve Naroff752d6ef2007-10-30 16:42:30 +0000444 SourceLocation LocStart = PDecl->getLocStart();
445
446 // FIXME: handle protocol headers that are declared across multiple lines.
447 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
448
Steve Naroff71c0a952007-11-13 23:01:27 +0000449 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
450 PDecl->getInstanceMethods());
451 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
452 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000453 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000454 SourceLocation LocEnd = PDecl->getAtEndLoc();
455 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000456
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000457 // Must comment out @optional/@required
458 const char *startBuf = SM->getCharacterData(LocStart);
459 const char *endBuf = SM->getCharacterData(LocEnd);
460 for (const char *p = startBuf; p < endBuf; p++) {
461 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
462 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000463 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000464 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
465 CommentedOptional.c_str(), CommentedOptional.size());
466
467 }
468 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
469 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000470 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000471 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
472 CommentedRequired.c_str(), CommentedRequired.size());
473
474 }
475 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000476}
477
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000478void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
479 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000480 if (LocStart.isInvalid())
481 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000482 // FIXME: handle forward protocol that are declared across multiple lines.
483 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
484}
485
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000486void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
487 std::string &ResultStr) {
488 ResultStr += "\nstatic ";
489 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000490 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000491
492 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000493 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000495 if (OMD->isInstance())
496 NameStr += "_I_";
497 else
498 NameStr += "_C_";
499
500 NameStr += OMD->getClassInterface()->getName();
501 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000502
503 NamedDecl *MethodContext = OMD->getMethodContext();
504 if (ObjcCategoryImplDecl *CID =
505 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000506 NameStr += CID->getName();
507 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000508 }
509 // Append selector names, replacing ':' with '_'
510 const char *selName = OMD->getSelector().getName().c_str();
511 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000512 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000513 else {
514 std::string selString = OMD->getSelector().getName();
515 int len = selString.size();
516 for (int i = 0; i < len; i++)
517 if (selString[i] == ':')
518 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000519 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000521 // Remember this name for metadata emission
522 MethodInternalNames[OMD] = NameStr;
523 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524
525 // Rewrite arguments
526 ResultStr += "(";
527
528 // invisible arguments
529 if (OMD->isInstance()) {
530 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
531 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000532 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
533 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000534 ResultStr += selfTy.getAsString();
535 }
536 else
537 ResultStr += Context->getObjcIdType().getAsString();
538
539 ResultStr += " self, ";
540 ResultStr += Context->getObjcSelType().getAsString();
541 ResultStr += " _cmd";
542
543 // Method arguments.
544 for (int i = 0; i < OMD->getNumParams(); i++) {
545 ParmVarDecl *PDecl = OMD->getParamDecl(i);
546 ResultStr += ", ";
547 ResultStr += PDecl->getType().getAsString();
548 ResultStr += " ";
549 ResultStr += PDecl->getName();
550 }
551 ResultStr += ")";
552
553}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000554void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
555 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
556 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000558 if (IMD)
559 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
560 else
561 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000562
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000563 int numMethods = IMD ? IMD->getNumInstanceMethods()
564 : CID->getNumInstanceMethods();
565
566 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 ObjcMethodDecl *OMD;
569 if (IMD)
570 OMD = IMD->getInstanceMethods()[i];
571 else
572 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000573 RewriteObjcMethodDecl(OMD, ResultStr);
574 SourceLocation LocStart = OMD->getLocStart();
575 SourceLocation LocEnd = OMD->getBody()->getLocStart();
576
577 const char *startBuf = SM->getCharacterData(LocStart);
578 const char *endBuf = SM->getCharacterData(LocEnd);
579 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
580 ResultStr.c_str(), ResultStr.size());
581 }
582
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000583 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
584 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000586 ObjcMethodDecl *OMD;
587 if (IMD)
588 OMD = IMD->getClassMethods()[i];
589 else
590 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000591 RewriteObjcMethodDecl(OMD, ResultStr);
592 SourceLocation LocStart = OMD->getLocStart();
593 SourceLocation LocEnd = OMD->getBody()->getLocStart();
594
595 const char *startBuf = SM->getCharacterData(LocStart);
596 const char *endBuf = SM->getCharacterData(LocEnd);
597 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
598 ResultStr.c_str(), ResultStr.size());
599 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000600 if (IMD)
601 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
602 else
603 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000604}
605
Steve Naroffbef11852007-10-26 20:53:56 +0000606void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000607 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000608 if (!ObjcForwardDecls.count(ClassDecl)) {
609 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000610 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000611 ResultStr += ClassDecl->getName();
612 ResultStr += "\n";
613 ResultStr += "#define _REWRITER_typedef_";
614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000616 ResultStr += "typedef struct ";
617 ResultStr += ClassDecl->getName();
618 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000619 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000620 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000621
622 // Mark this typedef as having been generated.
623 ObjcForwardDecls.insert(ClassDecl);
624 }
Steve Narofff908a872007-10-30 02:23:23 +0000625 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
626
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000627 RewriteProperties(ClassDecl->getNumPropertyDecl(),
628 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000629 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
630 ClassDecl->getInstanceMethods());
631 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
632 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000633
Steve Naroff2feac5e2007-10-30 03:43:13 +0000634 // Lastly, comment out the @end.
635 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000636}
637
Steve Naroff7e3411b2007-11-15 02:58:25 +0000638Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
639 ObjcIvarDecl *D = IV->getDecl();
640 if (IV->isFreeIvar()) {
641 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
642 IV->getLocation());
643 Rewrite.ReplaceStmt(IV, Replacement);
644 delete IV;
645 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000646 } else {
647 if (CurMethodDecl) {
648 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
649 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
650 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
651 IdentifierInfo *II = intT->getDecl()->getIdentifier();
652 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
653 II, 0);
654 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
655
656 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
657 // Don't forget the parens to enforce the proper binding.
658 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
659 Rewrite.ReplaceStmt(IV->getBase(), PE);
660 delete IV->getBase();
661 return PE;
662 }
663 }
664 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000665 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000666 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000667}
668
Chris Lattnerf04da132007-10-24 17:06:59 +0000669//===----------------------------------------------------------------------===//
670// Function Body / Expression rewriting
671//===----------------------------------------------------------------------===//
672
Steve Narofff3473a72007-11-09 15:20:18 +0000673Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000674 // Otherwise, just rewrite all children.
675 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
676 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000677 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000678 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000679 if (newStmt)
680 *CI = newStmt;
681 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000682
683 // Handle specific things.
684 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
685 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000686
687 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
688 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000689
690 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
691 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000692
693 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
694 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000695
Steve Naroff934f2762007-10-24 22:48:43 +0000696 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
697 // Before we rewrite it, put the original message expression in a comment.
698 SourceLocation startLoc = MessExpr->getLocStart();
699 SourceLocation endLoc = MessExpr->getLocEnd();
700
701 const char *startBuf = SM->getCharacterData(startLoc);
702 const char *endBuf = SM->getCharacterData(endLoc);
703
704 std::string messString;
705 messString += "// ";
706 messString.append(startBuf, endBuf-startBuf+1);
707 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000708
Steve Naroff934f2762007-10-24 22:48:43 +0000709 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
710 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
711 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000712 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000713 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000714 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000715
716 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
717 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000718
719 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
720 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000721
722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
723 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000724#if 0
725 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
726 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
727 // Get the new text.
728 std::ostringstream Buf;
729 Replacement->printPretty(Buf);
730 const std::string &Str = Buf.str();
731
732 printf("CAST = %s\n", &Str[0]);
733 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
734 delete S;
735 return Replacement;
736 }
737#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000738 // Return this stmt unmodified.
739 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000740}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000741
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000742Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000743 // Get the start location and compute the semi location.
744 SourceLocation startLoc = S->getLocStart();
745 const char *startBuf = SM->getCharacterData(startLoc);
746
747 assert((*startBuf == '@') && "bogus @try location");
748
749 std::string buf;
750 // declare a new scope with two variables, _stack and _rethrow.
751 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
752 buf += "int buf[18/*32-bit i386*/];\n";
753 buf += "char *pointers[4];} _stack;\n";
754 buf += "id volatile _rethrow = 0;\n";
755 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000756 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000757
758 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
759
760 startLoc = S->getTryBody()->getLocEnd();
761 startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '}') && "bogus @try block");
764
765 SourceLocation lastCurlyLoc = startLoc;
766
767 startLoc = startLoc.getFileLocWithOffset(1);
768 buf = " /* @catch begin */ else {\n";
769 buf += " id _caught = objc_exception_extract(&_stack);\n";
770 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000771 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000772 buf += " _rethrow = objc_exception_extract(&_stack);\n";
773 buf += " else { /* @catch continue */";
774
Chris Lattner28d1fe82007-11-08 04:41:51 +0000775 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000776
777 bool sawIdTypedCatch = false;
778 Stmt *lastCatchBody = 0;
779 ObjcAtCatchStmt *catchList = S->getCatchStmts();
780 while (catchList) {
781 Stmt *catchStmt = catchList->getCatchParamStmt();
782
783 if (catchList == S->getCatchStmts())
784 buf = "if ("; // we are generating code for the first catch clause
785 else
786 buf = "else if (";
787 startLoc = catchList->getLocStart();
788 startBuf = SM->getCharacterData(startLoc);
789
790 assert((*startBuf == '@') && "bogus @catch location");
791
792 const char *lParenLoc = strchr(startBuf, '(');
793
794 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
795 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
796 if (t == Context->getObjcIdType()) {
797 buf += "1) { ";
798 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
799 buf.c_str(), buf.size());
800 sawIdTypedCatch = true;
801 } else if (const PointerType *pType = t->getAsPointerType()) {
802 ObjcInterfaceType *cls; // Should be a pointer to a class.
803
804 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
805 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000806 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000807 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000808 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000809 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
810 buf.c_str(), buf.size());
811 }
812 }
813 // Now rewrite the body...
814 lastCatchBody = catchList->getCatchBody();
815 SourceLocation rParenLoc = catchList->getRParenLoc();
816 SourceLocation bodyLoc = lastCatchBody->getLocStart();
817 const char *bodyBuf = SM->getCharacterData(bodyLoc);
818 const char *rParenBuf = SM->getCharacterData(rParenLoc);
819 assert((*rParenBuf == ')') && "bogus @catch paren location");
820 assert((*bodyBuf == '{') && "bogus @catch body location");
821
822 buf = " = _caught;";
823 // Here we replace ") {" with "= _caught;" (which initializes and
824 // declares the @catch parameter).
825 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
826 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000827 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000828 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000829 }
Steve Naroff75730982007-11-07 04:08:17 +0000830 catchList = catchList->getNextCatchStmt();
831 }
832 // Complete the catch list...
833 if (lastCatchBody) {
834 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
835 const char *bodyBuf = SM->getCharacterData(bodyLoc);
836 assert((*bodyBuf == '}') && "bogus @catch body location");
837 bodyLoc = bodyLoc.getFileLocWithOffset(1);
838 buf = " } } /* @catch end */\n";
839
Chris Lattner28d1fe82007-11-08 04:41:51 +0000840 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000841
842 // Set lastCurlyLoc
843 lastCurlyLoc = lastCatchBody->getLocEnd();
844 }
845 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
846 startLoc = finalStmt->getLocStart();
847 startBuf = SM->getCharacterData(startLoc);
848 assert((*startBuf == '@') && "bogus @finally start");
849
850 buf = "/* @finally */";
851 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
852
853 Stmt *body = finalStmt->getFinallyBody();
854 SourceLocation startLoc = body->getLocStart();
855 SourceLocation endLoc = body->getLocEnd();
856 const char *startBuf = SM->getCharacterData(startLoc);
857 const char *endBuf = SM->getCharacterData(endLoc);
858 assert((*startBuf == '{') && "bogus @finally body location");
859 assert((*endBuf == '}') && "bogus @finally body location");
860
861 startLoc = startLoc.getFileLocWithOffset(1);
862 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000863 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000864 endLoc = endLoc.getFileLocWithOffset(-1);
865 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000866 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000867
868 // Set lastCurlyLoc
869 lastCurlyLoc = body->getLocEnd();
870 }
871 // Now emit the final closing curly brace...
872 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
873 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000874 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000875 return 0;
876}
877
878Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
879 return 0;
880}
881
882Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
883 return 0;
884}
885
Steve Naroff2bd03922007-11-07 15:32:26 +0000886// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
887// the throw expression is typically a message expression that's already
888// been rewritten! (which implies the SourceLocation's are invalid).
889Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = S->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893
894 assert((*startBuf == '@') && "bogus @throw location");
895
896 std::string buf;
897 /* void objc_exception_throw(id) __attribute__((noreturn)); */
898 buf = "objc_exception_throw(";
899 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
900 const char *semiBuf = strchr(startBuf, ';');
901 assert((*semiBuf == ';') && "@throw: can't find ';'");
902 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
903 buf = ");";
904 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
905 return 0;
906}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000907
Chris Lattnere64b7772007-10-24 16:57:36 +0000908Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000909 // Create a new string expression.
910 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000911 std::string StrEncoding;
912 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
913 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
914 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000915 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000916 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
917 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000918 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
919 "rewriter could not replace sub-expression due to macros");
920 SourceRange Range = Exp->getSourceRange();
921 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
922 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000923 return Exp;
924 }
925
Chris Lattner07506182007-11-30 22:53:43 +0000926 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000927 delete Exp;
928 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000929}
930
Steve Naroffb42f8412007-11-05 14:50:49 +0000931Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
932 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
933 // Create a call to sel_registerName("selName").
934 llvm::SmallVector<Expr*, 8> SelExprs;
935 QualType argType = Context->getPointerType(Context->CharTy);
936 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
937 Exp->getSelector().getName().size(),
938 false, argType, SourceLocation(),
939 SourceLocation()));
940 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
941 &SelExprs[0], SelExprs.size());
942 Rewrite.ReplaceStmt(Exp, SelExp);
943 delete Exp;
944 return SelExp;
945}
946
Steve Naroff934f2762007-10-24 22:48:43 +0000947CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
948 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000949 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000950 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000951
952 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000953 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000954
955 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000956 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000957 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
958
959 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000960
Steve Naroff934f2762007-10-24 22:48:43 +0000961 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
962}
963
Steve Naroffd5255f52007-11-01 13:24:47 +0000964static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
965 const char *&startRef, const char *&endRef) {
966 while (startBuf < endBuf) {
967 if (*startBuf == '<')
968 startRef = startBuf; // mark the start.
969 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000970 if (startRef && *startRef == '<') {
971 endRef = startBuf; // mark the end.
972 return true;
973 }
974 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000975 }
976 startBuf++;
977 }
978 return false;
979}
980
981bool RewriteTest::needToScanForQualifiers(QualType T) {
982 // FIXME: we don't currently represent "id <Protocol>" in the type system.
983 if (T == Context->getObjcIdType())
984 return true;
985
986 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000987 Type *pointeeType = pType->getPointeeType().getTypePtr();
988 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
989 return true; // we have "Class <Protocol> *".
990 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000991 return false;
992}
993
994void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
995 const FunctionTypeProto *proto, FunctionDecl *FD) {
996
997 if (needToScanForQualifiers(proto->getResultType())) {
998 // Since types are unique, we need to scan the buffer.
999 SourceLocation Loc = FD->getLocation();
1000
1001 const char *endBuf = SM->getCharacterData(Loc);
1002 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001003 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001004 startBuf--; // scan backward (from the decl location) for return type.
1005 const char *startRef = 0, *endRef = 0;
1006 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1007 // Get the locations of the startRef, endRef.
1008 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1009 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1010 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001011 Rewrite.InsertText(LessLoc, "/*", 2);
1012 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001013 }
1014 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001015 // Now check arguments.
1016 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1017 if (needToScanForQualifiers(proto->getArgType(i))) {
1018 // Since types are unique, we need to scan the buffer.
1019 SourceLocation Loc = FD->getLocation();
1020
1021 const char *startBuf = SM->getCharacterData(Loc);
1022 const char *endBuf = startBuf;
1023 while (*endBuf != ';')
1024 endBuf++; // scan forward (from the decl location) for argument types.
1025 const char *startRef = 0, *endRef = 0;
1026 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1027 // Get the locations of the startRef, endRef.
1028 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1029 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1030 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001031 Rewrite.InsertText(LessLoc, "/*", 2);
1032 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001033 }
1034 }
1035 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001036}
1037
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001038// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1039void RewriteTest::SynthSelGetUidFunctionDecl() {
1040 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1041 llvm::SmallVector<QualType, 16> ArgTys;
1042 ArgTys.push_back(Context->getPointerType(
1043 Context->CharTy.getQualifiedType(QualType::Const)));
1044 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1045 &ArgTys[0], ArgTys.size(),
1046 false /*isVariadic*/);
1047 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1048 SelGetUidIdent, getFuncType,
1049 FunctionDecl::Extern, false, 0);
1050}
1051
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001052// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1053void RewriteTest::SynthGetProtocolFunctionDecl() {
1054 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1055 llvm::SmallVector<QualType, 16> ArgTys;
1056 ArgTys.push_back(Context->getPointerType(
1057 Context->CharTy.getQualifiedType(QualType::Const)));
1058 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1059 &ArgTys[0], ArgTys.size(),
1060 false /*isVariadic*/);
1061 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1062 SelGetProtoIdent, getFuncType,
1063 FunctionDecl::Extern, false, 0);
1064}
1065
Steve Naroff09b266e2007-10-30 23:14:51 +00001066void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1067 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001068 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001069 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001070 return;
1071 }
1072 // Check for ObjC 'id' and class types that have been adorned with protocol
1073 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1074 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1075 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +00001076 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1077 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001078}
1079
1080// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1081void RewriteTest::SynthMsgSendFunctionDecl() {
1082 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1083 llvm::SmallVector<QualType, 16> ArgTys;
1084 QualType argT = Context->getObjcIdType();
1085 assert(!argT.isNull() && "Can't find 'id' type");
1086 ArgTys.push_back(argT);
1087 argT = Context->getObjcSelType();
1088 assert(!argT.isNull() && "Can't find 'SEL' type");
1089 ArgTys.push_back(argT);
1090 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1091 &ArgTys[0], ArgTys.size(),
1092 true /*isVariadic*/);
1093 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1094 msgSendIdent, msgSendType,
1095 FunctionDecl::Extern, false, 0);
1096}
1097
Steve Naroff874e2322007-11-15 10:28:18 +00001098// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1099void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1100 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1101 llvm::SmallVector<QualType, 16> ArgTys;
1102 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1103 &Context->Idents.get("objc_super"), 0);
1104 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1105 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1106 ArgTys.push_back(argT);
1107 argT = Context->getObjcSelType();
1108 assert(!argT.isNull() && "Can't find 'SEL' type");
1109 ArgTys.push_back(argT);
1110 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1111 &ArgTys[0], ArgTys.size(),
1112 true /*isVariadic*/);
1113 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1114 msgSendIdent, msgSendType,
1115 FunctionDecl::Extern, false, 0);
1116}
1117
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001118// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1119void RewriteTest::SynthMsgSendStretFunctionDecl() {
1120 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1121 llvm::SmallVector<QualType, 16> ArgTys;
1122 QualType argT = Context->getObjcIdType();
1123 assert(!argT.isNull() && "Can't find 'id' type");
1124 ArgTys.push_back(argT);
1125 argT = Context->getObjcSelType();
1126 assert(!argT.isNull() && "Can't find 'SEL' type");
1127 ArgTys.push_back(argT);
1128 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1129 &ArgTys[0], ArgTys.size(),
1130 true /*isVariadic*/);
1131 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1132 msgSendIdent, msgSendType,
1133 FunctionDecl::Extern, false, 0);
1134}
1135
1136// SynthMsgSendSuperStretFunctionDecl -
1137// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1138void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1139 IdentifierInfo *msgSendIdent =
1140 &Context->Idents.get("objc_msgSendSuper_stret");
1141 llvm::SmallVector<QualType, 16> ArgTys;
1142 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1143 &Context->Idents.get("objc_super"), 0);
1144 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1145 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1146 ArgTys.push_back(argT);
1147 argT = Context->getObjcSelType();
1148 assert(!argT.isNull() && "Can't find 'SEL' type");
1149 ArgTys.push_back(argT);
1150 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1151 &ArgTys[0], ArgTys.size(),
1152 true /*isVariadic*/);
1153 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1154 msgSendIdent, msgSendType,
1155 FunctionDecl::Extern, false, 0);
1156}
1157
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001158// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1159void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1160 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1161 llvm::SmallVector<QualType, 16> ArgTys;
1162 QualType argT = Context->getObjcIdType();
1163 assert(!argT.isNull() && "Can't find 'id' type");
1164 ArgTys.push_back(argT);
1165 argT = Context->getObjcSelType();
1166 assert(!argT.isNull() && "Can't find 'SEL' type");
1167 ArgTys.push_back(argT);
1168 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1169 &ArgTys[0], ArgTys.size(),
1170 true /*isVariadic*/);
1171 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1172 msgSendIdent, msgSendType,
1173 FunctionDecl::Extern, false, 0);
1174}
1175
Steve Naroff09b266e2007-10-30 23:14:51 +00001176// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1177void RewriteTest::SynthGetClassFunctionDecl() {
1178 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1179 llvm::SmallVector<QualType, 16> ArgTys;
1180 ArgTys.push_back(Context->getPointerType(
1181 Context->CharTy.getQualifiedType(QualType::Const)));
1182 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1183 &ArgTys[0], ArgTys.size(),
1184 false /*isVariadic*/);
1185 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1186 getClassIdent, getClassType,
1187 FunctionDecl::Extern, false, 0);
1188}
1189
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001190// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1191void RewriteTest::SynthGetMetaClassFunctionDecl() {
1192 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1193 llvm::SmallVector<QualType, 16> ArgTys;
1194 ArgTys.push_back(Context->getPointerType(
1195 Context->CharTy.getQualifiedType(QualType::Const)));
1196 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1197 &ArgTys[0], ArgTys.size(),
1198 false /*isVariadic*/);
1199 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1200 getClassIdent, getClassType,
1201 FunctionDecl::Extern, false, 0);
1202}
1203
Steve Naroff96984642007-11-08 14:30:50 +00001204// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1205void RewriteTest::SynthCFStringFunctionDecl() {
1206 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1207 llvm::SmallVector<QualType, 16> ArgTys;
1208 ArgTys.push_back(Context->getPointerType(
1209 Context->CharTy.getQualifiedType(QualType::Const)));
1210 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1211 &ArgTys[0], ArgTys.size(),
1212 false /*isVariadic*/);
1213 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1214 getClassIdent, getClassType,
1215 FunctionDecl::Extern, false, 0);
1216}
1217
Steve Naroffbeaf2992007-11-03 11:27:19 +00001218Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001219#if 1
1220 // This rewrite is specific to GCC, which has builtin support for CFString.
1221 if (!CFStringFunctionDecl)
1222 SynthCFStringFunctionDecl();
1223 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1224 llvm::SmallVector<Expr*, 8> StrExpr;
1225 StrExpr.push_back(Exp->getString());
1226 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1227 &StrExpr[0], StrExpr.size());
1228 // cast to NSConstantString *
1229 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1230 Rewrite.ReplaceStmt(Exp, cast);
1231 delete Exp;
1232 return cast;
1233#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001234 assert(ConstantStringClassReference && "Can't find constant string reference");
1235 llvm::SmallVector<Expr*, 4> InitExprs;
1236
1237 // Synthesize "(Class)&_NSConstantStringClassReference"
1238 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1239 ConstantStringClassReference->getType(),
1240 SourceLocation());
1241 QualType expType = Context->getPointerType(ClsRef->getType());
1242 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1243 expType, SourceLocation());
1244 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1245 SourceLocation());
1246 InitExprs.push_back(cast); // set the 'isa'.
1247 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1248 unsigned IntSize = static_cast<unsigned>(
1249 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1250 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1251 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1252 Exp->getLocStart());
1253 InitExprs.push_back(len); // set "int numBytes".
1254
1255 // struct NSConstantString
1256 QualType CFConstantStrType = Context->getCFConstantStringType();
1257 // (struct NSConstantString) { <exprs from above> }
1258 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1259 &InitExprs[0], InitExprs.size(),
1260 SourceLocation());
1261 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1262 // struct NSConstantString *
1263 expType = Context->getPointerType(StrRep->getType());
1264 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1265 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001266 // cast to NSConstantString *
1267 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001268 Rewrite.ReplaceStmt(Exp, cast);
1269 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001270 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001271#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001272}
1273
Steve Naroff874e2322007-11-15 10:28:18 +00001274ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001275 // check if we are sending a message to 'super'
1276 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001277 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1278 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1279 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1280 if (!strcmp(PVD->getName(), "self")) {
1281 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1282 if (ObjcInterfaceType *IT =
1283 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1284 if (IT->getDecl() ==
1285 CurMethodDecl->getClassInterface()->getSuperClass())
1286 return IT->getDecl();
1287 }
1288 }
1289 }
1290 }
1291 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001292 }
Steve Naroff874e2322007-11-15 10:28:18 +00001293 }
1294 return 0;
1295}
1296
1297// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1298QualType RewriteTest::getSuperStructType() {
1299 if (!SuperStructDecl) {
1300 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1301 &Context->Idents.get("objc_super"), 0);
1302 QualType FieldTypes[2];
1303
1304 // struct objc_object *receiver;
1305 FieldTypes[0] = Context->getObjcIdType();
1306 // struct objc_class *super;
1307 FieldTypes[1] = Context->getObjcClassType();
1308 // Create fields
1309 FieldDecl *FieldDecls[2];
1310
1311 for (unsigned i = 0; i < 2; ++i)
1312 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1313
1314 SuperStructDecl->defineBody(FieldDecls, 4);
1315 }
1316 return Context->getTagDeclType(SuperStructDecl);
1317}
1318
Steve Naroff934f2762007-10-24 22:48:43 +00001319Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001320 if (!SelGetUidFunctionDecl)
1321 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001322 if (!MsgSendFunctionDecl)
1323 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001324 if (!MsgSendSuperFunctionDecl)
1325 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001326 if (!MsgSendStretFunctionDecl)
1327 SynthMsgSendStretFunctionDecl();
1328 if (!MsgSendSuperStretFunctionDecl)
1329 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001330 if (!MsgSendFpretFunctionDecl)
1331 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001332 if (!GetClassFunctionDecl)
1333 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001334 if (!GetMetaClassFunctionDecl)
1335 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001336
Steve Naroff874e2322007-11-15 10:28:18 +00001337 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001338 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1339 // May need to use objc_msgSend_stret() as well.
1340 FunctionDecl *MsgSendStretFlavor = 0;
1341 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1342 QualType resultType = mDecl->getResultType();
1343 if (resultType.getCanonicalType()->isStructureType()
1344 || resultType.getCanonicalType()->isUnionType())
1345 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001346 else if (resultType.getCanonicalType()->isRealFloatingType())
1347 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001348 }
Steve Naroff874e2322007-11-15 10:28:18 +00001349
Steve Naroff934f2762007-10-24 22:48:43 +00001350 // Synthesize a call to objc_msgSend().
1351 llvm::SmallVector<Expr*, 8> MsgExprs;
1352 IdentifierInfo *clsName = Exp->getClassName();
1353
1354 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1355 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001356 if (!strcmp(clsName->getName(), "super")) {
1357 MsgSendFlavor = MsgSendSuperFunctionDecl;
1358 if (MsgSendStretFlavor)
1359 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1360 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1361
1362 ObjcInterfaceDecl *SuperDecl =
1363 CurMethodDecl->getClassInterface()->getSuperClass();
1364
1365 llvm::SmallVector<Expr*, 4> InitExprs;
1366
1367 // set the receiver to self, the first argument to all methods.
1368 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1369 Context->getObjcIdType(),
1370 SourceLocation()));
1371 llvm::SmallVector<Expr*, 8> ClsExprs;
1372 QualType argType = Context->getPointerType(Context->CharTy);
1373 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1374 SuperDecl->getIdentifier()->getLength(),
1375 false, argType, SourceLocation(),
1376 SourceLocation()));
1377 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1378 &ClsExprs[0],
1379 ClsExprs.size());
1380 // To turn off a warning, type-cast to 'id'
1381 InitExprs.push_back(
1382 new CastExpr(Context->getObjcIdType(),
1383 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1384 // struct objc_super
1385 QualType superType = getSuperStructType();
1386 // (struct objc_super) { <exprs from above> }
1387 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1388 &InitExprs[0], InitExprs.size(),
1389 SourceLocation());
1390 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1391 // struct objc_super *
1392 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1393 Context->getPointerType(SuperRep->getType()),
1394 SourceLocation());
1395 MsgExprs.push_back(Unop);
1396 } else {
1397 llvm::SmallVector<Expr*, 8> ClsExprs;
1398 QualType argType = Context->getPointerType(Context->CharTy);
1399 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1400 clsName->getLength(),
1401 false, argType, SourceLocation(),
1402 SourceLocation()));
1403 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1404 &ClsExprs[0],
1405 ClsExprs.size());
1406 MsgExprs.push_back(Cls);
1407 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001408 } else { // instance message.
1409 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001410
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001411 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001412 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001413 if (MsgSendStretFlavor)
1414 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001415 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1416
1417 llvm::SmallVector<Expr*, 4> InitExprs;
1418
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001419 InitExprs.push_back(
1420 new CastExpr(Context->getObjcIdType(),
1421 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001422
1423 llvm::SmallVector<Expr*, 8> ClsExprs;
1424 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001425 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1426 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001427 false, argType, SourceLocation(),
1428 SourceLocation()));
1429 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001430 &ClsExprs[0],
1431 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001432 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001433 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001434 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001435 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001436 // struct objc_super
1437 QualType superType = getSuperStructType();
1438 // (struct objc_super) { <exprs from above> }
1439 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1440 &InitExprs[0], InitExprs.size(),
1441 SourceLocation());
1442 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1443 // struct objc_super *
1444 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1445 Context->getPointerType(SuperRep->getType()),
1446 SourceLocation());
1447 MsgExprs.push_back(Unop);
1448 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001449 // Remove all type-casts because it may contain objc-style types; e.g.
1450 // Foo<Proto> *.
1451 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1452 recExpr = CE->getSubExpr();
Steve Naroff874e2322007-11-15 10:28:18 +00001453 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1454 MsgExprs.push_back(recExpr);
1455 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001456 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001457 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001458 llvm::SmallVector<Expr*, 8> SelExprs;
1459 QualType argType = Context->getPointerType(Context->CharTy);
1460 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1461 Exp->getSelector().getName().size(),
1462 false, argType, SourceLocation(),
1463 SourceLocation()));
1464 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1465 &SelExprs[0], SelExprs.size());
1466 MsgExprs.push_back(SelExp);
1467
1468 // Now push any user supplied arguments.
1469 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001470 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001471 // Make all implicit casts explicit...ICE comes in handy:-)
1472 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1473 // Reuse the ICE type, it is exactly what the doctor ordered.
1474 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1475 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001476 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001477 // We've transferred the ownership to MsgExprs. Null out the argument in
1478 // the original expression, since we will delete it below.
1479 Exp->setArg(i, 0);
1480 }
Steve Naroffab972d32007-11-04 22:37:50 +00001481 // Generate the funky cast.
1482 CastExpr *cast;
1483 llvm::SmallVector<QualType, 8> ArgTypes;
1484 QualType returnType;
1485
1486 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001487 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1488 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1489 else
1490 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001491 ArgTypes.push_back(Context->getObjcSelType());
1492 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1493 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001494 for (int i = 0; i < mDecl->getNumParams(); i++) {
1495 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001496 ArgTypes.push_back(t);
1497 }
Steve Naroffab972d32007-11-04 22:37:50 +00001498 returnType = mDecl->getResultType();
1499 } else {
1500 returnType = Context->getObjcIdType();
1501 }
1502 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001503 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001504
1505 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001506 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1507 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001508
1509 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1510 // If we don't do this cast, we get the following bizarre warning/note:
1511 // xx.m:13: warning: function called through a non-compatible type
1512 // xx.m:13: note: if this code is reached, the program will abort
1513 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1514 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001515
Steve Naroffab972d32007-11-04 22:37:50 +00001516 // Now do the "normal" pointer to function cast.
1517 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001518 &ArgTypes[0], ArgTypes.size(),
1519 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001520 castType = Context->getPointerType(castType);
1521 cast = new CastExpr(castType, cast, SourceLocation());
1522
1523 // Don't forget the parens to enforce the proper binding.
1524 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1525
1526 const FunctionType *FT = msgSendType->getAsFunctionType();
1527 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1528 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001529 if (MsgSendStretFlavor) {
1530 // We have the method which returns a struct/union. Must also generate
1531 // call to objc_msgSend_stret and hang both varieties on a conditional
1532 // expression which dictate which one to envoke depending on size of
1533 // method's return type.
1534
1535 // Create a reference to the objc_msgSend_stret() declaration.
1536 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1537 SourceLocation());
1538 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1539 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1540 SourceLocation());
1541 // Now do the "normal" pointer to function cast.
1542 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001543 &ArgTypes[0], ArgTypes.size(),
1544 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001545 castType = Context->getPointerType(castType);
1546 cast = new CastExpr(castType, cast, SourceLocation());
1547
1548 // Don't forget the parens to enforce the proper binding.
1549 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1550
1551 FT = msgSendType->getAsFunctionType();
1552 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1553 FT->getResultType(), SourceLocation());
1554
1555 // Build sizeof(returnType)
1556 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1557 returnType, Context->getSizeType(),
1558 SourceLocation(), SourceLocation());
1559 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1560 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1561 // For X86 it is more complicated and some kind of target specific routine
1562 // is needed to decide what to do.
1563 unsigned IntSize = static_cast<unsigned>(
1564 Context->getTypeSize(Context->IntTy, SourceLocation()));
1565
1566 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1567 Context->IntTy,
1568 SourceLocation());
1569 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1570 BinaryOperator::LE,
1571 Context->IntTy,
1572 SourceLocation());
1573 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1574 ConditionalOperator *CondExpr =
1575 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1576 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1577 // Now do the actual rewrite.
1578 Rewrite.ReplaceStmt(Exp, PE);
1579 delete Exp;
1580 return PE;
1581 }
Steve Naroff934f2762007-10-24 22:48:43 +00001582 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001583 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001584
Chris Lattnere64b7772007-10-24 16:57:36 +00001585 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001586 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001587}
1588
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001589/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1590/// call to objc_getProtocol("proto-name").
1591Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1592 if (!GetProtocolFunctionDecl)
1593 SynthGetProtocolFunctionDecl();
1594 // Create a call to objc_getProtocol("ProtocolName").
1595 llvm::SmallVector<Expr*, 8> ProtoExprs;
1596 QualType argType = Context->getPointerType(Context->CharTy);
1597 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1598 strlen(Exp->getProtocol()->getName()),
1599 false, argType, SourceLocation(),
1600 SourceLocation()));
1601 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1602 &ProtoExprs[0],
1603 ProtoExprs.size());
1604 Rewrite.ReplaceStmt(Exp, ProtoExp);
1605 delete Exp;
1606 return ProtoExp;
1607
1608}
1609
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001610/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1611/// an objective-c class with ivars.
1612void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1613 std::string &Result) {
1614 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1615 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001616 // Do not synthesize more than once.
1617 if (ObjcSynthesizedStructs.count(CDecl))
1618 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001619 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001620 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001621 SourceLocation LocStart = CDecl->getLocStart();
1622 SourceLocation LocEnd = CDecl->getLocEnd();
1623
1624 const char *startBuf = SM->getCharacterData(LocStart);
1625 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001626 // If no ivars and no root or if its root, directly or indirectly,
1627 // have no ivars (thus not synthesized) then no need to synthesize this class.
1628 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001629 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1630 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1631 Result.c_str(), Result.size());
1632 return;
1633 }
1634
1635 // FIXME: This has potential of causing problem. If
1636 // SynthesizeObjcInternalStruct is ever called recursively.
1637 Result += "\nstruct ";
1638 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001639
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001640 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001641 const char *cursor = strchr(startBuf, '{');
1642 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001643 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001644
1645 // rewrite the original header *without* disturbing the '{'
1646 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1647 Result.c_str(), Result.size());
1648 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1649 Result = "\n struct ";
1650 Result += RCDecl->getName();
1651 Result += " _";
1652 Result += RCDecl->getName();
1653 Result += ";\n";
1654
1655 // insert the super class structure definition.
1656 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1657 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1658 }
1659 cursor++; // past '{'
1660
1661 // Now comment out any visibility specifiers.
1662 while (cursor < endBuf) {
1663 if (*cursor == '@') {
1664 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001665 // Skip whitespace.
1666 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1667 /*scan*/;
1668
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001669 // FIXME: presence of @public, etc. inside comment results in
1670 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001671 if (!strncmp(cursor, "public", strlen("public")) ||
1672 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001673 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001674 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001675 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001676 // FIXME: If there are cases where '<' is used in ivar declaration part
1677 // of user code, then scan the ivar list and use needToScanForQualifiers
1678 // for type checking.
1679 else if (*cursor == '<') {
1680 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1681 Rewrite.InsertText(atLoc, "/* ", 3);
1682 cursor = strchr(cursor, '>');
1683 cursor++;
1684 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1685 Rewrite.InsertText(atLoc, " */", 3);
1686 }
Steve Narofffea763e82007-11-14 19:25:57 +00001687 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001688 }
Steve Narofffea763e82007-11-14 19:25:57 +00001689 // Don't forget to add a ';'!!
1690 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1691 } else { // we don't have any instance variables - insert super struct.
1692 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1693 Result += " {\n struct ";
1694 Result += RCDecl->getName();
1695 Result += " _";
1696 Result += RCDecl->getName();
1697 Result += ";\n};\n";
1698 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1699 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001700 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001701 // Mark this struct as having been generated.
1702 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001703 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001704}
1705
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001706// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1707/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001708void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001709 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001710 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001711 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001712 const char *ClassName,
1713 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001714 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001715 if (NumMethods > 0 && !objc_impl_method) {
1716 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001717 SEL _cmd;
1718 char *method_types;
1719 void *_imp;
1720 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001721 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001722 Result += "\nstruct _objc_method {\n";
1723 Result += "\tSEL _cmd;\n";
1724 Result += "\tchar *method_types;\n";
1725 Result += "\tvoid *_imp;\n";
1726 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001727
1728 /* struct _objc_method_list {
1729 struct _objc_method_list *next_method;
1730 int method_count;
1731 struct _objc_method method_list[];
1732 }
1733 */
1734 Result += "\nstruct _objc_method_list {\n";
1735 Result += "\tstruct _objc_method_list *next_method;\n";
1736 Result += "\tint method_count;\n";
1737 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001738 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001739 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001740 // Build _objc_method_list for class's methods if needed
1741 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001742 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001743 Result += prefix;
1744 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1745 Result += "_METHODS_";
1746 Result += ClassName;
1747 Result += " __attribute__ ((section (\"__OBJC, __";
1748 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001749 Result += "_meth\")))= ";
1750 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1751
1752 Result += "\t,{{(SEL)\"";
1753 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001754 std::string MethodTypeString;
1755 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1756 Result += "\", \"";
1757 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001758 Result += "\", ";
1759 Result += MethodInternalNames[Methods[0]];
1760 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001761 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001762 Result += "\t ,{(SEL)\"";
1763 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001764 std::string MethodTypeString;
1765 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1766 Result += "\", \"";
1767 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001768 Result += "\", ";
1769 Result += MethodInternalNames[Methods[i]];
1770 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001771 }
1772 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001773 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001774}
1775
1776/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1777void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1778 int NumProtocols,
1779 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001780 const char *ClassName,
1781 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001782 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001783 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001784 for (int i = 0; i < NumProtocols; i++) {
1785 ObjcProtocolDecl *PDecl = Protocols[i];
1786 // Output struct protocol_methods holder of method selector and type.
1787 if (!objc_protocol_methods &&
1788 (PDecl->getNumInstanceMethods() > 0
1789 || PDecl->getNumClassMethods() > 0)) {
1790 /* struct protocol_methods {
1791 SEL _cmd;
1792 char *method_types;
1793 }
1794 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001795 Result += "\nstruct protocol_methods {\n";
1796 Result += "\tSEL _cmd;\n";
1797 Result += "\tchar *method_types;\n";
1798 Result += "};\n";
1799
1800 /* struct _objc_protocol_method_list {
1801 int protocol_method_count;
1802 struct protocol_methods protocols[];
1803 }
1804 */
1805 Result += "\nstruct _objc_protocol_method_list {\n";
1806 Result += "\tint protocol_method_count;\n";
1807 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001808 objc_protocol_methods = true;
1809 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001810
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001811 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001812 int NumMethods = PDecl->getNumInstanceMethods();
1813 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001814 Result += "\nstatic struct _objc_protocol_method_list "
1815 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1816 Result += PDecl->getName();
1817 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1818 "{\n\t" + utostr(NumMethods) + "\n";
1819
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001820 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001821 Result += "\t,{{(SEL)\"";
1822 Result += Methods[0]->getSelector().getName().c_str();
1823 Result += "\", \"\"}\n";
1824
1825 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001826 Result += "\t ,{(SEL)\"";
1827 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001828 std::string MethodTypeString;
1829 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1830 Result += "\", \"";
1831 Result += MethodTypeString;
1832 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001833 }
1834 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001835 }
1836
1837 // Output class methods declared in this protocol.
1838 NumMethods = PDecl->getNumClassMethods();
1839 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001840 Result += "\nstatic struct _objc_protocol_method_list "
1841 "_OBJC_PROTOCOL_CLASS_METHODS_";
1842 Result += PDecl->getName();
1843 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1844 "{\n\t";
1845 Result += utostr(NumMethods);
1846 Result += "\n";
1847
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001848 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001849 Result += "\t,{{(SEL)\"";
1850 Result += Methods[0]->getSelector().getName().c_str();
1851 Result += "\", \"\"}\n";
1852
1853 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001854 Result += "\t ,{(SEL)\"";
1855 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001856 std::string MethodTypeString;
1857 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1858 Result += "\", \"";
1859 Result += MethodTypeString;
1860 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001861 }
1862 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001863 }
1864 // Output:
1865 /* struct _objc_protocol {
1866 // Objective-C 1.0 extensions
1867 struct _objc_protocol_extension *isa;
1868 char *protocol_name;
1869 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001870 struct _objc_protocol_method_list *instance_methods;
1871 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001872 };
1873 */
1874 static bool objc_protocol = false;
1875 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001876 Result += "\nstruct _objc_protocol {\n";
1877 Result += "\tstruct _objc_protocol_extension *isa;\n";
1878 Result += "\tchar *protocol_name;\n";
1879 Result += "\tstruct _objc_protocol **protocol_list;\n";
1880 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1881 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1882 Result += "};\n";
1883
1884 /* struct _objc_protocol_list {
1885 struct _objc_protocol_list *next;
1886 int protocol_count;
1887 struct _objc_protocol *class_protocols[];
1888 }
1889 */
1890 Result += "\nstruct _objc_protocol_list {\n";
1891 Result += "\tstruct _objc_protocol_list *next;\n";
1892 Result += "\tint protocol_count;\n";
1893 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1894 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001895 objc_protocol = true;
1896 }
1897
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001898 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1899 Result += PDecl->getName();
1900 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1901 "{\n\t0, \"";
1902 Result += PDecl->getName();
1903 Result += "\", 0, ";
1904 if (PDecl->getInstanceMethods() > 0) {
1905 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1906 Result += PDecl->getName();
1907 Result += ", ";
1908 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001909 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001910 Result += "0, ";
1911 if (PDecl->getClassMethods() > 0) {
1912 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1913 Result += PDecl->getName();
1914 Result += "\n";
1915 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001916 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001917 Result += "0\n";
1918 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001919 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001920 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001921 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1922 Result += prefix;
1923 Result += "_PROTOCOLS_";
1924 Result += ClassName;
1925 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1926 "{\n\t0, ";
1927 Result += utostr(NumProtocols);
1928 Result += "\n";
1929
1930 Result += "\t,{&_OBJC_PROTOCOL_";
1931 Result += Protocols[0]->getName();
1932 Result += " \n";
1933
1934 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001935 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001936 Result += "\t ,&_OBJC_PROTOCOL_";
1937 Result += PDecl->getName();
1938 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001939 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001940 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001941 }
1942}
1943
1944/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1945/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001946void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1947 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001948 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1949 // Find category declaration for this implementation.
1950 ObjcCategoryDecl *CDecl;
1951 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1952 CDecl = CDecl->getNextClassCategory())
1953 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1954 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001955
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001956 char *FullCategoryName = (char*)alloca(
1957 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1958 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1959
1960 // Build _objc_method_list for class's instance methods if needed
1961 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1962 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001963 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001964 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001965
1966 // Build _objc_method_list for class's class methods if needed
1967 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1968 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001969 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001970 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001971
1972 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001973 // Null CDecl is case of a category implementation with no category interface
1974 if (CDecl)
1975 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1976 CDecl->getNumReferencedProtocols(),
1977 "CATEGORY",
1978 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001979
1980 /* struct _objc_category {
1981 char *category_name;
1982 char *class_name;
1983 struct _objc_method_list *instance_methods;
1984 struct _objc_method_list *class_methods;
1985 struct _objc_protocol_list *protocols;
1986 // Objective-C 1.0 extensions
1987 uint32_t size; // sizeof (struct _objc_category)
1988 struct _objc_property_list *instance_properties; // category's own
1989 // @property decl.
1990 };
1991 */
1992
1993 static bool objc_category = false;
1994 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001995 Result += "\nstruct _objc_category {\n";
1996 Result += "\tchar *category_name;\n";
1997 Result += "\tchar *class_name;\n";
1998 Result += "\tstruct _objc_method_list *instance_methods;\n";
1999 Result += "\tstruct _objc_method_list *class_methods;\n";
2000 Result += "\tstruct _objc_protocol_list *protocols;\n";
2001 Result += "\tunsigned int size;\n";
2002 Result += "\tstruct _objc_property_list *instance_properties;\n";
2003 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002004 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002005 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002006 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2007 Result += FullCategoryName;
2008 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2009 Result += IDecl->getName();
2010 Result += "\"\n\t, \"";
2011 Result += ClassDecl->getName();
2012 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002013
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002014 if (IDecl->getNumInstanceMethods() > 0) {
2015 Result += "\t, (struct _objc_method_list *)"
2016 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2017 Result += FullCategoryName;
2018 Result += "\n";
2019 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002020 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002021 Result += "\t, 0\n";
2022 if (IDecl->getNumClassMethods() > 0) {
2023 Result += "\t, (struct _objc_method_list *)"
2024 "&_OBJC_CATEGORY_CLASS_METHODS_";
2025 Result += FullCategoryName;
2026 Result += "\n";
2027 }
2028 else
2029 Result += "\t, 0\n";
2030
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002031 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002032 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2033 Result += FullCategoryName;
2034 Result += "\n";
2035 }
2036 else
2037 Result += "\t, 0\n";
2038 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002039}
2040
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002041/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2042/// ivar offset.
2043void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2044 ObjcIvarDecl *ivar,
2045 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002046 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002047 Result += IDecl->getName();
2048 Result += ", ";
2049 Result += ivar->getName();
2050 Result += ")";
2051}
2052
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002053//===----------------------------------------------------------------------===//
2054// Meta Data Emission
2055//===----------------------------------------------------------------------===//
2056
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002057void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2058 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002059 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2060
2061 // Build _objc_ivar_list metadata for classes ivars if needed
2062 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2063 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00002064 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002065 // Explictly declared @interface's are already synthesized.
2066 if (CDecl->ImplicitInterfaceDecl()) {
2067 // FIXME: Implementation of a class with no @interface (legacy) doese not
2068 // produce correct synthesis as yet.
2069 SynthesizeObjcInternalStruct(CDecl, Result);
2070 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002071
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002072 if (NumIvars > 0) {
2073 static bool objc_ivar = false;
2074 if (!objc_ivar) {
2075 /* struct _objc_ivar {
2076 char *ivar_name;
2077 char *ivar_type;
2078 int ivar_offset;
2079 };
2080 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002081 Result += "\nstruct _objc_ivar {\n";
2082 Result += "\tchar *ivar_name;\n";
2083 Result += "\tchar *ivar_type;\n";
2084 Result += "\tint ivar_offset;\n";
2085 Result += "};\n";
2086
2087 /* struct _objc_ivar_list {
2088 int ivar_count;
2089 struct _objc_ivar ivar_list[];
2090 };
2091 */
2092 Result += "\nstruct _objc_ivar_list {\n";
2093 Result += "\tint ivar_count;\n";
2094 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002095 objc_ivar = true;
2096 }
2097
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002098 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2099 Result += IDecl->getName();
2100 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2101 "{\n\t";
2102 Result += utostr(NumIvars);
2103 Result += "\n";
2104
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002105 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2106 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00002107 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002108 Result += "\t,{{\"";
2109 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002110 Result += "\", \"";
2111 std::string StrEncoding;
2112 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2113 Result += StrEncoding;
2114 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002115 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2116 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002117 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002118 Result += "\t ,{\"";
2119 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002120 Result += "\", \"";
2121 std::string StrEncoding;
2122 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2123 Result += StrEncoding;
2124 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002125 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2126 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002127 }
2128
2129 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002130 }
2131
2132 // Build _objc_method_list for class's instance methods if needed
2133 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2134 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002135 true,
2136 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002137
2138 // Build _objc_method_list for class's class methods if needed
2139 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002140 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002141 false,
2142 "", IDecl->getName(), Result);
2143
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002144 // Protocols referenced in class declaration?
2145 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2146 CDecl->getNumIntfRefProtocols(),
2147 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002148 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002149
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002150
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002151 // Declaration of class/meta-class metadata
2152 /* struct _objc_class {
2153 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002154 const char *super_class_name;
2155 char *name;
2156 long version;
2157 long info;
2158 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002159 struct _objc_ivar_list *ivars;
2160 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002161 struct objc_cache *cache;
2162 struct objc_protocol_list *protocols;
2163 const char *ivar_layout;
2164 struct _objc_class_ext *ext;
2165 };
2166 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002167 static bool objc_class = false;
2168 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002169 Result += "\nstruct _objc_class {\n";
2170 Result += "\tstruct _objc_class *isa;\n";
2171 Result += "\tconst char *super_class_name;\n";
2172 Result += "\tchar *name;\n";
2173 Result += "\tlong version;\n";
2174 Result += "\tlong info;\n";
2175 Result += "\tlong instance_size;\n";
2176 Result += "\tstruct _objc_ivar_list *ivars;\n";
2177 Result += "\tstruct _objc_method_list *methods;\n";
2178 Result += "\tstruct objc_cache *cache;\n";
2179 Result += "\tstruct _objc_protocol_list *protocols;\n";
2180 Result += "\tconst char *ivar_layout;\n";
2181 Result += "\tstruct _objc_class_ext *ext;\n";
2182 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002183 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002184 }
2185
2186 // Meta-class metadata generation.
2187 ObjcInterfaceDecl *RootClass = 0;
2188 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2189 while (SuperClass) {
2190 RootClass = SuperClass;
2191 SuperClass = SuperClass->getSuperClass();
2192 }
2193 SuperClass = CDecl->getSuperClass();
2194
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002195 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2196 Result += CDecl->getName();
2197 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2198 "{\n\t(struct _objc_class *)\"";
2199 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2200 Result += "\"";
2201
2202 if (SuperClass) {
2203 Result += ", \"";
2204 Result += SuperClass->getName();
2205 Result += "\", \"";
2206 Result += CDecl->getName();
2207 Result += "\"";
2208 }
2209 else {
2210 Result += ", 0, \"";
2211 Result += CDecl->getName();
2212 Result += "\"";
2213 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002214 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002215 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002216 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002217 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002218 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002219 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002220 Result += "\n";
2221 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002222 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002223 Result += ", 0\n";
2224 if (CDecl->getNumIntfRefProtocols() > 0) {
2225 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2226 Result += CDecl->getName();
2227 Result += ",0,0\n";
2228 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002229 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002230 Result += "\t,0,0,0,0\n";
2231 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002232
2233 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002234 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2235 Result += CDecl->getName();
2236 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2237 "{\n\t&_OBJC_METACLASS_";
2238 Result += CDecl->getName();
2239 if (SuperClass) {
2240 Result += ", \"";
2241 Result += SuperClass->getName();
2242 Result += "\", \"";
2243 Result += CDecl->getName();
2244 Result += "\"";
2245 }
2246 else {
2247 Result += ", 0, \"";
2248 Result += CDecl->getName();
2249 Result += "\"";
2250 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002251 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002252 Result += ", 0,1";
2253 if (!ObjcSynthesizedStructs.count(CDecl))
2254 Result += ",0";
2255 else {
2256 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002257 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002258 Result += CDecl->getName();
2259 Result += ")";
2260 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002261 if (NumIvars > 0) {
2262 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2263 Result += CDecl->getName();
2264 Result += "\n\t";
2265 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002266 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002267 Result += ",0";
2268 if (IDecl->getNumInstanceMethods() > 0) {
2269 Result += ", &_OBJC_INSTANCE_METHODS_";
2270 Result += CDecl->getName();
2271 Result += ", 0\n\t";
2272 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002273 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002274 Result += ",0,0";
2275 if (CDecl->getNumIntfRefProtocols() > 0) {
2276 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2277 Result += CDecl->getName();
2278 Result += ", 0,0\n";
2279 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002280 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002281 Result += ",0,0,0\n";
2282 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002283}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002284
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002285/// RewriteImplementations - This routine rewrites all method implementations
2286/// and emits meta-data.
2287
2288void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002289 int ClsDefCount = ClassImplementation.size();
2290 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002291
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002292 if (ClsDefCount == 0 && CatDefCount == 0)
2293 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002294 // Rewrite implemented methods
2295 for (int i = 0; i < ClsDefCount; i++)
2296 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002297
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002298 for (int i = 0; i < CatDefCount; i++)
2299 RewriteImplementationDecl(CategoryImplementation[i]);
2300
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002301 // This is needed for use of offsetof
2302 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002303
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002304 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002305 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002306 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002307
2308 // For each implemented category, write out all its meta data.
2309 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002310 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002311
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002312 // Write objc_symtab metadata
2313 /*
2314 struct _objc_symtab
2315 {
2316 long sel_ref_cnt;
2317 SEL *refs;
2318 short cls_def_cnt;
2319 short cat_def_cnt;
2320 void *defs[cls_def_cnt + cat_def_cnt];
2321 };
2322 */
2323
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002324 Result += "\nstruct _objc_symtab {\n";
2325 Result += "\tlong sel_ref_cnt;\n";
2326 Result += "\tSEL *refs;\n";
2327 Result += "\tshort cls_def_cnt;\n";
2328 Result += "\tshort cat_def_cnt;\n";
2329 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2330 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002331
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002332 Result += "static struct _objc_symtab "
2333 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2334 Result += "\t0, 0, " + utostr(ClsDefCount)
2335 + ", " + utostr(CatDefCount) + "\n";
2336 for (int i = 0; i < ClsDefCount; i++) {
2337 Result += "\t,&_OBJC_CLASS_";
2338 Result += ClassImplementation[i]->getName();
2339 Result += "\n";
2340 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002341
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002342 for (int i = 0; i < CatDefCount; i++) {
2343 Result += "\t,&_OBJC_CATEGORY_";
2344 Result += CategoryImplementation[i]->getClassInterface()->getName();
2345 Result += "_";
2346 Result += CategoryImplementation[i]->getName();
2347 Result += "\n";
2348 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002349
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002350 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002351
2352 // Write objc_module metadata
2353
2354 /*
2355 struct _objc_module {
2356 long version;
2357 long size;
2358 const char *name;
2359 struct _objc_symtab *symtab;
2360 }
2361 */
2362
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002363 Result += "\nstruct _objc_module {\n";
2364 Result += "\tlong version;\n";
2365 Result += "\tlong size;\n";
2366 Result += "\tconst char *name;\n";
2367 Result += "\tstruct _objc_symtab *symtab;\n";
2368 Result += "};\n\n";
2369 Result += "static struct _objc_module "
2370 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002371 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2372 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002373 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002374
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002375}
Chris Lattner311ff022007-10-16 22:36:42 +00002376