blob: 88ac5a47be9065d05427e24ee16b721a65f0f52b [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;
Steve Naroffebf2b562007-10-23 23:50:29 +000048 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000049 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000050 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000051
Steve Naroffbeaf2992007-11-03 11:27:19 +000052 // ObjC string constant support.
53 FileVarDecl *ConstantStringClassReference;
54 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000055
Steve Naroff874e2322007-11-15 10:28:18 +000056 // Needed for super.
57 ObjcMethodDecl *CurMethodDecl;
58 RecordDecl *SuperStructDecl;
59
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000060 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000061 public:
Chris Lattner01c57482007-10-17 22:35:30 +000062 void Initialize(ASTContext &context, unsigned mainFileID) {
63 Context = &context;
64 SM = &Context->SourceMgr;
Steve Naroffebf2b562007-10-23 23:50:29 +000065 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000066 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 MsgSendStretFunctionDecl = 0;
68 MsgSendSuperStretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000069 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000070 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000071 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000072 ConstantStringClassReference = 0;
73 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000074 CurMethodDecl = 0;
75 SuperStructDecl = 0;
76
Chris Lattner26de4652007-12-02 01:13:47 +000077 // Get the ID and start/end of the main file.
78 MainFileID = mainFileID;
79 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
80 MainFileStart = MainBuf->getBufferStart();
81 MainFileEnd = MainBuf->getBufferEnd();
82
83
Chris Lattner01c57482007-10-17 22:35:30 +000084 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000085 // declaring objc_selector outside the parameter list removes a silly
86 // scope related warning...
Steve Narofff6248702007-11-15 17:06:21 +000087 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000088 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000089 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000090 "extern struct objc_object *objc_msgSendSuper"
91 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000092 "extern struct objc_object *objc_msgSend_stret"
93 "(struct objc_object *, struct objc_selector *, ...);\n"
94 "extern struct objc_object *objc_msgSendSuper_stret"
95 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +000096 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000097 "(const char *);\n"
98 "extern void objc_exception_throw(struct objc_object *);\n"
99 "extern void objc_exception_try_enter(void *);\n"
100 "extern void objc_exception_try_exit(void *);\n"
101 "extern struct objc_object *objc_exception_extract(void *);\n"
102 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000103 "(struct objc_class *, struct objc_object *, ...);\n"
104 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000105
Steve Naroffab972d32007-11-04 22:37:50 +0000106 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
107 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000108 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000109
Chris Lattnerf04da132007-10-24 17:06:59 +0000110 // Top Level Driver code.
111 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000112 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000113 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000114 ~RewriteTest();
115
116 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000117 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000118 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 void RewriteTabs();
120 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000121 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000122 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000123 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000124 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000125 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000126 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000127 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000128 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000129 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000130 void RewriteObjcQualifiedInterfaceTypes(
131 const FunctionTypeProto *proto, FunctionDecl *FD);
132 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000133 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
134 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000135
Chris Lattnerf04da132007-10-24 17:06:59 +0000136 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000137 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000138 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000139 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000140 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000141 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000142 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000143 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
144 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
145 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000146 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000147 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
148 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000150 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000151 void SynthMsgSendStretFunctionDecl();
152 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000153 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000154 void SynthCFStringFunctionDecl();
155
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000157 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
158 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000160 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
161 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000162
Steve Naroff0416fb92007-11-11 17:19:15 +0000163 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000164 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000165 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000166 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000167 const char *ClassName,
168 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000169
170 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
171 int NumProtocols,
172 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000173 const char *ClassName,
174 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000175 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
176 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000177 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
178 ObjcIvarDecl *ivar,
179 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000180 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000181 };
182}
183
Chris Lattnere365c502007-11-30 22:25:36 +0000184ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
185 return new RewriteTest(Diags);
186}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000187
Chris Lattnerf04da132007-10-24 17:06:59 +0000188//===----------------------------------------------------------------------===//
189// Top Level Driver Code
190//===----------------------------------------------------------------------===//
191
Chris Lattner8a12c272007-10-11 18:38:32 +0000192void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000193 // Two cases: either the decl could be in the main file, or it could be in a
194 // #included file. If the former, rewrite it now. If the later, check to see
195 // if we rewrote the #include/#import.
196 SourceLocation Loc = D->getLocation();
197 Loc = SM->getLogicalLoc(Loc);
198
199 // If this is for a builtin, ignore it.
200 if (Loc.isInvalid()) return;
201
Steve Naroffebf2b562007-10-23 23:50:29 +0000202 // Look for built-in declarations that we need to refer during the rewrite.
203 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000204 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000205 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
206 // declared in <Foundation/NSString.h>
207 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
208 ConstantStringClassReference = FVD;
209 return;
210 }
Steve Naroffbef11852007-10-26 20:53:56 +0000211 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
212 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000213 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
214 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000215 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
216 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000217 } else if (ObjcForwardProtocolDecl *FP =
218 dyn_cast<ObjcForwardProtocolDecl>(D)){
219 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000220 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000222 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
223 return HandleDeclInMainFile(D);
224
Chris Lattnerf04da132007-10-24 17:06:59 +0000225 // Otherwise, see if there is a #import in the main file that should be
226 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000227 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000228}
229
Chris Lattnerf04da132007-10-24 17:06:59 +0000230/// HandleDeclInMainFile - This is called for each top-level decl defined in the
231/// main file of the input.
232void RewriteTest::HandleDeclInMainFile(Decl *D) {
233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
234 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000235 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000236
237 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000238 if (Stmt *Body = MD->getBody()) {
239 //Body->dump();
240 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000241 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000242 CurMethodDecl = 0;
243 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000244 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
246 ClassImplementation.push_back(CI);
247 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
248 CategoryImplementation.push_back(CI);
249 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
250 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000251 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
252 if (VD->getInit())
253 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
254 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000255 // Nothing yet.
256}
257
258RewriteTest::~RewriteTest() {
259 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000260
261 // Rewrite tabs if we care.
262 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000263
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000264 // Rewrite Objective-c meta data*
265 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000266 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000267
Chris Lattnerf04da132007-10-24 17:06:59 +0000268 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
269 // we are done.
270 if (const RewriteBuffer *RewriteBuf =
271 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000272 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 std::string S(RewriteBuf->begin(), RewriteBuf->end());
274 printf("%s\n", S.c_str());
275 } else {
276 printf("No changes\n");
277 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000278 // Emit metadata.
279 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000280}
281
Chris Lattnerf04da132007-10-24 17:06:59 +0000282//===----------------------------------------------------------------------===//
283// Syntactic (non-AST) Rewriting Code
284//===----------------------------------------------------------------------===//
285
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000286void RewriteTest::RewriteInclude(SourceLocation Loc) {
287 // Rip up the #include stack to the main file.
288 SourceLocation IncLoc = Loc, NextLoc = Loc;
289 do {
290 IncLoc = Loc;
291 Loc = SM->getLogicalLoc(NextLoc);
292 NextLoc = SM->getIncludeLoc(Loc);
293 } while (!NextLoc.isInvalid());
294
295 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
296 // IncLoc indicates the header that was included if it is useful.
297 IncLoc = SM->getLogicalLoc(IncLoc);
298 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
299 Loc == LastIncLoc)
300 return;
301 LastIncLoc = Loc;
302
303 unsigned IncCol = SM->getColumnNumber(Loc);
304 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
305
306 // Replace the #import with #include.
307 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
308}
309
Chris Lattnerf04da132007-10-24 17:06:59 +0000310void RewriteTest::RewriteTabs() {
311 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
312 const char *MainBufStart = MainBuf.first;
313 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000314
Chris Lattnerf04da132007-10-24 17:06:59 +0000315 // Loop over the whole file, looking for tabs.
316 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
317 if (*BufPtr != '\t')
318 continue;
319
320 // Okay, we found a tab. This tab will turn into at least one character,
321 // but it depends on which 'virtual column' it is in. Compute that now.
322 unsigned VCol = 0;
323 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
324 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
325 ++VCol;
326
327 // Okay, now that we know the virtual column, we know how many spaces to
328 // insert. We assume 8-character tab-stops.
329 unsigned Spaces = 8-(VCol & 7);
330
331 // Get the location of the tab.
332 SourceLocation TabLoc =
333 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
334
335 // Rewrite the single tab character into a sequence of spaces.
336 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
337 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000338}
339
340
Chris Lattnerf04da132007-10-24 17:06:59 +0000341void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
342 int numDecls = ClassDecl->getNumForwardDecls();
343 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
344
345 // Get the start location and compute the semi location.
346 SourceLocation startLoc = ClassDecl->getLocation();
347 const char *startBuf = SM->getCharacterData(startLoc);
348 const char *semiPtr = strchr(startBuf, ';');
349
350 // Translate to typedef's that forward reference structs with the same name
351 // as the class. As a convenience, we include the original declaration
352 // as a comment.
353 std::string typedefString;
354 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000355 typedefString.append(startBuf, semiPtr-startBuf+1);
356 typedefString += "\n";
357 for (int i = 0; i < numDecls; i++) {
358 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000359 typedefString += "#ifndef _REWRITER_typedef_";
360 typedefString += ForwardDecl->getName();
361 typedefString += "\n";
362 typedefString += "#define _REWRITER_typedef_";
363 typedefString += ForwardDecl->getName();
364 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000365 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000366 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000367 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000368 }
369
370 // Replace the @class with typedefs corresponding to the classes.
371 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
372 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000373}
374
Steve Naroff71c0a952007-11-13 23:01:27 +0000375void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000376 for (int i = 0; i < nMethods; i++) {
377 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000378 SourceLocation LocStart = Method->getLocStart();
379 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000380
Steve Naroff1d098f62007-11-14 14:34:23 +0000381 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
382 Rewrite.InsertText(LocStart, "/* ", 3);
383 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
384 } else {
385 Rewrite.InsertText(LocStart, "// ", 3);
386 }
Steve Naroff423cb562007-10-30 13:30:57 +0000387 }
388}
389
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000390void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
391{
392 for (int i = 0; i < nProperties; i++) {
393 ObjcPropertyDecl *Property = Properties[i];
394 SourceLocation Loc = Property->getLocation();
395
396 Rewrite.ReplaceText(Loc, 0, "// ", 3);
397
398 // FIXME: handle properties that are declared across multiple lines.
399 }
400}
401
Steve Naroff423cb562007-10-30 13:30:57 +0000402void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
403 SourceLocation LocStart = CatDecl->getLocStart();
404
405 // FIXME: handle category headers that are declared across multiple lines.
406 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
407
Steve Naroff71c0a952007-11-13 23:01:27 +0000408 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
409 CatDecl->getInstanceMethods());
410 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
411 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000412 // Lastly, comment out the @end.
413 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
414}
415
Steve Naroff752d6ef2007-10-30 16:42:30 +0000416void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000417 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000418
Steve Naroff752d6ef2007-10-30 16:42:30 +0000419 SourceLocation LocStart = PDecl->getLocStart();
420
421 // FIXME: handle protocol headers that are declared across multiple lines.
422 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
423
Steve Naroff71c0a952007-11-13 23:01:27 +0000424 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
425 PDecl->getInstanceMethods());
426 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
427 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000428 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000429 SourceLocation LocEnd = PDecl->getAtEndLoc();
430 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000431
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000432 // Must comment out @optional/@required
433 const char *startBuf = SM->getCharacterData(LocStart);
434 const char *endBuf = SM->getCharacterData(LocEnd);
435 for (const char *p = startBuf; p < endBuf; p++) {
436 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
437 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000438 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000439 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
440 CommentedOptional.c_str(), CommentedOptional.size());
441
442 }
443 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
444 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000445 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000446 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
447 CommentedRequired.c_str(), CommentedRequired.size());
448
449 }
450 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000451}
452
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000453void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
454 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000455 if (LocStart.isInvalid())
456 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000457 // FIXME: handle forward protocol that are declared across multiple lines.
458 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
459}
460
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000461void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
462 std::string &ResultStr) {
463 ResultStr += "\nstatic ";
464 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000465 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000466
467 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000468 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000469
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000470 if (OMD->isInstance())
471 NameStr += "_I_";
472 else
473 NameStr += "_C_";
474
475 NameStr += OMD->getClassInterface()->getName();
476 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000477
478 NamedDecl *MethodContext = OMD->getMethodContext();
479 if (ObjcCategoryImplDecl *CID =
480 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000481 NameStr += CID->getName();
482 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000483 }
484 // Append selector names, replacing ':' with '_'
485 const char *selName = OMD->getSelector().getName().c_str();
486 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000487 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000488 else {
489 std::string selString = OMD->getSelector().getName();
490 int len = selString.size();
491 for (int i = 0; i < len; i++)
492 if (selString[i] == ':')
493 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000494 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000495 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000496 // Remember this name for metadata emission
497 MethodInternalNames[OMD] = NameStr;
498 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000499
500 // Rewrite arguments
501 ResultStr += "(";
502
503 // invisible arguments
504 if (OMD->isInstance()) {
505 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
506 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000507 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
508 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509 ResultStr += selfTy.getAsString();
510 }
511 else
512 ResultStr += Context->getObjcIdType().getAsString();
513
514 ResultStr += " self, ";
515 ResultStr += Context->getObjcSelType().getAsString();
516 ResultStr += " _cmd";
517
518 // Method arguments.
519 for (int i = 0; i < OMD->getNumParams(); i++) {
520 ParmVarDecl *PDecl = OMD->getParamDecl(i);
521 ResultStr += ", ";
522 ResultStr += PDecl->getType().getAsString();
523 ResultStr += " ";
524 ResultStr += PDecl->getName();
525 }
526 ResultStr += ")";
527
528}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000529void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
530 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
531 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000532
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000533 if (IMD)
534 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
535 else
536 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000537
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000538 int numMethods = IMD ? IMD->getNumInstanceMethods()
539 : CID->getNumInstanceMethods();
540
541 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000542 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000543 ObjcMethodDecl *OMD;
544 if (IMD)
545 OMD = IMD->getInstanceMethods()[i];
546 else
547 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000548 RewriteObjcMethodDecl(OMD, ResultStr);
549 SourceLocation LocStart = OMD->getLocStart();
550 SourceLocation LocEnd = OMD->getBody()->getLocStart();
551
552 const char *startBuf = SM->getCharacterData(LocStart);
553 const char *endBuf = SM->getCharacterData(LocEnd);
554 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
555 ResultStr.c_str(), ResultStr.size());
556 }
557
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000558 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
559 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000560 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000561 ObjcMethodDecl *OMD;
562 if (IMD)
563 OMD = IMD->getClassMethods()[i];
564 else
565 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000566 RewriteObjcMethodDecl(OMD, ResultStr);
567 SourceLocation LocStart = OMD->getLocStart();
568 SourceLocation LocEnd = OMD->getBody()->getLocStart();
569
570 const char *startBuf = SM->getCharacterData(LocStart);
571 const char *endBuf = SM->getCharacterData(LocEnd);
572 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
573 ResultStr.c_str(), ResultStr.size());
574 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000575 if (IMD)
576 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
577 else
578 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000579}
580
Steve Naroffbef11852007-10-26 20:53:56 +0000581void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000582 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000583 if (!ObjcForwardDecls.count(ClassDecl)) {
584 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000585 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000586 ResultStr += ClassDecl->getName();
587 ResultStr += "\n";
588 ResultStr += "#define _REWRITER_typedef_";
589 ResultStr += ClassDecl->getName();
590 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000591 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000592 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000593 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000594
595 // Mark this typedef as having been generated.
596 ObjcForwardDecls.insert(ClassDecl);
597 }
Steve Narofff908a872007-10-30 02:23:23 +0000598 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
599
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000600 RewriteProperties(ClassDecl->getNumPropertyDecl(),
601 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000602 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
603 ClassDecl->getInstanceMethods());
604 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
605 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000606
Steve Naroff2feac5e2007-10-30 03:43:13 +0000607 // Lastly, comment out the @end.
608 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000609}
610
Steve Naroff7e3411b2007-11-15 02:58:25 +0000611Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
612 ObjcIvarDecl *D = IV->getDecl();
613 if (IV->isFreeIvar()) {
614 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
615 IV->getLocation());
616 Rewrite.ReplaceStmt(IV, Replacement);
617 delete IV;
618 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000619 } else {
620 if (CurMethodDecl) {
621 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
622 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
623 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
624 IdentifierInfo *II = intT->getDecl()->getIdentifier();
625 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
626 II, 0);
627 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
628
629 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
630 // Don't forget the parens to enforce the proper binding.
631 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
632 Rewrite.ReplaceStmt(IV->getBase(), PE);
633 delete IV->getBase();
634 return PE;
635 }
636 }
637 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000638 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000639 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000640}
641
Chris Lattnerf04da132007-10-24 17:06:59 +0000642//===----------------------------------------------------------------------===//
643// Function Body / Expression rewriting
644//===----------------------------------------------------------------------===//
645
Steve Narofff3473a72007-11-09 15:20:18 +0000646Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000647 // Otherwise, just rewrite all children.
648 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
649 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000650 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000651 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000652 if (newStmt)
653 *CI = newStmt;
654 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000655
656 // Handle specific things.
657 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
658 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000659
660 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
661 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000662
663 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
664 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000665
666 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
667 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000668
Steve Naroff934f2762007-10-24 22:48:43 +0000669 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
670 // Before we rewrite it, put the original message expression in a comment.
671 SourceLocation startLoc = MessExpr->getLocStart();
672 SourceLocation endLoc = MessExpr->getLocEnd();
673
674 const char *startBuf = SM->getCharacterData(startLoc);
675 const char *endBuf = SM->getCharacterData(endLoc);
676
677 std::string messString;
678 messString += "// ";
679 messString.append(startBuf, endBuf-startBuf+1);
680 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000681
Steve Naroff934f2762007-10-24 22:48:43 +0000682 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
683 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
684 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000685 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000686 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000687 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000688
689 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
690 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000691
692 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
693 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000694#if 0
695 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
696 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
697 // Get the new text.
698 std::ostringstream Buf;
699 Replacement->printPretty(Buf);
700 const std::string &Str = Buf.str();
701
702 printf("CAST = %s\n", &Str[0]);
703 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
704 delete S;
705 return Replacement;
706 }
707#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000708 // Return this stmt unmodified.
709 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000710}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000711
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000712Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000713 // Get the start location and compute the semi location.
714 SourceLocation startLoc = S->getLocStart();
715 const char *startBuf = SM->getCharacterData(startLoc);
716
717 assert((*startBuf == '@') && "bogus @try location");
718
719 std::string buf;
720 // declare a new scope with two variables, _stack and _rethrow.
721 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
722 buf += "int buf[18/*32-bit i386*/];\n";
723 buf += "char *pointers[4];} _stack;\n";
724 buf += "id volatile _rethrow = 0;\n";
725 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000726 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000727
728 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
729
730 startLoc = S->getTryBody()->getLocEnd();
731 startBuf = SM->getCharacterData(startLoc);
732
733 assert((*startBuf == '}') && "bogus @try block");
734
735 SourceLocation lastCurlyLoc = startLoc;
736
737 startLoc = startLoc.getFileLocWithOffset(1);
738 buf = " /* @catch begin */ else {\n";
739 buf += " id _caught = objc_exception_extract(&_stack);\n";
740 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000741 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000742 buf += " _rethrow = objc_exception_extract(&_stack);\n";
743 buf += " else { /* @catch continue */";
744
Chris Lattner28d1fe82007-11-08 04:41:51 +0000745 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000746
747 bool sawIdTypedCatch = false;
748 Stmt *lastCatchBody = 0;
749 ObjcAtCatchStmt *catchList = S->getCatchStmts();
750 while (catchList) {
751 Stmt *catchStmt = catchList->getCatchParamStmt();
752
753 if (catchList == S->getCatchStmts())
754 buf = "if ("; // we are generating code for the first catch clause
755 else
756 buf = "else if (";
757 startLoc = catchList->getLocStart();
758 startBuf = SM->getCharacterData(startLoc);
759
760 assert((*startBuf == '@') && "bogus @catch location");
761
762 const char *lParenLoc = strchr(startBuf, '(');
763
764 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
765 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
766 if (t == Context->getObjcIdType()) {
767 buf += "1) { ";
768 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
769 buf.c_str(), buf.size());
770 sawIdTypedCatch = true;
771 } else if (const PointerType *pType = t->getAsPointerType()) {
772 ObjcInterfaceType *cls; // Should be a pointer to a class.
773
774 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
775 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000776 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000777 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000778 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000779 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
780 buf.c_str(), buf.size());
781 }
782 }
783 // Now rewrite the body...
784 lastCatchBody = catchList->getCatchBody();
785 SourceLocation rParenLoc = catchList->getRParenLoc();
786 SourceLocation bodyLoc = lastCatchBody->getLocStart();
787 const char *bodyBuf = SM->getCharacterData(bodyLoc);
788 const char *rParenBuf = SM->getCharacterData(rParenLoc);
789 assert((*rParenBuf == ')') && "bogus @catch paren location");
790 assert((*bodyBuf == '{') && "bogus @catch body location");
791
792 buf = " = _caught;";
793 // Here we replace ") {" with "= _caught;" (which initializes and
794 // declares the @catch parameter).
795 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
796 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000797 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000798 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000799 }
Steve Naroff75730982007-11-07 04:08:17 +0000800 catchList = catchList->getNextCatchStmt();
801 }
802 // Complete the catch list...
803 if (lastCatchBody) {
804 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
805 const char *bodyBuf = SM->getCharacterData(bodyLoc);
806 assert((*bodyBuf == '}') && "bogus @catch body location");
807 bodyLoc = bodyLoc.getFileLocWithOffset(1);
808 buf = " } } /* @catch end */\n";
809
Chris Lattner28d1fe82007-11-08 04:41:51 +0000810 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000811
812 // Set lastCurlyLoc
813 lastCurlyLoc = lastCatchBody->getLocEnd();
814 }
815 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
816 startLoc = finalStmt->getLocStart();
817 startBuf = SM->getCharacterData(startLoc);
818 assert((*startBuf == '@') && "bogus @finally start");
819
820 buf = "/* @finally */";
821 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
822
823 Stmt *body = finalStmt->getFinallyBody();
824 SourceLocation startLoc = body->getLocStart();
825 SourceLocation endLoc = body->getLocEnd();
826 const char *startBuf = SM->getCharacterData(startLoc);
827 const char *endBuf = SM->getCharacterData(endLoc);
828 assert((*startBuf == '{') && "bogus @finally body location");
829 assert((*endBuf == '}') && "bogus @finally body location");
830
831 startLoc = startLoc.getFileLocWithOffset(1);
832 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000833 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000834 endLoc = endLoc.getFileLocWithOffset(-1);
835 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000836 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000837
838 // Set lastCurlyLoc
839 lastCurlyLoc = body->getLocEnd();
840 }
841 // Now emit the final closing curly brace...
842 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
843 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000844 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000845 return 0;
846}
847
848Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
849 return 0;
850}
851
852Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
853 return 0;
854}
855
Steve Naroff2bd03922007-11-07 15:32:26 +0000856// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
857// the throw expression is typically a message expression that's already
858// been rewritten! (which implies the SourceLocation's are invalid).
859Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
860 // Get the start location and compute the semi location.
861 SourceLocation startLoc = S->getLocStart();
862 const char *startBuf = SM->getCharacterData(startLoc);
863
864 assert((*startBuf == '@') && "bogus @throw location");
865
866 std::string buf;
867 /* void objc_exception_throw(id) __attribute__((noreturn)); */
868 buf = "objc_exception_throw(";
869 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
870 const char *semiBuf = strchr(startBuf, ';');
871 assert((*semiBuf == ';') && "@throw: can't find ';'");
872 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
873 buf = ");";
874 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
875 return 0;
876}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000877
Chris Lattnere64b7772007-10-24 16:57:36 +0000878Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000879 // Create a new string expression.
880 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000881 std::string StrEncoding;
882 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
883 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
884 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000885 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000886 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
887 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000888 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
889 "rewriter could not replace sub-expression due to macros");
890 SourceRange Range = Exp->getSourceRange();
891 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
892 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000893 return Exp;
894 }
895
Chris Lattner07506182007-11-30 22:53:43 +0000896 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000897 delete Exp;
898 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000899}
900
Steve Naroffb42f8412007-11-05 14:50:49 +0000901Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
902 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
903 // Create a call to sel_registerName("selName").
904 llvm::SmallVector<Expr*, 8> SelExprs;
905 QualType argType = Context->getPointerType(Context->CharTy);
906 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
907 Exp->getSelector().getName().size(),
908 false, argType, SourceLocation(),
909 SourceLocation()));
910 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
911 &SelExprs[0], SelExprs.size());
912 Rewrite.ReplaceStmt(Exp, SelExp);
913 delete Exp;
914 return SelExp;
915}
916
Steve Naroff934f2762007-10-24 22:48:43 +0000917CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
918 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000919 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000920 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000921
922 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000923 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000924
925 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000926 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000927 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
928
929 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000930
Steve Naroff934f2762007-10-24 22:48:43 +0000931 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
932}
933
Steve Naroffd5255f52007-11-01 13:24:47 +0000934static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
935 const char *&startRef, const char *&endRef) {
936 while (startBuf < endBuf) {
937 if (*startBuf == '<')
938 startRef = startBuf; // mark the start.
939 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000940 if (startRef && *startRef == '<') {
941 endRef = startBuf; // mark the end.
942 return true;
943 }
944 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000945 }
946 startBuf++;
947 }
948 return false;
949}
950
951bool RewriteTest::needToScanForQualifiers(QualType T) {
952 // FIXME: we don't currently represent "id <Protocol>" in the type system.
953 if (T == Context->getObjcIdType())
954 return true;
955
956 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000957 Type *pointeeType = pType->getPointeeType().getTypePtr();
958 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
959 return true; // we have "Class <Protocol> *".
960 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000961 return false;
962}
963
964void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
965 const FunctionTypeProto *proto, FunctionDecl *FD) {
966
967 if (needToScanForQualifiers(proto->getResultType())) {
968 // Since types are unique, we need to scan the buffer.
969 SourceLocation Loc = FD->getLocation();
970
971 const char *endBuf = SM->getCharacterData(Loc);
972 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +0000973 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +0000974 startBuf--; // scan backward (from the decl location) for return type.
975 const char *startRef = 0, *endRef = 0;
976 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
977 // Get the locations of the startRef, endRef.
978 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
979 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
980 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000981 Rewrite.InsertText(LessLoc, "/*", 2);
982 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000983 }
984 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000985 // Now check arguments.
986 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
987 if (needToScanForQualifiers(proto->getArgType(i))) {
988 // Since types are unique, we need to scan the buffer.
989 SourceLocation Loc = FD->getLocation();
990
991 const char *startBuf = SM->getCharacterData(Loc);
992 const char *endBuf = startBuf;
993 while (*endBuf != ';')
994 endBuf++; // scan forward (from the decl location) for argument types.
995 const char *startRef = 0, *endRef = 0;
996 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
997 // Get the locations of the startRef, endRef.
998 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
999 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1000 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001001 Rewrite.InsertText(LessLoc, "/*", 2);
1002 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001003 }
1004 }
1005 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001006}
1007
Steve Naroff09b266e2007-10-30 23:14:51 +00001008void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1009 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001010 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001011 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001012 return;
1013 }
1014 // Check for ObjC 'id' and class types that have been adorned with protocol
1015 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1016 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1017 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +00001018 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1019 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001020}
1021
1022// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1023void RewriteTest::SynthMsgSendFunctionDecl() {
1024 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1025 llvm::SmallVector<QualType, 16> ArgTys;
1026 QualType argT = Context->getObjcIdType();
1027 assert(!argT.isNull() && "Can't find 'id' type");
1028 ArgTys.push_back(argT);
1029 argT = Context->getObjcSelType();
1030 assert(!argT.isNull() && "Can't find 'SEL' type");
1031 ArgTys.push_back(argT);
1032 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1033 &ArgTys[0], ArgTys.size(),
1034 true /*isVariadic*/);
1035 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1036 msgSendIdent, msgSendType,
1037 FunctionDecl::Extern, false, 0);
1038}
1039
Steve Naroff874e2322007-11-15 10:28:18 +00001040// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1041void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1042 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1043 llvm::SmallVector<QualType, 16> ArgTys;
1044 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1045 &Context->Idents.get("objc_super"), 0);
1046 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1047 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1048 ArgTys.push_back(argT);
1049 argT = Context->getObjcSelType();
1050 assert(!argT.isNull() && "Can't find 'SEL' type");
1051 ArgTys.push_back(argT);
1052 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1053 &ArgTys[0], ArgTys.size(),
1054 true /*isVariadic*/);
1055 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1056 msgSendIdent, msgSendType,
1057 FunctionDecl::Extern, false, 0);
1058}
1059
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001060// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1061void RewriteTest::SynthMsgSendStretFunctionDecl() {
1062 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1063 llvm::SmallVector<QualType, 16> ArgTys;
1064 QualType argT = Context->getObjcIdType();
1065 assert(!argT.isNull() && "Can't find 'id' type");
1066 ArgTys.push_back(argT);
1067 argT = Context->getObjcSelType();
1068 assert(!argT.isNull() && "Can't find 'SEL' type");
1069 ArgTys.push_back(argT);
1070 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1071 &ArgTys[0], ArgTys.size(),
1072 true /*isVariadic*/);
1073 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1074 msgSendIdent, msgSendType,
1075 FunctionDecl::Extern, false, 0);
1076}
1077
1078// SynthMsgSendSuperStretFunctionDecl -
1079// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1080void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1081 IdentifierInfo *msgSendIdent =
1082 &Context->Idents.get("objc_msgSendSuper_stret");
1083 llvm::SmallVector<QualType, 16> ArgTys;
1084 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1085 &Context->Idents.get("objc_super"), 0);
1086 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1087 assert(!argT.isNull() && "Can't build 'struct objc_super *' 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 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1096 msgSendIdent, msgSendType,
1097 FunctionDecl::Extern, false, 0);
1098}
1099
Steve Naroff09b266e2007-10-30 23:14:51 +00001100// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1101void RewriteTest::SynthGetClassFunctionDecl() {
1102 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1103 llvm::SmallVector<QualType, 16> ArgTys;
1104 ArgTys.push_back(Context->getPointerType(
1105 Context->CharTy.getQualifiedType(QualType::Const)));
1106 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1107 &ArgTys[0], ArgTys.size(),
1108 false /*isVariadic*/);
1109 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1110 getClassIdent, getClassType,
1111 FunctionDecl::Extern, false, 0);
1112}
1113
Steve Naroff96984642007-11-08 14:30:50 +00001114// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1115void RewriteTest::SynthCFStringFunctionDecl() {
1116 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1117 llvm::SmallVector<QualType, 16> ArgTys;
1118 ArgTys.push_back(Context->getPointerType(
1119 Context->CharTy.getQualifiedType(QualType::Const)));
1120 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1121 &ArgTys[0], ArgTys.size(),
1122 false /*isVariadic*/);
1123 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1124 getClassIdent, getClassType,
1125 FunctionDecl::Extern, false, 0);
1126}
1127
Steve Naroffbeaf2992007-11-03 11:27:19 +00001128Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001129#if 1
1130 // This rewrite is specific to GCC, which has builtin support for CFString.
1131 if (!CFStringFunctionDecl)
1132 SynthCFStringFunctionDecl();
1133 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1134 llvm::SmallVector<Expr*, 8> StrExpr;
1135 StrExpr.push_back(Exp->getString());
1136 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1137 &StrExpr[0], StrExpr.size());
1138 // cast to NSConstantString *
1139 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1140 Rewrite.ReplaceStmt(Exp, cast);
1141 delete Exp;
1142 return cast;
1143#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001144 assert(ConstantStringClassReference && "Can't find constant string reference");
1145 llvm::SmallVector<Expr*, 4> InitExprs;
1146
1147 // Synthesize "(Class)&_NSConstantStringClassReference"
1148 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1149 ConstantStringClassReference->getType(),
1150 SourceLocation());
1151 QualType expType = Context->getPointerType(ClsRef->getType());
1152 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1153 expType, SourceLocation());
1154 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1155 SourceLocation());
1156 InitExprs.push_back(cast); // set the 'isa'.
1157 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1158 unsigned IntSize = static_cast<unsigned>(
1159 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1160 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1161 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1162 Exp->getLocStart());
1163 InitExprs.push_back(len); // set "int numBytes".
1164
1165 // struct NSConstantString
1166 QualType CFConstantStrType = Context->getCFConstantStringType();
1167 // (struct NSConstantString) { <exprs from above> }
1168 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1169 &InitExprs[0], InitExprs.size(),
1170 SourceLocation());
1171 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1172 // struct NSConstantString *
1173 expType = Context->getPointerType(StrRep->getType());
1174 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1175 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001176 // cast to NSConstantString *
1177 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001178 Rewrite.ReplaceStmt(Exp, cast);
1179 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001180 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001181#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001182}
1183
Steve Naroff874e2322007-11-15 10:28:18 +00001184ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1185 if (CurMethodDecl) { // check if we are sending a message to 'super'
1186 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1187 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1188 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1189 if (!strcmp(PVD->getName(), "self")) {
1190 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1191 if (ObjcInterfaceType *IT =
1192 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1193 if (IT->getDecl() ==
1194 CurMethodDecl->getClassInterface()->getSuperClass())
1195 return IT->getDecl();
1196 }
1197 }
1198 }
1199 }
1200 }
1201 }
1202 }
1203 return 0;
1204}
1205
1206// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1207QualType RewriteTest::getSuperStructType() {
1208 if (!SuperStructDecl) {
1209 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1210 &Context->Idents.get("objc_super"), 0);
1211 QualType FieldTypes[2];
1212
1213 // struct objc_object *receiver;
1214 FieldTypes[0] = Context->getObjcIdType();
1215 // struct objc_class *super;
1216 FieldTypes[1] = Context->getObjcClassType();
1217 // Create fields
1218 FieldDecl *FieldDecls[2];
1219
1220 for (unsigned i = 0; i < 2; ++i)
1221 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1222
1223 SuperStructDecl->defineBody(FieldDecls, 4);
1224 }
1225 return Context->getTagDeclType(SuperStructDecl);
1226}
1227
Steve Naroff934f2762007-10-24 22:48:43 +00001228Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001229 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001230 if (!MsgSendFunctionDecl)
1231 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001232 if (!MsgSendSuperFunctionDecl)
1233 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001234 if (!MsgSendStretFunctionDecl)
1235 SynthMsgSendStretFunctionDecl();
1236 if (!MsgSendSuperStretFunctionDecl)
1237 SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001238 if (!GetClassFunctionDecl)
1239 SynthGetClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001240
Steve Naroff874e2322007-11-15 10:28:18 +00001241 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001242 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1243 // May need to use objc_msgSend_stret() as well.
1244 FunctionDecl *MsgSendStretFlavor = 0;
1245 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1246 QualType resultType = mDecl->getResultType();
1247 if (resultType.getCanonicalType()->isStructureType()
1248 || resultType.getCanonicalType()->isUnionType())
1249 MsgSendStretFlavor = MsgSendStretFunctionDecl;
1250 }
Steve Naroff874e2322007-11-15 10:28:18 +00001251
Steve Naroff934f2762007-10-24 22:48:43 +00001252 // Synthesize a call to objc_msgSend().
1253 llvm::SmallVector<Expr*, 8> MsgExprs;
1254 IdentifierInfo *clsName = Exp->getClassName();
1255
1256 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1257 if (clsName) { // class message.
1258 llvm::SmallVector<Expr*, 8> ClsExprs;
1259 QualType argType = Context->getPointerType(Context->CharTy);
1260 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1261 clsName->getLength(),
1262 false, argType, SourceLocation(),
1263 SourceLocation()));
1264 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1265 &ClsExprs[0], ClsExprs.size());
1266 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001267 } else { // instance message.
1268 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001269
1270 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1271 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001272 if (MsgSendStretFlavor)
1273 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001274 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1275
1276 llvm::SmallVector<Expr*, 4> InitExprs;
1277
1278 InitExprs.push_back(recExpr); // set the 'receiver'.
1279
1280 llvm::SmallVector<Expr*, 8> ClsExprs;
1281 QualType argType = Context->getPointerType(Context->CharTy);
1282 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1283 ID->getIdentifier()->getLength(),
1284 false, argType, SourceLocation(),
1285 SourceLocation()));
1286 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1287 &ClsExprs[0], ClsExprs.size());
1288 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1289 // struct objc_super
1290 QualType superType = getSuperStructType();
1291 // (struct objc_super) { <exprs from above> }
1292 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1293 &InitExprs[0], InitExprs.size(),
1294 SourceLocation());
1295 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1296 // struct objc_super *
1297 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1298 Context->getPointerType(SuperRep->getType()),
1299 SourceLocation());
1300 MsgExprs.push_back(Unop);
1301 } else {
1302 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1303 MsgExprs.push_back(recExpr);
1304 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001305 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001306 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001307 llvm::SmallVector<Expr*, 8> SelExprs;
1308 QualType argType = Context->getPointerType(Context->CharTy);
1309 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1310 Exp->getSelector().getName().size(),
1311 false, argType, SourceLocation(),
1312 SourceLocation()));
1313 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1314 &SelExprs[0], SelExprs.size());
1315 MsgExprs.push_back(SelExp);
1316
1317 // Now push any user supplied arguments.
1318 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001319 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001320 // Make all implicit casts explicit...ICE comes in handy:-)
1321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1322 // Reuse the ICE type, it is exactly what the doctor ordered.
1323 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1324 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001325 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001326 // We've transferred the ownership to MsgExprs. Null out the argument in
1327 // the original expression, since we will delete it below.
1328 Exp->setArg(i, 0);
1329 }
Steve Naroffab972d32007-11-04 22:37:50 +00001330 // Generate the funky cast.
1331 CastExpr *cast;
1332 llvm::SmallVector<QualType, 8> ArgTypes;
1333 QualType returnType;
1334
1335 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001336 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1337 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1338 else
1339 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001340 ArgTypes.push_back(Context->getObjcSelType());
1341 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1342 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001343 for (int i = 0; i < mDecl->getNumParams(); i++) {
1344 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001345 ArgTypes.push_back(t);
1346 }
Steve Naroffab972d32007-11-04 22:37:50 +00001347 returnType = mDecl->getResultType();
1348 } else {
1349 returnType = Context->getObjcIdType();
1350 }
1351 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001352 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001353
1354 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001355 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1356 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001357
1358 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1359 // If we don't do this cast, we get the following bizarre warning/note:
1360 // xx.m:13: warning: function called through a non-compatible type
1361 // xx.m:13: note: if this code is reached, the program will abort
1362 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1363 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001364
Steve Naroffab972d32007-11-04 22:37:50 +00001365 // Now do the "normal" pointer to function cast.
1366 QualType castType = Context->getFunctionType(returnType,
1367 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001368 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001369 castType = Context->getPointerType(castType);
1370 cast = new CastExpr(castType, cast, SourceLocation());
1371
1372 // Don't forget the parens to enforce the proper binding.
1373 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1374
1375 const FunctionType *FT = msgSendType->getAsFunctionType();
1376 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1377 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001378 if (MsgSendStretFlavor) {
1379 // We have the method which returns a struct/union. Must also generate
1380 // call to objc_msgSend_stret and hang both varieties on a conditional
1381 // expression which dictate which one to envoke depending on size of
1382 // method's return type.
1383
1384 // Create a reference to the objc_msgSend_stret() declaration.
1385 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1386 SourceLocation());
1387 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1388 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1389 SourceLocation());
1390 // Now do the "normal" pointer to function cast.
1391 castType = Context->getFunctionType(returnType,
1392 &ArgTypes[0], ArgTypes.size(),
1393 Exp->getMethodDecl()->isVariadic());
1394 castType = Context->getPointerType(castType);
1395 cast = new CastExpr(castType, cast, SourceLocation());
1396
1397 // Don't forget the parens to enforce the proper binding.
1398 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1399
1400 FT = msgSendType->getAsFunctionType();
1401 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1402 FT->getResultType(), SourceLocation());
1403
1404 // Build sizeof(returnType)
1405 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1406 returnType, Context->getSizeType(),
1407 SourceLocation(), SourceLocation());
1408 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1409 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1410 // For X86 it is more complicated and some kind of target specific routine
1411 // is needed to decide what to do.
1412 unsigned IntSize = static_cast<unsigned>(
1413 Context->getTypeSize(Context->IntTy, SourceLocation()));
1414
1415 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1416 Context->IntTy,
1417 SourceLocation());
1418 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1419 BinaryOperator::LE,
1420 Context->IntTy,
1421 SourceLocation());
1422 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1423 ConditionalOperator *CondExpr =
1424 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1425 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1426 // Now do the actual rewrite.
1427 Rewrite.ReplaceStmt(Exp, PE);
1428 delete Exp;
1429 return PE;
1430 }
Steve Naroff934f2762007-10-24 22:48:43 +00001431 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001432 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001433
Chris Lattnere64b7772007-10-24 16:57:36 +00001434 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001435 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001436}
1437
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001438/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1439/// an objective-c class with ivars.
1440void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1441 std::string &Result) {
1442 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1443 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001444 // Do not synthesize more than once.
1445 if (ObjcSynthesizedStructs.count(CDecl))
1446 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001447 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001448 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001449 SourceLocation LocStart = CDecl->getLocStart();
1450 SourceLocation LocEnd = CDecl->getLocEnd();
1451
1452 const char *startBuf = SM->getCharacterData(LocStart);
1453 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001454 // If no ivars and no root or if its root, directly or indirectly,
1455 // have no ivars (thus not synthesized) then no need to synthesize this class.
1456 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001457 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1458 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1459 Result.c_str(), Result.size());
1460 return;
1461 }
1462
1463 // FIXME: This has potential of causing problem. If
1464 // SynthesizeObjcInternalStruct is ever called recursively.
1465 Result += "\nstruct ";
1466 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001467
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001468 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001469 const char *cursor = strchr(startBuf, '{');
1470 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001471 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001472
1473 // rewrite the original header *without* disturbing the '{'
1474 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1475 Result.c_str(), Result.size());
1476 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1477 Result = "\n struct ";
1478 Result += RCDecl->getName();
1479 Result += " _";
1480 Result += RCDecl->getName();
1481 Result += ";\n";
1482
1483 // insert the super class structure definition.
1484 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1485 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1486 }
1487 cursor++; // past '{'
1488
1489 // Now comment out any visibility specifiers.
1490 while (cursor < endBuf) {
1491 if (*cursor == '@') {
1492 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001493 // Skip whitespace.
1494 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1495 /*scan*/;
1496
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001497 // FIXME: presence of @public, etc. inside comment results in
1498 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001499 if (!strncmp(cursor, "public", strlen("public")) ||
1500 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001501 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001502 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001503 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001504 // FIXME: If there are cases where '<' is used in ivar declaration part
1505 // of user code, then scan the ivar list and use needToScanForQualifiers
1506 // for type checking.
1507 else if (*cursor == '<') {
1508 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1509 Rewrite.InsertText(atLoc, "/* ", 3);
1510 cursor = strchr(cursor, '>');
1511 cursor++;
1512 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1513 Rewrite.InsertText(atLoc, " */", 3);
1514 }
Steve Narofffea763e82007-11-14 19:25:57 +00001515 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001516 }
Steve Narofffea763e82007-11-14 19:25:57 +00001517 // Don't forget to add a ';'!!
1518 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1519 } else { // we don't have any instance variables - insert super struct.
1520 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1521 Result += " {\n struct ";
1522 Result += RCDecl->getName();
1523 Result += " _";
1524 Result += RCDecl->getName();
1525 Result += ";\n};\n";
1526 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1527 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001528 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001529 // Mark this struct as having been generated.
1530 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001531 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001532}
1533
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001534// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1535/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001536void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001537 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001538 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001539 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001540 const char *ClassName,
1541 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001542 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001543 if (NumMethods > 0 && !objc_impl_method) {
1544 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001545 SEL _cmd;
1546 char *method_types;
1547 void *_imp;
1548 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001549 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001550 Result += "\nstruct _objc_method {\n";
1551 Result += "\tSEL _cmd;\n";
1552 Result += "\tchar *method_types;\n";
1553 Result += "\tvoid *_imp;\n";
1554 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001555
1556 /* struct _objc_method_list {
1557 struct _objc_method_list *next_method;
1558 int method_count;
1559 struct _objc_method method_list[];
1560 }
1561 */
1562 Result += "\nstruct _objc_method_list {\n";
1563 Result += "\tstruct _objc_method_list *next_method;\n";
1564 Result += "\tint method_count;\n";
1565 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001566 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001567 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001568 // Build _objc_method_list for class's methods if needed
1569 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001570 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001571 Result += prefix;
1572 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1573 Result += "_METHODS_";
1574 Result += ClassName;
1575 Result += " __attribute__ ((section (\"__OBJC, __";
1576 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001577 Result += "_meth\")))= ";
1578 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1579
1580 Result += "\t,{{(SEL)\"";
1581 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001582 std::string MethodTypeString;
1583 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1584 Result += "\", \"";
1585 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001586 Result += "\", ";
1587 Result += MethodInternalNames[Methods[0]];
1588 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001589 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001590 Result += "\t ,{(SEL)\"";
1591 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001592 std::string MethodTypeString;
1593 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1594 Result += "\", \"";
1595 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001596 Result += "\", ";
1597 Result += MethodInternalNames[Methods[i]];
1598 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001599 }
1600 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001601 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001602}
1603
1604/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1605void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1606 int NumProtocols,
1607 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001608 const char *ClassName,
1609 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001610 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001611 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001612 for (int i = 0; i < NumProtocols; i++) {
1613 ObjcProtocolDecl *PDecl = Protocols[i];
1614 // Output struct protocol_methods holder of method selector and type.
1615 if (!objc_protocol_methods &&
1616 (PDecl->getNumInstanceMethods() > 0
1617 || PDecl->getNumClassMethods() > 0)) {
1618 /* struct protocol_methods {
1619 SEL _cmd;
1620 char *method_types;
1621 }
1622 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001623 Result += "\nstruct protocol_methods {\n";
1624 Result += "\tSEL _cmd;\n";
1625 Result += "\tchar *method_types;\n";
1626 Result += "};\n";
1627
1628 /* struct _objc_protocol_method_list {
1629 int protocol_method_count;
1630 struct protocol_methods protocols[];
1631 }
1632 */
1633 Result += "\nstruct _objc_protocol_method_list {\n";
1634 Result += "\tint protocol_method_count;\n";
1635 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001636 objc_protocol_methods = true;
1637 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001638
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001639 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001640 int NumMethods = PDecl->getNumInstanceMethods();
1641 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001642 Result += "\nstatic struct _objc_protocol_method_list "
1643 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1644 Result += PDecl->getName();
1645 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1646 "{\n\t" + utostr(NumMethods) + "\n";
1647
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001648 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001649 Result += "\t,{{(SEL)\"";
1650 Result += Methods[0]->getSelector().getName().c_str();
1651 Result += "\", \"\"}\n";
1652
1653 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001654 Result += "\t ,{(SEL)\"";
1655 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001656 std::string MethodTypeString;
1657 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1658 Result += "\", \"";
1659 Result += MethodTypeString;
1660 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001661 }
1662 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001663 }
1664
1665 // Output class methods declared in this protocol.
1666 NumMethods = PDecl->getNumClassMethods();
1667 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001668 Result += "\nstatic struct _objc_protocol_method_list "
1669 "_OBJC_PROTOCOL_CLASS_METHODS_";
1670 Result += PDecl->getName();
1671 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1672 "{\n\t";
1673 Result += utostr(NumMethods);
1674 Result += "\n";
1675
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001676 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001677 Result += "\t,{{(SEL)\"";
1678 Result += Methods[0]->getSelector().getName().c_str();
1679 Result += "\", \"\"}\n";
1680
1681 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001682 Result += "\t ,{(SEL)\"";
1683 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001684 std::string MethodTypeString;
1685 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1686 Result += "\", \"";
1687 Result += MethodTypeString;
1688 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001689 }
1690 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001691 }
1692 // Output:
1693 /* struct _objc_protocol {
1694 // Objective-C 1.0 extensions
1695 struct _objc_protocol_extension *isa;
1696 char *protocol_name;
1697 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001698 struct _objc_protocol_method_list *instance_methods;
1699 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001700 };
1701 */
1702 static bool objc_protocol = false;
1703 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001704 Result += "\nstruct _objc_protocol {\n";
1705 Result += "\tstruct _objc_protocol_extension *isa;\n";
1706 Result += "\tchar *protocol_name;\n";
1707 Result += "\tstruct _objc_protocol **protocol_list;\n";
1708 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1709 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1710 Result += "};\n";
1711
1712 /* struct _objc_protocol_list {
1713 struct _objc_protocol_list *next;
1714 int protocol_count;
1715 struct _objc_protocol *class_protocols[];
1716 }
1717 */
1718 Result += "\nstruct _objc_protocol_list {\n";
1719 Result += "\tstruct _objc_protocol_list *next;\n";
1720 Result += "\tint protocol_count;\n";
1721 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1722 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001723 objc_protocol = true;
1724 }
1725
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001726 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1727 Result += PDecl->getName();
1728 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1729 "{\n\t0, \"";
1730 Result += PDecl->getName();
1731 Result += "\", 0, ";
1732 if (PDecl->getInstanceMethods() > 0) {
1733 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1734 Result += PDecl->getName();
1735 Result += ", ";
1736 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001737 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001738 Result += "0, ";
1739 if (PDecl->getClassMethods() > 0) {
1740 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1741 Result += PDecl->getName();
1742 Result += "\n";
1743 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001744 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001745 Result += "0\n";
1746 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001747 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001748 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001749 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1750 Result += prefix;
1751 Result += "_PROTOCOLS_";
1752 Result += ClassName;
1753 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1754 "{\n\t0, ";
1755 Result += utostr(NumProtocols);
1756 Result += "\n";
1757
1758 Result += "\t,{&_OBJC_PROTOCOL_";
1759 Result += Protocols[0]->getName();
1760 Result += " \n";
1761
1762 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001763 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001764 Result += "\t ,&_OBJC_PROTOCOL_";
1765 Result += PDecl->getName();
1766 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001767 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001768 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001769 }
1770}
1771
1772/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1773/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001774void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1775 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001776 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1777 // Find category declaration for this implementation.
1778 ObjcCategoryDecl *CDecl;
1779 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1780 CDecl = CDecl->getNextClassCategory())
1781 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1782 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001783
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001784 char *FullCategoryName = (char*)alloca(
1785 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1786 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1787
1788 // Build _objc_method_list for class's instance methods if needed
1789 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1790 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001791 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001792 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001793
1794 // Build _objc_method_list for class's class methods if needed
1795 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1796 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001797 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001798 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001799
1800 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001801 // Null CDecl is case of a category implementation with no category interface
1802 if (CDecl)
1803 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1804 CDecl->getNumReferencedProtocols(),
1805 "CATEGORY",
1806 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001807
1808 /* struct _objc_category {
1809 char *category_name;
1810 char *class_name;
1811 struct _objc_method_list *instance_methods;
1812 struct _objc_method_list *class_methods;
1813 struct _objc_protocol_list *protocols;
1814 // Objective-C 1.0 extensions
1815 uint32_t size; // sizeof (struct _objc_category)
1816 struct _objc_property_list *instance_properties; // category's own
1817 // @property decl.
1818 };
1819 */
1820
1821 static bool objc_category = false;
1822 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001823 Result += "\nstruct _objc_category {\n";
1824 Result += "\tchar *category_name;\n";
1825 Result += "\tchar *class_name;\n";
1826 Result += "\tstruct _objc_method_list *instance_methods;\n";
1827 Result += "\tstruct _objc_method_list *class_methods;\n";
1828 Result += "\tstruct _objc_protocol_list *protocols;\n";
1829 Result += "\tunsigned int size;\n";
1830 Result += "\tstruct _objc_property_list *instance_properties;\n";
1831 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001832 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001833 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001834 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1835 Result += FullCategoryName;
1836 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1837 Result += IDecl->getName();
1838 Result += "\"\n\t, \"";
1839 Result += ClassDecl->getName();
1840 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001841
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001842 if (IDecl->getNumInstanceMethods() > 0) {
1843 Result += "\t, (struct _objc_method_list *)"
1844 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1845 Result += FullCategoryName;
1846 Result += "\n";
1847 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001848 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001849 Result += "\t, 0\n";
1850 if (IDecl->getNumClassMethods() > 0) {
1851 Result += "\t, (struct _objc_method_list *)"
1852 "&_OBJC_CATEGORY_CLASS_METHODS_";
1853 Result += FullCategoryName;
1854 Result += "\n";
1855 }
1856 else
1857 Result += "\t, 0\n";
1858
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001859 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001860 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1861 Result += FullCategoryName;
1862 Result += "\n";
1863 }
1864 else
1865 Result += "\t, 0\n";
1866 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001867}
1868
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001869/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1870/// ivar offset.
1871void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1872 ObjcIvarDecl *ivar,
1873 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001874 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001875 Result += IDecl->getName();
1876 Result += ", ";
1877 Result += ivar->getName();
1878 Result += ")";
1879}
1880
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001881//===----------------------------------------------------------------------===//
1882// Meta Data Emission
1883//===----------------------------------------------------------------------===//
1884
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001885void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1886 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001887 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1888
1889 // Build _objc_ivar_list metadata for classes ivars if needed
1890 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1891 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001892 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00001893 // Explictly declared @interface's are already synthesized.
1894 if (CDecl->ImplicitInterfaceDecl()) {
1895 // FIXME: Implementation of a class with no @interface (legacy) doese not
1896 // produce correct synthesis as yet.
1897 SynthesizeObjcInternalStruct(CDecl, Result);
1898 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001899
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001900 if (NumIvars > 0) {
1901 static bool objc_ivar = false;
1902 if (!objc_ivar) {
1903 /* struct _objc_ivar {
1904 char *ivar_name;
1905 char *ivar_type;
1906 int ivar_offset;
1907 };
1908 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001909 Result += "\nstruct _objc_ivar {\n";
1910 Result += "\tchar *ivar_name;\n";
1911 Result += "\tchar *ivar_type;\n";
1912 Result += "\tint ivar_offset;\n";
1913 Result += "};\n";
1914
1915 /* struct _objc_ivar_list {
1916 int ivar_count;
1917 struct _objc_ivar ivar_list[];
1918 };
1919 */
1920 Result += "\nstruct _objc_ivar_list {\n";
1921 Result += "\tint ivar_count;\n";
1922 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001923 objc_ivar = true;
1924 }
1925
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001926 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1927 Result += IDecl->getName();
1928 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1929 "{\n\t";
1930 Result += utostr(NumIvars);
1931 Result += "\n";
1932
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001933 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1934 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001935 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001936 Result += "\t,{{\"";
1937 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001938 Result += "\", \"";
1939 std::string StrEncoding;
1940 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1941 Result += StrEncoding;
1942 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001943 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1944 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001945 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001946 Result += "\t ,{\"";
1947 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001948 Result += "\", \"";
1949 std::string StrEncoding;
1950 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1951 Result += StrEncoding;
1952 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001953 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1954 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001955 }
1956
1957 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001958 }
1959
1960 // Build _objc_method_list for class's instance methods if needed
1961 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1962 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001963 true,
1964 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001965
1966 // Build _objc_method_list for class's class methods if needed
1967 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001968 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001969 false,
1970 "", IDecl->getName(), Result);
1971
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001972 // Protocols referenced in class declaration?
1973 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1974 CDecl->getNumIntfRefProtocols(),
1975 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001976 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001977
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001978
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001979 // Declaration of class/meta-class metadata
1980 /* struct _objc_class {
1981 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001982 const char *super_class_name;
1983 char *name;
1984 long version;
1985 long info;
1986 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001987 struct _objc_ivar_list *ivars;
1988 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001989 struct objc_cache *cache;
1990 struct objc_protocol_list *protocols;
1991 const char *ivar_layout;
1992 struct _objc_class_ext *ext;
1993 };
1994 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001995 static bool objc_class = false;
1996 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001997 Result += "\nstruct _objc_class {\n";
1998 Result += "\tstruct _objc_class *isa;\n";
1999 Result += "\tconst char *super_class_name;\n";
2000 Result += "\tchar *name;\n";
2001 Result += "\tlong version;\n";
2002 Result += "\tlong info;\n";
2003 Result += "\tlong instance_size;\n";
2004 Result += "\tstruct _objc_ivar_list *ivars;\n";
2005 Result += "\tstruct _objc_method_list *methods;\n";
2006 Result += "\tstruct objc_cache *cache;\n";
2007 Result += "\tstruct _objc_protocol_list *protocols;\n";
2008 Result += "\tconst char *ivar_layout;\n";
2009 Result += "\tstruct _objc_class_ext *ext;\n";
2010 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002011 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002012 }
2013
2014 // Meta-class metadata generation.
2015 ObjcInterfaceDecl *RootClass = 0;
2016 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2017 while (SuperClass) {
2018 RootClass = SuperClass;
2019 SuperClass = SuperClass->getSuperClass();
2020 }
2021 SuperClass = CDecl->getSuperClass();
2022
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002023 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2024 Result += CDecl->getName();
2025 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2026 "{\n\t(struct _objc_class *)\"";
2027 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2028 Result += "\"";
2029
2030 if (SuperClass) {
2031 Result += ", \"";
2032 Result += SuperClass->getName();
2033 Result += "\", \"";
2034 Result += CDecl->getName();
2035 Result += "\"";
2036 }
2037 else {
2038 Result += ", 0, \"";
2039 Result += CDecl->getName();
2040 Result += "\"";
2041 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002042 // TODO: 'ivars' field for root class is currently set to 0.
2043 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002044 Result += ", 0,2, sizeof(struct _objc_class), 0";
2045 if (CDecl->getNumClassMethods() > 0) {
2046 Result += "\n\t, &_OBJC_CLASS_METHODS_";
2047 Result += CDecl->getName();
2048 Result += "\n";
2049 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002050 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002051 Result += ", 0\n";
2052 if (CDecl->getNumIntfRefProtocols() > 0) {
2053 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2054 Result += CDecl->getName();
2055 Result += ",0,0\n";
2056 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002057 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002058 Result += "\t,0,0,0,0\n";
2059 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002060
2061 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002062 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2063 Result += CDecl->getName();
2064 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2065 "{\n\t&_OBJC_METACLASS_";
2066 Result += CDecl->getName();
2067 if (SuperClass) {
2068 Result += ", \"";
2069 Result += SuperClass->getName();
2070 Result += "\", \"";
2071 Result += CDecl->getName();
2072 Result += "\"";
2073 }
2074 else {
2075 Result += ", 0, \"";
2076 Result += CDecl->getName();
2077 Result += "\"";
2078 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002079 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002080 Result += ", 0,1";
2081 if (!ObjcSynthesizedStructs.count(CDecl))
2082 Result += ",0";
2083 else {
2084 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002085 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002086 Result += CDecl->getName();
2087 Result += ")";
2088 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002089 if (NumIvars > 0) {
2090 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2091 Result += CDecl->getName();
2092 Result += "\n\t";
2093 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002094 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002095 Result += ",0";
2096 if (IDecl->getNumInstanceMethods() > 0) {
2097 Result += ", &_OBJC_INSTANCE_METHODS_";
2098 Result += CDecl->getName();
2099 Result += ", 0\n\t";
2100 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002101 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002102 Result += ",0,0";
2103 if (CDecl->getNumIntfRefProtocols() > 0) {
2104 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2105 Result += CDecl->getName();
2106 Result += ", 0,0\n";
2107 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002108 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002109 Result += ",0,0,0\n";
2110 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002111}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002112
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002113/// RewriteImplementations - This routine rewrites all method implementations
2114/// and emits meta-data.
2115
2116void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002117 int ClsDefCount = ClassImplementation.size();
2118 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002119
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002120 if (ClsDefCount == 0 && CatDefCount == 0)
2121 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002122 // Rewrite implemented methods
2123 for (int i = 0; i < ClsDefCount; i++)
2124 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002125
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002126 for (int i = 0; i < CatDefCount; i++)
2127 RewriteImplementationDecl(CategoryImplementation[i]);
2128
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002129 // This is needed for use of offsetof
2130 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002131
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002132 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002133 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002134 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002135
2136 // For each implemented category, write out all its meta data.
2137 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002138 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002139
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002140 // Write objc_symtab metadata
2141 /*
2142 struct _objc_symtab
2143 {
2144 long sel_ref_cnt;
2145 SEL *refs;
2146 short cls_def_cnt;
2147 short cat_def_cnt;
2148 void *defs[cls_def_cnt + cat_def_cnt];
2149 };
2150 */
2151
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002152 Result += "\nstruct _objc_symtab {\n";
2153 Result += "\tlong sel_ref_cnt;\n";
2154 Result += "\tSEL *refs;\n";
2155 Result += "\tshort cls_def_cnt;\n";
2156 Result += "\tshort cat_def_cnt;\n";
2157 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2158 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002160 Result += "static struct _objc_symtab "
2161 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2162 Result += "\t0, 0, " + utostr(ClsDefCount)
2163 + ", " + utostr(CatDefCount) + "\n";
2164 for (int i = 0; i < ClsDefCount; i++) {
2165 Result += "\t,&_OBJC_CLASS_";
2166 Result += ClassImplementation[i]->getName();
2167 Result += "\n";
2168 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002169
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002170 for (int i = 0; i < CatDefCount; i++) {
2171 Result += "\t,&_OBJC_CATEGORY_";
2172 Result += CategoryImplementation[i]->getClassInterface()->getName();
2173 Result += "_";
2174 Result += CategoryImplementation[i]->getName();
2175 Result += "\n";
2176 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002177
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002178 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002179
2180 // Write objc_module metadata
2181
2182 /*
2183 struct _objc_module {
2184 long version;
2185 long size;
2186 const char *name;
2187 struct _objc_symtab *symtab;
2188 }
2189 */
2190
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002191 Result += "\nstruct _objc_module {\n";
2192 Result += "\tlong version;\n";
2193 Result += "\tlong size;\n";
2194 Result += "\tconst char *name;\n";
2195 Result += "\tstruct _objc_symtab *symtab;\n";
2196 Result += "};\n\n";
2197 Result += "static struct _objc_module "
2198 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002199 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2200 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002201 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002202
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002203}
Chris Lattner311ff022007-10-16 22:36:42 +00002204