blob: c197705f50e31541a43c1963e2d3a5872e91fdd3 [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 Naroff934f2762007-10-24 22:48:43 +000050 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000051 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000052
Steve Naroffbeaf2992007-11-03 11:27:19 +000053 // ObjC string constant support.
54 FileVarDecl *ConstantStringClassReference;
55 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000056
Steve Naroff874e2322007-11-15 10:28:18 +000057 // Needed for super.
58 ObjcMethodDecl *CurMethodDecl;
59 RecordDecl *SuperStructDecl;
60
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000061 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 public:
Chris Lattner01c57482007-10-17 22:35:30 +000063 void Initialize(ASTContext &context, unsigned mainFileID) {
64 Context = &context;
65 SM = &Context->SourceMgr;
Steve Naroffebf2b562007-10-23 23:50:29 +000066 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000067 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000068 MsgSendStretFunctionDecl = 0;
69 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000070 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000071 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000072 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000073 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000074 ConstantStringClassReference = 0;
75 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000076 CurMethodDecl = 0;
77 SuperStructDecl = 0;
78
Chris Lattner26de4652007-12-02 01:13:47 +000079 // Get the ID and start/end of the main file.
80 MainFileID = mainFileID;
81 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
82 MainFileStart = MainBuf->getBufferStart();
83 MainFileEnd = MainBuf->getBufferEnd();
84
85
Chris Lattner01c57482007-10-17 22:35:30 +000086 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000087 // declaring objc_selector outside the parameter list removes a silly
88 // scope related warning...
Steve Narofff6248702007-11-15 17:06:21 +000089 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000090 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000091 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000092 "extern struct objc_object *objc_msgSendSuper"
93 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000094 "extern struct objc_object *objc_msgSend_stret"
95 "(struct objc_object *, struct objc_selector *, ...);\n"
96 "extern struct objc_object *objc_msgSendSuper_stret"
97 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +000098 "extern struct objc_object *objc_msgSend_fpret"
99 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000100 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000101 "(const char *);\n"
102 "extern void objc_exception_throw(struct objc_object *);\n"
103 "extern void objc_exception_try_enter(void *);\n"
104 "extern void objc_exception_try_exit(void *);\n"
105 "extern struct objc_object *objc_exception_extract(void *);\n"
106 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000107 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000108 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000109
Steve Naroffab972d32007-11-04 22:37:50 +0000110 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
111 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000112 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000113
Chris Lattnerf04da132007-10-24 17:06:59 +0000114 // Top Level Driver code.
115 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000116 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000117 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 ~RewriteTest();
119
120 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000121 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000123 void RewriteTabs();
124 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000125 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000126 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000127 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000128 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000129 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000130 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000131 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000132 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000133 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000134 void RewriteObjcQualifiedInterfaceTypes(
135 const FunctionTypeProto *proto, FunctionDecl *FD);
136 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000137 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
138 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000139
Chris Lattnerf04da132007-10-24 17:06:59 +0000140 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000141 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000142 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000143 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000144 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000145 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000146 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000147 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
148 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
149 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000150 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000151 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
152 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000153 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000154 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000155 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000156 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000157 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000158 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000159 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000160 void SynthSelGetUidFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000163 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
164 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000165
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000166 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
167 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000168
Steve Naroff0416fb92007-11-11 17:19:15 +0000169 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000170 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000171 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000172 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000173 const char *ClassName,
174 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000175
176 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
177 int NumProtocols,
178 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000179 const char *ClassName,
180 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000181 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
182 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000183 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
184 ObjcIvarDecl *ivar,
185 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000186 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000187 };
188}
189
Chris Lattnere365c502007-11-30 22:25:36 +0000190ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
191 return new RewriteTest(Diags);
192}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000193
Chris Lattnerf04da132007-10-24 17:06:59 +0000194//===----------------------------------------------------------------------===//
195// Top Level Driver Code
196//===----------------------------------------------------------------------===//
197
Chris Lattner8a12c272007-10-11 18:38:32 +0000198void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000199 // Two cases: either the decl could be in the main file, or it could be in a
200 // #included file. If the former, rewrite it now. If the later, check to see
201 // if we rewrote the #include/#import.
202 SourceLocation Loc = D->getLocation();
203 Loc = SM->getLogicalLoc(Loc);
204
205 // If this is for a builtin, ignore it.
206 if (Loc.isInvalid()) return;
207
Steve Naroffebf2b562007-10-23 23:50:29 +0000208 // Look for built-in declarations that we need to refer during the rewrite.
209 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000210 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000211 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
212 // declared in <Foundation/NSString.h>
213 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
214 ConstantStringClassReference = FVD;
215 return;
216 }
Steve Naroffbef11852007-10-26 20:53:56 +0000217 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
218 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000219 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
220 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000221 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
222 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000223 } else if (ObjcForwardProtocolDecl *FP =
224 dyn_cast<ObjcForwardProtocolDecl>(D)){
225 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000226 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000227 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000228 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
229 return HandleDeclInMainFile(D);
230
Chris Lattnerf04da132007-10-24 17:06:59 +0000231 // Otherwise, see if there is a #import in the main file that should be
232 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000233 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000234}
235
Chris Lattnerf04da132007-10-24 17:06:59 +0000236/// HandleDeclInMainFile - This is called for each top-level decl defined in the
237/// main file of the input.
238void RewriteTest::HandleDeclInMainFile(Decl *D) {
239 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
240 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000241 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000242
243 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000244 if (Stmt *Body = MD->getBody()) {
245 //Body->dump();
246 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000247 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000248 CurMethodDecl = 0;
249 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000250 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000251 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
252 ClassImplementation.push_back(CI);
253 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
254 CategoryImplementation.push_back(CI);
255 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
256 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000257 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
258 if (VD->getInit())
259 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
260 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000261 // Nothing yet.
262}
263
264RewriteTest::~RewriteTest() {
265 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000266
267 // Rewrite tabs if we care.
268 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000269
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000270 // Rewrite Objective-c meta data*
271 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000272 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
275 // we are done.
276 if (const RewriteBuffer *RewriteBuf =
277 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000278 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000279 std::string S(RewriteBuf->begin(), RewriteBuf->end());
280 printf("%s\n", S.c_str());
281 } else {
282 printf("No changes\n");
283 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000284 // Emit metadata.
285 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000286}
287
Chris Lattnerf04da132007-10-24 17:06:59 +0000288//===----------------------------------------------------------------------===//
289// Syntactic (non-AST) Rewriting Code
290//===----------------------------------------------------------------------===//
291
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000292void RewriteTest::RewriteInclude(SourceLocation Loc) {
293 // Rip up the #include stack to the main file.
294 SourceLocation IncLoc = Loc, NextLoc = Loc;
295 do {
296 IncLoc = Loc;
297 Loc = SM->getLogicalLoc(NextLoc);
298 NextLoc = SM->getIncludeLoc(Loc);
299 } while (!NextLoc.isInvalid());
300
301 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
302 // IncLoc indicates the header that was included if it is useful.
303 IncLoc = SM->getLogicalLoc(IncLoc);
304 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
305 Loc == LastIncLoc)
306 return;
307 LastIncLoc = Loc;
308
309 unsigned IncCol = SM->getColumnNumber(Loc);
310 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
311
312 // Replace the #import with #include.
313 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
314}
315
Chris Lattnerf04da132007-10-24 17:06:59 +0000316void RewriteTest::RewriteTabs() {
317 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
318 const char *MainBufStart = MainBuf.first;
319 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000320
Chris Lattnerf04da132007-10-24 17:06:59 +0000321 // Loop over the whole file, looking for tabs.
322 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
323 if (*BufPtr != '\t')
324 continue;
325
326 // Okay, we found a tab. This tab will turn into at least one character,
327 // but it depends on which 'virtual column' it is in. Compute that now.
328 unsigned VCol = 0;
329 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
330 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
331 ++VCol;
332
333 // Okay, now that we know the virtual column, we know how many spaces to
334 // insert. We assume 8-character tab-stops.
335 unsigned Spaces = 8-(VCol & 7);
336
337 // Get the location of the tab.
338 SourceLocation TabLoc =
339 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
340
341 // Rewrite the single tab character into a sequence of spaces.
342 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
343 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000344}
345
346
Chris Lattnerf04da132007-10-24 17:06:59 +0000347void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
348 int numDecls = ClassDecl->getNumForwardDecls();
349 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
350
351 // Get the start location and compute the semi location.
352 SourceLocation startLoc = ClassDecl->getLocation();
353 const char *startBuf = SM->getCharacterData(startLoc);
354 const char *semiPtr = strchr(startBuf, ';');
355
356 // Translate to typedef's that forward reference structs with the same name
357 // as the class. As a convenience, we include the original declaration
358 // as a comment.
359 std::string typedefString;
360 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000361 typedefString.append(startBuf, semiPtr-startBuf+1);
362 typedefString += "\n";
363 for (int i = 0; i < numDecls; i++) {
364 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000365 typedefString += "#ifndef _REWRITER_typedef_";
366 typedefString += ForwardDecl->getName();
367 typedefString += "\n";
368 typedefString += "#define _REWRITER_typedef_";
369 typedefString += ForwardDecl->getName();
370 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000371 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000372 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000373 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000374 }
375
376 // Replace the @class with typedefs corresponding to the classes.
377 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
378 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000379}
380
Steve Naroff71c0a952007-11-13 23:01:27 +0000381void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000382 for (int i = 0; i < nMethods; i++) {
383 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000384 SourceLocation LocStart = Method->getLocStart();
385 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000386
Steve Naroff1d098f62007-11-14 14:34:23 +0000387 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
388 Rewrite.InsertText(LocStart, "/* ", 3);
389 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
390 } else {
391 Rewrite.InsertText(LocStart, "// ", 3);
392 }
Steve Naroff423cb562007-10-30 13:30:57 +0000393 }
394}
395
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000396void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
397{
398 for (int i = 0; i < nProperties; i++) {
399 ObjcPropertyDecl *Property = Properties[i];
400 SourceLocation Loc = Property->getLocation();
401
402 Rewrite.ReplaceText(Loc, 0, "// ", 3);
403
404 // FIXME: handle properties that are declared across multiple lines.
405 }
406}
407
Steve Naroff423cb562007-10-30 13:30:57 +0000408void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
409 SourceLocation LocStart = CatDecl->getLocStart();
410
411 // FIXME: handle category headers that are declared across multiple lines.
412 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
413
Steve Naroff71c0a952007-11-13 23:01:27 +0000414 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
415 CatDecl->getInstanceMethods());
416 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
417 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000418 // Lastly, comment out the @end.
419 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
420}
421
Steve Naroff752d6ef2007-10-30 16:42:30 +0000422void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000423 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000424
Steve Naroff752d6ef2007-10-30 16:42:30 +0000425 SourceLocation LocStart = PDecl->getLocStart();
426
427 // FIXME: handle protocol headers that are declared across multiple lines.
428 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
429
Steve Naroff71c0a952007-11-13 23:01:27 +0000430 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
431 PDecl->getInstanceMethods());
432 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
433 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000434 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000435 SourceLocation LocEnd = PDecl->getAtEndLoc();
436 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000437
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000438 // Must comment out @optional/@required
439 const char *startBuf = SM->getCharacterData(LocStart);
440 const char *endBuf = SM->getCharacterData(LocEnd);
441 for (const char *p = startBuf; p < endBuf; p++) {
442 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
443 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000444 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000445 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
446 CommentedOptional.c_str(), CommentedOptional.size());
447
448 }
449 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
450 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000451 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000452 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
453 CommentedRequired.c_str(), CommentedRequired.size());
454
455 }
456 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000457}
458
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000459void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
460 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000461 if (LocStart.isInvalid())
462 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000463 // FIXME: handle forward protocol that are declared across multiple lines.
464 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
465}
466
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000467void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
468 std::string &ResultStr) {
469 ResultStr += "\nstatic ";
470 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000471 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000472
473 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000474 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000475
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000476 if (OMD->isInstance())
477 NameStr += "_I_";
478 else
479 NameStr += "_C_";
480
481 NameStr += OMD->getClassInterface()->getName();
482 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000483
484 NamedDecl *MethodContext = OMD->getMethodContext();
485 if (ObjcCategoryImplDecl *CID =
486 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000487 NameStr += CID->getName();
488 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000489 }
490 // Append selector names, replacing ':' with '_'
491 const char *selName = OMD->getSelector().getName().c_str();
492 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000493 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494 else {
495 std::string selString = OMD->getSelector().getName();
496 int len = selString.size();
497 for (int i = 0; i < len; i++)
498 if (selString[i] == ':')
499 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000500 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000501 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000502 // Remember this name for metadata emission
503 MethodInternalNames[OMD] = NameStr;
504 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000505
506 // Rewrite arguments
507 ResultStr += "(";
508
509 // invisible arguments
510 if (OMD->isInstance()) {
511 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
512 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000513 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
514 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515 ResultStr += selfTy.getAsString();
516 }
517 else
518 ResultStr += Context->getObjcIdType().getAsString();
519
520 ResultStr += " self, ";
521 ResultStr += Context->getObjcSelType().getAsString();
522 ResultStr += " _cmd";
523
524 // Method arguments.
525 for (int i = 0; i < OMD->getNumParams(); i++) {
526 ParmVarDecl *PDecl = OMD->getParamDecl(i);
527 ResultStr += ", ";
528 ResultStr += PDecl->getType().getAsString();
529 ResultStr += " ";
530 ResultStr += PDecl->getName();
531 }
532 ResultStr += ")";
533
534}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000535void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
536 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
537 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000538
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 if (IMD)
540 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
541 else
542 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000543
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000544 int numMethods = IMD ? IMD->getNumInstanceMethods()
545 : CID->getNumInstanceMethods();
546
547 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000548 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000549 ObjcMethodDecl *OMD;
550 if (IMD)
551 OMD = IMD->getInstanceMethods()[i];
552 else
553 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000554 RewriteObjcMethodDecl(OMD, ResultStr);
555 SourceLocation LocStart = OMD->getLocStart();
556 SourceLocation LocEnd = OMD->getBody()->getLocStart();
557
558 const char *startBuf = SM->getCharacterData(LocStart);
559 const char *endBuf = SM->getCharacterData(LocEnd);
560 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
561 ResultStr.c_str(), ResultStr.size());
562 }
563
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000564 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
565 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000566 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000567 ObjcMethodDecl *OMD;
568 if (IMD)
569 OMD = IMD->getClassMethods()[i];
570 else
571 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000572 RewriteObjcMethodDecl(OMD, ResultStr);
573 SourceLocation LocStart = OMD->getLocStart();
574 SourceLocation LocEnd = OMD->getBody()->getLocStart();
575
576 const char *startBuf = SM->getCharacterData(LocStart);
577 const char *endBuf = SM->getCharacterData(LocEnd);
578 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
579 ResultStr.c_str(), ResultStr.size());
580 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000581 if (IMD)
582 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
583 else
584 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585}
586
Steve Naroffbef11852007-10-26 20:53:56 +0000587void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000588 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000589 if (!ObjcForwardDecls.count(ClassDecl)) {
590 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000591 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000592 ResultStr += ClassDecl->getName();
593 ResultStr += "\n";
594 ResultStr += "#define _REWRITER_typedef_";
595 ResultStr += ClassDecl->getName();
596 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000597 ResultStr += "typedef struct ";
598 ResultStr += ClassDecl->getName();
599 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000600 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000601 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000602
603 // Mark this typedef as having been generated.
604 ObjcForwardDecls.insert(ClassDecl);
605 }
Steve Narofff908a872007-10-30 02:23:23 +0000606 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
607
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000608 RewriteProperties(ClassDecl->getNumPropertyDecl(),
609 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000610 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
611 ClassDecl->getInstanceMethods());
612 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
613 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000614
Steve Naroff2feac5e2007-10-30 03:43:13 +0000615 // Lastly, comment out the @end.
616 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000617}
618
Steve Naroff7e3411b2007-11-15 02:58:25 +0000619Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
620 ObjcIvarDecl *D = IV->getDecl();
621 if (IV->isFreeIvar()) {
622 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
623 IV->getLocation());
624 Rewrite.ReplaceStmt(IV, Replacement);
625 delete IV;
626 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000627 } else {
628 if (CurMethodDecl) {
629 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
630 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
631 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
632 IdentifierInfo *II = intT->getDecl()->getIdentifier();
633 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
634 II, 0);
635 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
636
637 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
638 // Don't forget the parens to enforce the proper binding.
639 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
640 Rewrite.ReplaceStmt(IV->getBase(), PE);
641 delete IV->getBase();
642 return PE;
643 }
644 }
645 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000646 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000647 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000648}
649
Chris Lattnerf04da132007-10-24 17:06:59 +0000650//===----------------------------------------------------------------------===//
651// Function Body / Expression rewriting
652//===----------------------------------------------------------------------===//
653
Steve Narofff3473a72007-11-09 15:20:18 +0000654Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000655 // Otherwise, just rewrite all children.
656 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
657 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000658 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000659 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000660 if (newStmt)
661 *CI = newStmt;
662 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000663
664 // Handle specific things.
665 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
666 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000667
668 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
669 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000670
671 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
672 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000673
674 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
675 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000676
Steve Naroff934f2762007-10-24 22:48:43 +0000677 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
678 // Before we rewrite it, put the original message expression in a comment.
679 SourceLocation startLoc = MessExpr->getLocStart();
680 SourceLocation endLoc = MessExpr->getLocEnd();
681
682 const char *startBuf = SM->getCharacterData(startLoc);
683 const char *endBuf = SM->getCharacterData(endLoc);
684
685 std::string messString;
686 messString += "// ";
687 messString.append(startBuf, endBuf-startBuf+1);
688 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000689
Steve Naroff934f2762007-10-24 22:48:43 +0000690 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
691 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
692 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000693 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000694 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000695 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000696
697 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
698 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000699
700 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
701 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000702#if 0
703 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
704 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
705 // Get the new text.
706 std::ostringstream Buf;
707 Replacement->printPretty(Buf);
708 const std::string &Str = Buf.str();
709
710 printf("CAST = %s\n", &Str[0]);
711 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
712 delete S;
713 return Replacement;
714 }
715#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000716 // Return this stmt unmodified.
717 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000718}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000719
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000720Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000721 // Get the start location and compute the semi location.
722 SourceLocation startLoc = S->getLocStart();
723 const char *startBuf = SM->getCharacterData(startLoc);
724
725 assert((*startBuf == '@') && "bogus @try location");
726
727 std::string buf;
728 // declare a new scope with two variables, _stack and _rethrow.
729 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
730 buf += "int buf[18/*32-bit i386*/];\n";
731 buf += "char *pointers[4];} _stack;\n";
732 buf += "id volatile _rethrow = 0;\n";
733 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000734 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000735
736 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
737
738 startLoc = S->getTryBody()->getLocEnd();
739 startBuf = SM->getCharacterData(startLoc);
740
741 assert((*startBuf == '}') && "bogus @try block");
742
743 SourceLocation lastCurlyLoc = startLoc;
744
745 startLoc = startLoc.getFileLocWithOffset(1);
746 buf = " /* @catch begin */ else {\n";
747 buf += " id _caught = objc_exception_extract(&_stack);\n";
748 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000749 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000750 buf += " _rethrow = objc_exception_extract(&_stack);\n";
751 buf += " else { /* @catch continue */";
752
Chris Lattner28d1fe82007-11-08 04:41:51 +0000753 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000754
755 bool sawIdTypedCatch = false;
756 Stmt *lastCatchBody = 0;
757 ObjcAtCatchStmt *catchList = S->getCatchStmts();
758 while (catchList) {
759 Stmt *catchStmt = catchList->getCatchParamStmt();
760
761 if (catchList == S->getCatchStmts())
762 buf = "if ("; // we are generating code for the first catch clause
763 else
764 buf = "else if (";
765 startLoc = catchList->getLocStart();
766 startBuf = SM->getCharacterData(startLoc);
767
768 assert((*startBuf == '@') && "bogus @catch location");
769
770 const char *lParenLoc = strchr(startBuf, '(');
771
772 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
773 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
774 if (t == Context->getObjcIdType()) {
775 buf += "1) { ";
776 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
777 buf.c_str(), buf.size());
778 sawIdTypedCatch = true;
779 } else if (const PointerType *pType = t->getAsPointerType()) {
780 ObjcInterfaceType *cls; // Should be a pointer to a class.
781
782 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
783 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000784 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000785 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000786 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000787 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
788 buf.c_str(), buf.size());
789 }
790 }
791 // Now rewrite the body...
792 lastCatchBody = catchList->getCatchBody();
793 SourceLocation rParenLoc = catchList->getRParenLoc();
794 SourceLocation bodyLoc = lastCatchBody->getLocStart();
795 const char *bodyBuf = SM->getCharacterData(bodyLoc);
796 const char *rParenBuf = SM->getCharacterData(rParenLoc);
797 assert((*rParenBuf == ')') && "bogus @catch paren location");
798 assert((*bodyBuf == '{') && "bogus @catch body location");
799
800 buf = " = _caught;";
801 // Here we replace ") {" with "= _caught;" (which initializes and
802 // declares the @catch parameter).
803 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
804 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000805 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000806 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000807 }
Steve Naroff75730982007-11-07 04:08:17 +0000808 catchList = catchList->getNextCatchStmt();
809 }
810 // Complete the catch list...
811 if (lastCatchBody) {
812 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
813 const char *bodyBuf = SM->getCharacterData(bodyLoc);
814 assert((*bodyBuf == '}') && "bogus @catch body location");
815 bodyLoc = bodyLoc.getFileLocWithOffset(1);
816 buf = " } } /* @catch end */\n";
817
Chris Lattner28d1fe82007-11-08 04:41:51 +0000818 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000819
820 // Set lastCurlyLoc
821 lastCurlyLoc = lastCatchBody->getLocEnd();
822 }
823 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
824 startLoc = finalStmt->getLocStart();
825 startBuf = SM->getCharacterData(startLoc);
826 assert((*startBuf == '@') && "bogus @finally start");
827
828 buf = "/* @finally */";
829 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
830
831 Stmt *body = finalStmt->getFinallyBody();
832 SourceLocation startLoc = body->getLocStart();
833 SourceLocation endLoc = body->getLocEnd();
834 const char *startBuf = SM->getCharacterData(startLoc);
835 const char *endBuf = SM->getCharacterData(endLoc);
836 assert((*startBuf == '{') && "bogus @finally body location");
837 assert((*endBuf == '}') && "bogus @finally body location");
838
839 startLoc = startLoc.getFileLocWithOffset(1);
840 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000841 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000842 endLoc = endLoc.getFileLocWithOffset(-1);
843 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000844 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000845
846 // Set lastCurlyLoc
847 lastCurlyLoc = body->getLocEnd();
848 }
849 // Now emit the final closing curly brace...
850 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
851 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000852 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000853 return 0;
854}
855
856Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
857 return 0;
858}
859
860Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
861 return 0;
862}
863
Steve Naroff2bd03922007-11-07 15:32:26 +0000864// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
865// the throw expression is typically a message expression that's already
866// been rewritten! (which implies the SourceLocation's are invalid).
867Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
868 // Get the start location and compute the semi location.
869 SourceLocation startLoc = S->getLocStart();
870 const char *startBuf = SM->getCharacterData(startLoc);
871
872 assert((*startBuf == '@') && "bogus @throw location");
873
874 std::string buf;
875 /* void objc_exception_throw(id) __attribute__((noreturn)); */
876 buf = "objc_exception_throw(";
877 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
878 const char *semiBuf = strchr(startBuf, ';');
879 assert((*semiBuf == ';') && "@throw: can't find ';'");
880 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
881 buf = ");";
882 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
883 return 0;
884}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000885
Chris Lattnere64b7772007-10-24 16:57:36 +0000886Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000887 // Create a new string expression.
888 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000889 std::string StrEncoding;
890 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
891 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
892 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000893 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000894 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
895 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000896 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
897 "rewriter could not replace sub-expression due to macros");
898 SourceRange Range = Exp->getSourceRange();
899 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
900 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000901 return Exp;
902 }
903
Chris Lattner07506182007-11-30 22:53:43 +0000904 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000905 delete Exp;
906 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000907}
908
Steve Naroffb42f8412007-11-05 14:50:49 +0000909Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
910 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
911 // Create a call to sel_registerName("selName").
912 llvm::SmallVector<Expr*, 8> SelExprs;
913 QualType argType = Context->getPointerType(Context->CharTy);
914 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
915 Exp->getSelector().getName().size(),
916 false, argType, SourceLocation(),
917 SourceLocation()));
918 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
919 &SelExprs[0], SelExprs.size());
920 Rewrite.ReplaceStmt(Exp, SelExp);
921 delete Exp;
922 return SelExp;
923}
924
Steve Naroff934f2762007-10-24 22:48:43 +0000925CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
926 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000927 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000928 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000929
930 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000931 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000932
933 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000934 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000935 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
936
937 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000938
Steve Naroff934f2762007-10-24 22:48:43 +0000939 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
940}
941
Steve Naroffd5255f52007-11-01 13:24:47 +0000942static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
943 const char *&startRef, const char *&endRef) {
944 while (startBuf < endBuf) {
945 if (*startBuf == '<')
946 startRef = startBuf; // mark the start.
947 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000948 if (startRef && *startRef == '<') {
949 endRef = startBuf; // mark the end.
950 return true;
951 }
952 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000953 }
954 startBuf++;
955 }
956 return false;
957}
958
959bool RewriteTest::needToScanForQualifiers(QualType T) {
960 // FIXME: we don't currently represent "id <Protocol>" in the type system.
961 if (T == Context->getObjcIdType())
962 return true;
963
964 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000965 Type *pointeeType = pType->getPointeeType().getTypePtr();
966 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
967 return true; // we have "Class <Protocol> *".
968 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000969 return false;
970}
971
972void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
973 const FunctionTypeProto *proto, FunctionDecl *FD) {
974
975 if (needToScanForQualifiers(proto->getResultType())) {
976 // Since types are unique, we need to scan the buffer.
977 SourceLocation Loc = FD->getLocation();
978
979 const char *endBuf = SM->getCharacterData(Loc);
980 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +0000981 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +0000982 startBuf--; // scan backward (from the decl location) for return type.
983 const char *startRef = 0, *endRef = 0;
984 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
985 // Get the locations of the startRef, endRef.
986 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
987 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
988 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000989 Rewrite.InsertText(LessLoc, "/*", 2);
990 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000991 }
992 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000993 // Now check arguments.
994 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
995 if (needToScanForQualifiers(proto->getArgType(i))) {
996 // Since types are unique, we need to scan the buffer.
997 SourceLocation Loc = FD->getLocation();
998
999 const char *startBuf = SM->getCharacterData(Loc);
1000 const char *endBuf = startBuf;
1001 while (*endBuf != ';')
1002 endBuf++; // scan forward (from the decl location) for argument types.
1003 const char *startRef = 0, *endRef = 0;
1004 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1005 // Get the locations of the startRef, endRef.
1006 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1007 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1008 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001009 Rewrite.InsertText(LessLoc, "/*", 2);
1010 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001011 }
1012 }
1013 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001014}
1015
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001016// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1017void RewriteTest::SynthSelGetUidFunctionDecl() {
1018 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1019 llvm::SmallVector<QualType, 16> ArgTys;
1020 ArgTys.push_back(Context->getPointerType(
1021 Context->CharTy.getQualifiedType(QualType::Const)));
1022 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1023 &ArgTys[0], ArgTys.size(),
1024 false /*isVariadic*/);
1025 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1026 SelGetUidIdent, getFuncType,
1027 FunctionDecl::Extern, false, 0);
1028}
1029
Steve Naroff09b266e2007-10-30 23:14:51 +00001030void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1031 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001032 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001033 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001034 return;
1035 }
1036 // Check for ObjC 'id' and class types that have been adorned with protocol
1037 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1038 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1039 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +00001040 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1041 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001042}
1043
1044// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1045void RewriteTest::SynthMsgSendFunctionDecl() {
1046 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1047 llvm::SmallVector<QualType, 16> ArgTys;
1048 QualType argT = Context->getObjcIdType();
1049 assert(!argT.isNull() && "Can't find 'id' type");
1050 ArgTys.push_back(argT);
1051 argT = Context->getObjcSelType();
1052 assert(!argT.isNull() && "Can't find 'SEL' type");
1053 ArgTys.push_back(argT);
1054 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1055 &ArgTys[0], ArgTys.size(),
1056 true /*isVariadic*/);
1057 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1058 msgSendIdent, msgSendType,
1059 FunctionDecl::Extern, false, 0);
1060}
1061
Steve Naroff874e2322007-11-15 10:28:18 +00001062// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1063void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1064 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1065 llvm::SmallVector<QualType, 16> ArgTys;
1066 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1067 &Context->Idents.get("objc_super"), 0);
1068 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1069 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1070 ArgTys.push_back(argT);
1071 argT = Context->getObjcSelType();
1072 assert(!argT.isNull() && "Can't find 'SEL' type");
1073 ArgTys.push_back(argT);
1074 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1075 &ArgTys[0], ArgTys.size(),
1076 true /*isVariadic*/);
1077 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1078 msgSendIdent, msgSendType,
1079 FunctionDecl::Extern, false, 0);
1080}
1081
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001082// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1083void RewriteTest::SynthMsgSendStretFunctionDecl() {
1084 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1085 llvm::SmallVector<QualType, 16> ArgTys;
1086 QualType argT = Context->getObjcIdType();
1087 assert(!argT.isNull() && "Can't find 'id' type");
1088 ArgTys.push_back(argT);
1089 argT = Context->getObjcSelType();
1090 assert(!argT.isNull() && "Can't find 'SEL' type");
1091 ArgTys.push_back(argT);
1092 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1093 &ArgTys[0], ArgTys.size(),
1094 true /*isVariadic*/);
1095 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1096 msgSendIdent, msgSendType,
1097 FunctionDecl::Extern, false, 0);
1098}
1099
1100// SynthMsgSendSuperStretFunctionDecl -
1101// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1102void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1103 IdentifierInfo *msgSendIdent =
1104 &Context->Idents.get("objc_msgSendSuper_stret");
1105 llvm::SmallVector<QualType, 16> ArgTys;
1106 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1107 &Context->Idents.get("objc_super"), 0);
1108 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1109 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1110 ArgTys.push_back(argT);
1111 argT = Context->getObjcSelType();
1112 assert(!argT.isNull() && "Can't find 'SEL' type");
1113 ArgTys.push_back(argT);
1114 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1115 &ArgTys[0], ArgTys.size(),
1116 true /*isVariadic*/);
1117 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1118 msgSendIdent, msgSendType,
1119 FunctionDecl::Extern, false, 0);
1120}
1121
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001122// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1123void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1124 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1125 llvm::SmallVector<QualType, 16> ArgTys;
1126 QualType argT = Context->getObjcIdType();
1127 assert(!argT.isNull() && "Can't find 'id' type");
1128 ArgTys.push_back(argT);
1129 argT = Context->getObjcSelType();
1130 assert(!argT.isNull() && "Can't find 'SEL' type");
1131 ArgTys.push_back(argT);
1132 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1133 &ArgTys[0], ArgTys.size(),
1134 true /*isVariadic*/);
1135 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1136 msgSendIdent, msgSendType,
1137 FunctionDecl::Extern, false, 0);
1138}
1139
Steve Naroff09b266e2007-10-30 23:14:51 +00001140// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1141void RewriteTest::SynthGetClassFunctionDecl() {
1142 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1143 llvm::SmallVector<QualType, 16> ArgTys;
1144 ArgTys.push_back(Context->getPointerType(
1145 Context->CharTy.getQualifiedType(QualType::Const)));
1146 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1147 &ArgTys[0], ArgTys.size(),
1148 false /*isVariadic*/);
1149 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1150 getClassIdent, getClassType,
1151 FunctionDecl::Extern, false, 0);
1152}
1153
Steve Naroff96984642007-11-08 14:30:50 +00001154// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1155void RewriteTest::SynthCFStringFunctionDecl() {
1156 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1157 llvm::SmallVector<QualType, 16> ArgTys;
1158 ArgTys.push_back(Context->getPointerType(
1159 Context->CharTy.getQualifiedType(QualType::Const)));
1160 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1161 &ArgTys[0], ArgTys.size(),
1162 false /*isVariadic*/);
1163 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1164 getClassIdent, getClassType,
1165 FunctionDecl::Extern, false, 0);
1166}
1167
Steve Naroffbeaf2992007-11-03 11:27:19 +00001168Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001169#if 1
1170 // This rewrite is specific to GCC, which has builtin support for CFString.
1171 if (!CFStringFunctionDecl)
1172 SynthCFStringFunctionDecl();
1173 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1174 llvm::SmallVector<Expr*, 8> StrExpr;
1175 StrExpr.push_back(Exp->getString());
1176 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1177 &StrExpr[0], StrExpr.size());
1178 // cast to NSConstantString *
1179 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1180 Rewrite.ReplaceStmt(Exp, cast);
1181 delete Exp;
1182 return cast;
1183#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001184 assert(ConstantStringClassReference && "Can't find constant string reference");
1185 llvm::SmallVector<Expr*, 4> InitExprs;
1186
1187 // Synthesize "(Class)&_NSConstantStringClassReference"
1188 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1189 ConstantStringClassReference->getType(),
1190 SourceLocation());
1191 QualType expType = Context->getPointerType(ClsRef->getType());
1192 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1193 expType, SourceLocation());
1194 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1195 SourceLocation());
1196 InitExprs.push_back(cast); // set the 'isa'.
1197 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1198 unsigned IntSize = static_cast<unsigned>(
1199 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1200 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1201 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1202 Exp->getLocStart());
1203 InitExprs.push_back(len); // set "int numBytes".
1204
1205 // struct NSConstantString
1206 QualType CFConstantStrType = Context->getCFConstantStringType();
1207 // (struct NSConstantString) { <exprs from above> }
1208 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1209 &InitExprs[0], InitExprs.size(),
1210 SourceLocation());
1211 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1212 // struct NSConstantString *
1213 expType = Context->getPointerType(StrRep->getType());
1214 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1215 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001216 // cast to NSConstantString *
1217 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001218 Rewrite.ReplaceStmt(Exp, cast);
1219 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001220 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001221#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001222}
1223
Steve Naroff874e2322007-11-15 10:28:18 +00001224ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1225 if (CurMethodDecl) { // check if we are sending a message to 'super'
1226 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1227 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1228 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1229 if (!strcmp(PVD->getName(), "self")) {
1230 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1231 if (ObjcInterfaceType *IT =
1232 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1233 if (IT->getDecl() ==
1234 CurMethodDecl->getClassInterface()->getSuperClass())
1235 return IT->getDecl();
1236 }
1237 }
1238 }
1239 }
1240 }
1241 }
1242 }
1243 return 0;
1244}
1245
1246// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1247QualType RewriteTest::getSuperStructType() {
1248 if (!SuperStructDecl) {
1249 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1250 &Context->Idents.get("objc_super"), 0);
1251 QualType FieldTypes[2];
1252
1253 // struct objc_object *receiver;
1254 FieldTypes[0] = Context->getObjcIdType();
1255 // struct objc_class *super;
1256 FieldTypes[1] = Context->getObjcClassType();
1257 // Create fields
1258 FieldDecl *FieldDecls[2];
1259
1260 for (unsigned i = 0; i < 2; ++i)
1261 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1262
1263 SuperStructDecl->defineBody(FieldDecls, 4);
1264 }
1265 return Context->getTagDeclType(SuperStructDecl);
1266}
1267
Steve Naroff934f2762007-10-24 22:48:43 +00001268Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001269 if (!SelGetUidFunctionDecl)
1270 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001271 if (!MsgSendFunctionDecl)
1272 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001273 if (!MsgSendSuperFunctionDecl)
1274 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001275 if (!MsgSendStretFunctionDecl)
1276 SynthMsgSendStretFunctionDecl();
1277 if (!MsgSendSuperStretFunctionDecl)
1278 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001279 if (!MsgSendFpretFunctionDecl)
1280 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001281 if (!GetClassFunctionDecl)
1282 SynthGetClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001283
Steve Naroff874e2322007-11-15 10:28:18 +00001284 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001285 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1286 // May need to use objc_msgSend_stret() as well.
1287 FunctionDecl *MsgSendStretFlavor = 0;
1288 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1289 QualType resultType = mDecl->getResultType();
1290 if (resultType.getCanonicalType()->isStructureType()
1291 || resultType.getCanonicalType()->isUnionType())
1292 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001293 else if (resultType.getCanonicalType()->isRealFloatingType())
1294 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001295 }
Steve Naroff874e2322007-11-15 10:28:18 +00001296
Steve Naroff934f2762007-10-24 22:48:43 +00001297 // Synthesize a call to objc_msgSend().
1298 llvm::SmallVector<Expr*, 8> MsgExprs;
1299 IdentifierInfo *clsName = Exp->getClassName();
1300
1301 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1302 if (clsName) { // class message.
1303 llvm::SmallVector<Expr*, 8> ClsExprs;
1304 QualType argType = Context->getPointerType(Context->CharTy);
1305 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1306 clsName->getLength(),
1307 false, argType, SourceLocation(),
1308 SourceLocation()));
1309 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1310 &ClsExprs[0], ClsExprs.size());
1311 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001312 } else { // instance message.
1313 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001314
1315 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1316 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001317 if (MsgSendStretFlavor)
1318 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001319 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1320
1321 llvm::SmallVector<Expr*, 4> InitExprs;
1322
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001323 InitExprs.push_back(
1324 new CastExpr(Context->getObjcIdType(),
1325 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001326
1327 llvm::SmallVector<Expr*, 8> ClsExprs;
1328 QualType argType = Context->getPointerType(Context->CharTy);
1329 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1330 ID->getIdentifier()->getLength(),
1331 false, argType, SourceLocation(),
1332 SourceLocation()));
1333 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001334 &ClsExprs[0],
1335 ClsExprs.size());
1336 // To turn off a warning, type-cast to 'Class'
1337 InitExprs.push_back(
1338 new CastExpr(Context->getObjcClassType(),
1339 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001340 // struct objc_super
1341 QualType superType = getSuperStructType();
1342 // (struct objc_super) { <exprs from above> }
1343 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1344 &InitExprs[0], InitExprs.size(),
1345 SourceLocation());
1346 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1347 // struct objc_super *
1348 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1349 Context->getPointerType(SuperRep->getType()),
1350 SourceLocation());
1351 MsgExprs.push_back(Unop);
1352 } else {
1353 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1354 MsgExprs.push_back(recExpr);
1355 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001356 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001357 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001358 llvm::SmallVector<Expr*, 8> SelExprs;
1359 QualType argType = Context->getPointerType(Context->CharTy);
1360 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1361 Exp->getSelector().getName().size(),
1362 false, argType, SourceLocation(),
1363 SourceLocation()));
1364 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1365 &SelExprs[0], SelExprs.size());
1366 MsgExprs.push_back(SelExp);
1367
1368 // Now push any user supplied arguments.
1369 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001370 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001371 // Make all implicit casts explicit...ICE comes in handy:-)
1372 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1373 // Reuse the ICE type, it is exactly what the doctor ordered.
1374 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1375 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001376 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001377 // We've transferred the ownership to MsgExprs. Null out the argument in
1378 // the original expression, since we will delete it below.
1379 Exp->setArg(i, 0);
1380 }
Steve Naroffab972d32007-11-04 22:37:50 +00001381 // Generate the funky cast.
1382 CastExpr *cast;
1383 llvm::SmallVector<QualType, 8> ArgTypes;
1384 QualType returnType;
1385
1386 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001387 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1388 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1389 else
1390 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001391 ArgTypes.push_back(Context->getObjcSelType());
1392 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1393 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001394 for (int i = 0; i < mDecl->getNumParams(); i++) {
1395 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001396 ArgTypes.push_back(t);
1397 }
Steve Naroffab972d32007-11-04 22:37:50 +00001398 returnType = mDecl->getResultType();
1399 } else {
1400 returnType = Context->getObjcIdType();
1401 }
1402 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001403 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001404
1405 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001406 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1407 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001408
1409 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1410 // If we don't do this cast, we get the following bizarre warning/note:
1411 // xx.m:13: warning: function called through a non-compatible type
1412 // xx.m:13: note: if this code is reached, the program will abort
1413 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1414 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001415
Steve Naroffab972d32007-11-04 22:37:50 +00001416 // Now do the "normal" pointer to function cast.
1417 QualType castType = Context->getFunctionType(returnType,
1418 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001419 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001420 castType = Context->getPointerType(castType);
1421 cast = new CastExpr(castType, cast, SourceLocation());
1422
1423 // Don't forget the parens to enforce the proper binding.
1424 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1425
1426 const FunctionType *FT = msgSendType->getAsFunctionType();
1427 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1428 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001429 if (MsgSendStretFlavor) {
1430 // We have the method which returns a struct/union. Must also generate
1431 // call to objc_msgSend_stret and hang both varieties on a conditional
1432 // expression which dictate which one to envoke depending on size of
1433 // method's return type.
1434
1435 // Create a reference to the objc_msgSend_stret() declaration.
1436 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1437 SourceLocation());
1438 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1439 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1440 SourceLocation());
1441 // Now do the "normal" pointer to function cast.
1442 castType = Context->getFunctionType(returnType,
1443 &ArgTypes[0], ArgTypes.size(),
1444 Exp->getMethodDecl()->isVariadic());
1445 castType = Context->getPointerType(castType);
1446 cast = new CastExpr(castType, cast, SourceLocation());
1447
1448 // Don't forget the parens to enforce the proper binding.
1449 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1450
1451 FT = msgSendType->getAsFunctionType();
1452 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1453 FT->getResultType(), SourceLocation());
1454
1455 // Build sizeof(returnType)
1456 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1457 returnType, Context->getSizeType(),
1458 SourceLocation(), SourceLocation());
1459 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1460 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1461 // For X86 it is more complicated and some kind of target specific routine
1462 // is needed to decide what to do.
1463 unsigned IntSize = static_cast<unsigned>(
1464 Context->getTypeSize(Context->IntTy, SourceLocation()));
1465
1466 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1467 Context->IntTy,
1468 SourceLocation());
1469 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1470 BinaryOperator::LE,
1471 Context->IntTy,
1472 SourceLocation());
1473 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1474 ConditionalOperator *CondExpr =
1475 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1476 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1477 // Now do the actual rewrite.
1478 Rewrite.ReplaceStmt(Exp, PE);
1479 delete Exp;
1480 return PE;
1481 }
Steve Naroff934f2762007-10-24 22:48:43 +00001482 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001483 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001484
Chris Lattnere64b7772007-10-24 16:57:36 +00001485 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001486 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001487}
1488
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001489/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1490/// an objective-c class with ivars.
1491void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1492 std::string &Result) {
1493 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1494 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001495 // Do not synthesize more than once.
1496 if (ObjcSynthesizedStructs.count(CDecl))
1497 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001498 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001499 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001500 SourceLocation LocStart = CDecl->getLocStart();
1501 SourceLocation LocEnd = CDecl->getLocEnd();
1502
1503 const char *startBuf = SM->getCharacterData(LocStart);
1504 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001505 // If no ivars and no root or if its root, directly or indirectly,
1506 // have no ivars (thus not synthesized) then no need to synthesize this class.
1507 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001508 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1509 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1510 Result.c_str(), Result.size());
1511 return;
1512 }
1513
1514 // FIXME: This has potential of causing problem. If
1515 // SynthesizeObjcInternalStruct is ever called recursively.
1516 Result += "\nstruct ";
1517 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001518
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001519 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001520 const char *cursor = strchr(startBuf, '{');
1521 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001522 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001523
1524 // rewrite the original header *without* disturbing the '{'
1525 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1526 Result.c_str(), Result.size());
1527 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1528 Result = "\n struct ";
1529 Result += RCDecl->getName();
1530 Result += " _";
1531 Result += RCDecl->getName();
1532 Result += ";\n";
1533
1534 // insert the super class structure definition.
1535 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1536 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1537 }
1538 cursor++; // past '{'
1539
1540 // Now comment out any visibility specifiers.
1541 while (cursor < endBuf) {
1542 if (*cursor == '@') {
1543 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001544 // Skip whitespace.
1545 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1546 /*scan*/;
1547
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001548 // FIXME: presence of @public, etc. inside comment results in
1549 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001550 if (!strncmp(cursor, "public", strlen("public")) ||
1551 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001552 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001553 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001554 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001555 // FIXME: If there are cases where '<' is used in ivar declaration part
1556 // of user code, then scan the ivar list and use needToScanForQualifiers
1557 // for type checking.
1558 else if (*cursor == '<') {
1559 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1560 Rewrite.InsertText(atLoc, "/* ", 3);
1561 cursor = strchr(cursor, '>');
1562 cursor++;
1563 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1564 Rewrite.InsertText(atLoc, " */", 3);
1565 }
Steve Narofffea763e82007-11-14 19:25:57 +00001566 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001567 }
Steve Narofffea763e82007-11-14 19:25:57 +00001568 // Don't forget to add a ';'!!
1569 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1570 } else { // we don't have any instance variables - insert super struct.
1571 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1572 Result += " {\n struct ";
1573 Result += RCDecl->getName();
1574 Result += " _";
1575 Result += RCDecl->getName();
1576 Result += ";\n};\n";
1577 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1578 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001579 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001580 // Mark this struct as having been generated.
1581 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001582 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001583}
1584
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001585// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1586/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001587void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001588 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001589 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001590 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001591 const char *ClassName,
1592 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001593 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001594 if (NumMethods > 0 && !objc_impl_method) {
1595 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001596 SEL _cmd;
1597 char *method_types;
1598 void *_imp;
1599 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001600 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001601 Result += "\nstruct _objc_method {\n";
1602 Result += "\tSEL _cmd;\n";
1603 Result += "\tchar *method_types;\n";
1604 Result += "\tvoid *_imp;\n";
1605 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001606
1607 /* struct _objc_method_list {
1608 struct _objc_method_list *next_method;
1609 int method_count;
1610 struct _objc_method method_list[];
1611 }
1612 */
1613 Result += "\nstruct _objc_method_list {\n";
1614 Result += "\tstruct _objc_method_list *next_method;\n";
1615 Result += "\tint method_count;\n";
1616 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001617 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001618 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001619 // Build _objc_method_list for class's methods if needed
1620 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001621 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001622 Result += prefix;
1623 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1624 Result += "_METHODS_";
1625 Result += ClassName;
1626 Result += " __attribute__ ((section (\"__OBJC, __";
1627 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001628 Result += "_meth\")))= ";
1629 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1630
1631 Result += "\t,{{(SEL)\"";
1632 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001633 std::string MethodTypeString;
1634 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1635 Result += "\", \"";
1636 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001637 Result += "\", ";
1638 Result += MethodInternalNames[Methods[0]];
1639 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001640 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001641 Result += "\t ,{(SEL)\"";
1642 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001643 std::string MethodTypeString;
1644 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1645 Result += "\", \"";
1646 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001647 Result += "\", ";
1648 Result += MethodInternalNames[Methods[i]];
1649 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001650 }
1651 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001652 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001653}
1654
1655/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1656void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1657 int NumProtocols,
1658 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001659 const char *ClassName,
1660 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001661 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001662 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001663 for (int i = 0; i < NumProtocols; i++) {
1664 ObjcProtocolDecl *PDecl = Protocols[i];
1665 // Output struct protocol_methods holder of method selector and type.
1666 if (!objc_protocol_methods &&
1667 (PDecl->getNumInstanceMethods() > 0
1668 || PDecl->getNumClassMethods() > 0)) {
1669 /* struct protocol_methods {
1670 SEL _cmd;
1671 char *method_types;
1672 }
1673 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001674 Result += "\nstruct protocol_methods {\n";
1675 Result += "\tSEL _cmd;\n";
1676 Result += "\tchar *method_types;\n";
1677 Result += "};\n";
1678
1679 /* struct _objc_protocol_method_list {
1680 int protocol_method_count;
1681 struct protocol_methods protocols[];
1682 }
1683 */
1684 Result += "\nstruct _objc_protocol_method_list {\n";
1685 Result += "\tint protocol_method_count;\n";
1686 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001687 objc_protocol_methods = true;
1688 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001689
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001690 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001691 int NumMethods = PDecl->getNumInstanceMethods();
1692 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001693 Result += "\nstatic struct _objc_protocol_method_list "
1694 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1695 Result += PDecl->getName();
1696 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1697 "{\n\t" + utostr(NumMethods) + "\n";
1698
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001699 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001700 Result += "\t,{{(SEL)\"";
1701 Result += Methods[0]->getSelector().getName().c_str();
1702 Result += "\", \"\"}\n";
1703
1704 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001705 Result += "\t ,{(SEL)\"";
1706 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001707 std::string MethodTypeString;
1708 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1709 Result += "\", \"";
1710 Result += MethodTypeString;
1711 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001712 }
1713 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001714 }
1715
1716 // Output class methods declared in this protocol.
1717 NumMethods = PDecl->getNumClassMethods();
1718 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001719 Result += "\nstatic struct _objc_protocol_method_list "
1720 "_OBJC_PROTOCOL_CLASS_METHODS_";
1721 Result += PDecl->getName();
1722 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1723 "{\n\t";
1724 Result += utostr(NumMethods);
1725 Result += "\n";
1726
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001727 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001728 Result += "\t,{{(SEL)\"";
1729 Result += Methods[0]->getSelector().getName().c_str();
1730 Result += "\", \"\"}\n";
1731
1732 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001733 Result += "\t ,{(SEL)\"";
1734 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001735 std::string MethodTypeString;
1736 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1737 Result += "\", \"";
1738 Result += MethodTypeString;
1739 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001740 }
1741 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001742 }
1743 // Output:
1744 /* struct _objc_protocol {
1745 // Objective-C 1.0 extensions
1746 struct _objc_protocol_extension *isa;
1747 char *protocol_name;
1748 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001749 struct _objc_protocol_method_list *instance_methods;
1750 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001751 };
1752 */
1753 static bool objc_protocol = false;
1754 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001755 Result += "\nstruct _objc_protocol {\n";
1756 Result += "\tstruct _objc_protocol_extension *isa;\n";
1757 Result += "\tchar *protocol_name;\n";
1758 Result += "\tstruct _objc_protocol **protocol_list;\n";
1759 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1760 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1761 Result += "};\n";
1762
1763 /* struct _objc_protocol_list {
1764 struct _objc_protocol_list *next;
1765 int protocol_count;
1766 struct _objc_protocol *class_protocols[];
1767 }
1768 */
1769 Result += "\nstruct _objc_protocol_list {\n";
1770 Result += "\tstruct _objc_protocol_list *next;\n";
1771 Result += "\tint protocol_count;\n";
1772 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1773 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001774 objc_protocol = true;
1775 }
1776
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001777 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1778 Result += PDecl->getName();
1779 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1780 "{\n\t0, \"";
1781 Result += PDecl->getName();
1782 Result += "\", 0, ";
1783 if (PDecl->getInstanceMethods() > 0) {
1784 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1785 Result += PDecl->getName();
1786 Result += ", ";
1787 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001788 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001789 Result += "0, ";
1790 if (PDecl->getClassMethods() > 0) {
1791 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1792 Result += PDecl->getName();
1793 Result += "\n";
1794 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001795 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001796 Result += "0\n";
1797 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001798 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001799 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001800 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1801 Result += prefix;
1802 Result += "_PROTOCOLS_";
1803 Result += ClassName;
1804 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1805 "{\n\t0, ";
1806 Result += utostr(NumProtocols);
1807 Result += "\n";
1808
1809 Result += "\t,{&_OBJC_PROTOCOL_";
1810 Result += Protocols[0]->getName();
1811 Result += " \n";
1812
1813 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001814 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001815 Result += "\t ,&_OBJC_PROTOCOL_";
1816 Result += PDecl->getName();
1817 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001818 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001820 }
1821}
1822
1823/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1824/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001825void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1826 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001827 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1828 // Find category declaration for this implementation.
1829 ObjcCategoryDecl *CDecl;
1830 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1831 CDecl = CDecl->getNextClassCategory())
1832 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1833 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001834
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001835 char *FullCategoryName = (char*)alloca(
1836 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1837 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1838
1839 // Build _objc_method_list for class's instance methods if needed
1840 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1841 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001842 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001843 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001844
1845 // Build _objc_method_list for class's class methods if needed
1846 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1847 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001848 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001849 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001850
1851 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001852 // Null CDecl is case of a category implementation with no category interface
1853 if (CDecl)
1854 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1855 CDecl->getNumReferencedProtocols(),
1856 "CATEGORY",
1857 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001858
1859 /* struct _objc_category {
1860 char *category_name;
1861 char *class_name;
1862 struct _objc_method_list *instance_methods;
1863 struct _objc_method_list *class_methods;
1864 struct _objc_protocol_list *protocols;
1865 // Objective-C 1.0 extensions
1866 uint32_t size; // sizeof (struct _objc_category)
1867 struct _objc_property_list *instance_properties; // category's own
1868 // @property decl.
1869 };
1870 */
1871
1872 static bool objc_category = false;
1873 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001874 Result += "\nstruct _objc_category {\n";
1875 Result += "\tchar *category_name;\n";
1876 Result += "\tchar *class_name;\n";
1877 Result += "\tstruct _objc_method_list *instance_methods;\n";
1878 Result += "\tstruct _objc_method_list *class_methods;\n";
1879 Result += "\tstruct _objc_protocol_list *protocols;\n";
1880 Result += "\tunsigned int size;\n";
1881 Result += "\tstruct _objc_property_list *instance_properties;\n";
1882 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001883 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001884 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001885 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1886 Result += FullCategoryName;
1887 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1888 Result += IDecl->getName();
1889 Result += "\"\n\t, \"";
1890 Result += ClassDecl->getName();
1891 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001892
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001893 if (IDecl->getNumInstanceMethods() > 0) {
1894 Result += "\t, (struct _objc_method_list *)"
1895 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1896 Result += FullCategoryName;
1897 Result += "\n";
1898 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001899 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001900 Result += "\t, 0\n";
1901 if (IDecl->getNumClassMethods() > 0) {
1902 Result += "\t, (struct _objc_method_list *)"
1903 "&_OBJC_CATEGORY_CLASS_METHODS_";
1904 Result += FullCategoryName;
1905 Result += "\n";
1906 }
1907 else
1908 Result += "\t, 0\n";
1909
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001910 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001911 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1912 Result += FullCategoryName;
1913 Result += "\n";
1914 }
1915 else
1916 Result += "\t, 0\n";
1917 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001918}
1919
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001920/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1921/// ivar offset.
1922void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1923 ObjcIvarDecl *ivar,
1924 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001925 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001926 Result += IDecl->getName();
1927 Result += ", ";
1928 Result += ivar->getName();
1929 Result += ")";
1930}
1931
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001932//===----------------------------------------------------------------------===//
1933// Meta Data Emission
1934//===----------------------------------------------------------------------===//
1935
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001936void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1937 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001938 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1939
1940 // Build _objc_ivar_list metadata for classes ivars if needed
1941 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1942 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001943 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00001944 // Explictly declared @interface's are already synthesized.
1945 if (CDecl->ImplicitInterfaceDecl()) {
1946 // FIXME: Implementation of a class with no @interface (legacy) doese not
1947 // produce correct synthesis as yet.
1948 SynthesizeObjcInternalStruct(CDecl, Result);
1949 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001950
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001951 if (NumIvars > 0) {
1952 static bool objc_ivar = false;
1953 if (!objc_ivar) {
1954 /* struct _objc_ivar {
1955 char *ivar_name;
1956 char *ivar_type;
1957 int ivar_offset;
1958 };
1959 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001960 Result += "\nstruct _objc_ivar {\n";
1961 Result += "\tchar *ivar_name;\n";
1962 Result += "\tchar *ivar_type;\n";
1963 Result += "\tint ivar_offset;\n";
1964 Result += "};\n";
1965
1966 /* struct _objc_ivar_list {
1967 int ivar_count;
1968 struct _objc_ivar ivar_list[];
1969 };
1970 */
1971 Result += "\nstruct _objc_ivar_list {\n";
1972 Result += "\tint ivar_count;\n";
1973 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001974 objc_ivar = true;
1975 }
1976
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001977 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1978 Result += IDecl->getName();
1979 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1980 "{\n\t";
1981 Result += utostr(NumIvars);
1982 Result += "\n";
1983
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001984 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1985 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001986 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001987 Result += "\t,{{\"";
1988 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001989 Result += "\", \"";
1990 std::string StrEncoding;
1991 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1992 Result += StrEncoding;
1993 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001994 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1995 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001996 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001997 Result += "\t ,{\"";
1998 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001999 Result += "\", \"";
2000 std::string StrEncoding;
2001 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2002 Result += StrEncoding;
2003 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002004 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2005 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002006 }
2007
2008 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002009 }
2010
2011 // Build _objc_method_list for class's instance methods if needed
2012 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2013 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002014 true,
2015 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002016
2017 // Build _objc_method_list for class's class methods if needed
2018 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002019 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002020 false,
2021 "", IDecl->getName(), Result);
2022
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002023 // Protocols referenced in class declaration?
2024 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2025 CDecl->getNumIntfRefProtocols(),
2026 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002027 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002028
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002029
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002030 // Declaration of class/meta-class metadata
2031 /* struct _objc_class {
2032 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002033 const char *super_class_name;
2034 char *name;
2035 long version;
2036 long info;
2037 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002038 struct _objc_ivar_list *ivars;
2039 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002040 struct objc_cache *cache;
2041 struct objc_protocol_list *protocols;
2042 const char *ivar_layout;
2043 struct _objc_class_ext *ext;
2044 };
2045 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002046 static bool objc_class = false;
2047 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002048 Result += "\nstruct _objc_class {\n";
2049 Result += "\tstruct _objc_class *isa;\n";
2050 Result += "\tconst char *super_class_name;\n";
2051 Result += "\tchar *name;\n";
2052 Result += "\tlong version;\n";
2053 Result += "\tlong info;\n";
2054 Result += "\tlong instance_size;\n";
2055 Result += "\tstruct _objc_ivar_list *ivars;\n";
2056 Result += "\tstruct _objc_method_list *methods;\n";
2057 Result += "\tstruct objc_cache *cache;\n";
2058 Result += "\tstruct _objc_protocol_list *protocols;\n";
2059 Result += "\tconst char *ivar_layout;\n";
2060 Result += "\tstruct _objc_class_ext *ext;\n";
2061 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002062 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002063 }
2064
2065 // Meta-class metadata generation.
2066 ObjcInterfaceDecl *RootClass = 0;
2067 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2068 while (SuperClass) {
2069 RootClass = SuperClass;
2070 SuperClass = SuperClass->getSuperClass();
2071 }
2072 SuperClass = CDecl->getSuperClass();
2073
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002074 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2075 Result += CDecl->getName();
2076 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2077 "{\n\t(struct _objc_class *)\"";
2078 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2079 Result += "\"";
2080
2081 if (SuperClass) {
2082 Result += ", \"";
2083 Result += SuperClass->getName();
2084 Result += "\", \"";
2085 Result += CDecl->getName();
2086 Result += "\"";
2087 }
2088 else {
2089 Result += ", 0, \"";
2090 Result += CDecl->getName();
2091 Result += "\"";
2092 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002093 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002094 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002095 Result += ", 0,2, sizeof(struct _objc_class), 0";
2096 if (CDecl->getNumClassMethods() > 0) {
2097 Result += "\n\t, &_OBJC_CLASS_METHODS_";
2098 Result += CDecl->getName();
2099 Result += "\n";
2100 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002101 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002102 Result += ", 0\n";
2103 if (CDecl->getNumIntfRefProtocols() > 0) {
2104 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2105 Result += CDecl->getName();
2106 Result += ",0,0\n";
2107 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002108 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002109 Result += "\t,0,0,0,0\n";
2110 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002111
2112 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002113 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2114 Result += CDecl->getName();
2115 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2116 "{\n\t&_OBJC_METACLASS_";
2117 Result += CDecl->getName();
2118 if (SuperClass) {
2119 Result += ", \"";
2120 Result += SuperClass->getName();
2121 Result += "\", \"";
2122 Result += CDecl->getName();
2123 Result += "\"";
2124 }
2125 else {
2126 Result += ", 0, \"";
2127 Result += CDecl->getName();
2128 Result += "\"";
2129 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002130 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002131 Result += ", 0,1";
2132 if (!ObjcSynthesizedStructs.count(CDecl))
2133 Result += ",0";
2134 else {
2135 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002136 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002137 Result += CDecl->getName();
2138 Result += ")";
2139 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002140 if (NumIvars > 0) {
2141 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2142 Result += CDecl->getName();
2143 Result += "\n\t";
2144 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002145 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002146 Result += ",0";
2147 if (IDecl->getNumInstanceMethods() > 0) {
2148 Result += ", &_OBJC_INSTANCE_METHODS_";
2149 Result += CDecl->getName();
2150 Result += ", 0\n\t";
2151 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002152 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002153 Result += ",0,0";
2154 if (CDecl->getNumIntfRefProtocols() > 0) {
2155 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2156 Result += CDecl->getName();
2157 Result += ", 0,0\n";
2158 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002159 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002160 Result += ",0,0,0\n";
2161 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002162}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002163
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002164/// RewriteImplementations - This routine rewrites all method implementations
2165/// and emits meta-data.
2166
2167void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002168 int ClsDefCount = ClassImplementation.size();
2169 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002170
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002171 if (ClsDefCount == 0 && CatDefCount == 0)
2172 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002173 // Rewrite implemented methods
2174 for (int i = 0; i < ClsDefCount; i++)
2175 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002176
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002177 for (int i = 0; i < CatDefCount; i++)
2178 RewriteImplementationDecl(CategoryImplementation[i]);
2179
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002180 // This is needed for use of offsetof
2181 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002182
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002183 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002184 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002185 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002186
2187 // For each implemented category, write out all its meta data.
2188 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002189 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002190
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002191 // Write objc_symtab metadata
2192 /*
2193 struct _objc_symtab
2194 {
2195 long sel_ref_cnt;
2196 SEL *refs;
2197 short cls_def_cnt;
2198 short cat_def_cnt;
2199 void *defs[cls_def_cnt + cat_def_cnt];
2200 };
2201 */
2202
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002203 Result += "\nstruct _objc_symtab {\n";
2204 Result += "\tlong sel_ref_cnt;\n";
2205 Result += "\tSEL *refs;\n";
2206 Result += "\tshort cls_def_cnt;\n";
2207 Result += "\tshort cat_def_cnt;\n";
2208 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2209 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002210
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002211 Result += "static struct _objc_symtab "
2212 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2213 Result += "\t0, 0, " + utostr(ClsDefCount)
2214 + ", " + utostr(CatDefCount) + "\n";
2215 for (int i = 0; i < ClsDefCount; i++) {
2216 Result += "\t,&_OBJC_CLASS_";
2217 Result += ClassImplementation[i]->getName();
2218 Result += "\n";
2219 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002220
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002221 for (int i = 0; i < CatDefCount; i++) {
2222 Result += "\t,&_OBJC_CATEGORY_";
2223 Result += CategoryImplementation[i]->getClassInterface()->getName();
2224 Result += "_";
2225 Result += CategoryImplementation[i]->getName();
2226 Result += "\n";
2227 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002228
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002229 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002230
2231 // Write objc_module metadata
2232
2233 /*
2234 struct _objc_module {
2235 long version;
2236 long size;
2237 const char *name;
2238 struct _objc_symtab *symtab;
2239 }
2240 */
2241
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002242 Result += "\nstruct _objc_module {\n";
2243 Result += "\tlong version;\n";
2244 Result += "\tlong size;\n";
2245 Result += "\tconst char *name;\n";
2246 Result += "\tstruct _objc_symtab *symtab;\n";
2247 Result += "};\n\n";
2248 Result += "static struct _objc_module "
2249 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002250 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2251 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002252 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002253
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002254}
Chris Lattner311ff022007-10-16 22:36:42 +00002255