blob: c29241bd0756fe920f578f5a05ef8b49b2d15afb [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//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000054
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000058
Steve Naroff874e2322007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 public:
Ted Kremenek95041a22007-12-19 22:51:13 +000065 void Initialize(ASTContext &context) {
Chris Lattner01c57482007-10-17 22:35:30 +000066 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattner26de4652007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
Ted Kremenek95041a22007-12-19 22:51:13 +000084 MainFileID = SM->getMainFileID();
Chris Lattner26de4652007-12-02 01:13:47 +000085 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000125
Ted Kremenek95041a22007-12-19 22:51:13 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroffab972d32007-11-04 22:37:50 +0000127 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000147 void RewriteMethodDeclaration(ObjcMethodDecl *Method);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane66894c2007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000187 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
189 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194
195 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
196 int NumProtocols,
197 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000200 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
201 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000202 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
203 ObjcIvarDecl *ivar,
204 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattnere365c502007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner8a12c272007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffebf2b562007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Steve Naroffbef11852007-10-26 20:53:56 +0000236 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
237 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000238 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
239 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000240 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
241 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000242 } else if (ObjcForwardProtocolDecl *FP =
243 dyn_cast<ObjcForwardProtocolDecl>(D)){
244 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000245 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000253}
254
Chris Lattnerf04da132007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000261
262 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000269 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000270 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
271 ClassImplementation.push_back(CI);
272 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
273 CategoryImplementation.push_back(CI);
274 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
275 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000277 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000289
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000293
Chris Lattnerf04da132007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306}
307
Chris Lattnerf04da132007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerf04da132007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000340
Chris Lattnerf04da132007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000364}
365
366
Chris Lattnerf04da132007-10-24 17:06:59 +0000367void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
368 int numDecls = ClassDecl->getNumForwardDecls();
369 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
384 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000399}
400
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000401void RewriteTest::RewriteMethodDeclaration(ObjcMethodDecl *Method) {
402 SourceLocation LocStart = Method->getLocStart();
403 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000404
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000405 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
406 Rewrite.InsertText(LocStart, "/* ", 3);
407 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
408 } else {
409 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000410 }
411}
412
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000413void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
414{
415 for (int i = 0; i < nProperties; i++) {
416 ObjcPropertyDecl *Property = Properties[i];
417 SourceLocation Loc = Property->getLocation();
418
419 Rewrite.ReplaceText(Loc, 0, "// ", 3);
420
421 // FIXME: handle properties that are declared across multiple lines.
422 }
423}
424
Steve Naroff423cb562007-10-30 13:30:57 +0000425void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
426 SourceLocation LocStart = CatDecl->getLocStart();
427
428 // FIXME: handle category headers that are declared across multiple lines.
429 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
430
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000431 for (ObjcCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
432 E = CatDecl->instmeth_end(); I != E; ++I)
433 RewriteMethodDeclaration(*I);
434 for (ObjcCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
435 E = CatDecl->classmeth_end(); I != E; ++I)
436 RewriteMethodDeclaration(*I);
437
Steve Naroff423cb562007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Steve Naroff752d6ef2007-10-30 16:42:30 +0000442void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000444
Steve Naroff752d6ef2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000450 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
451 E = PDecl->instmeth_end(); I != E; ++I)
452 RewriteMethodDeclaration(*I);
453 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
454 E = PDecl->classmeth_end(); I != E; ++I)
455 RewriteMethodDeclaration(*I);
456
Steve Naroff752d6ef2007-10-30 16:42:30 +0000457 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000458 SourceLocation LocEnd = PDecl->getAtEndLoc();
459 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000460
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000461 // Must comment out @optional/@required
462 const char *startBuf = SM->getCharacterData(LocStart);
463 const char *endBuf = SM->getCharacterData(LocEnd);
464 for (const char *p = startBuf; p < endBuf; p++) {
465 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
466 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000467 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000468 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
469 CommentedOptional.c_str(), CommentedOptional.size());
470
471 }
472 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
473 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000474 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000475 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
476 CommentedRequired.c_str(), CommentedRequired.size());
477
478 }
479 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000480}
481
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000482void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
483 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000484 if (LocStart.isInvalid())
485 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000486 // FIXME: handle forward protocol that are declared across multiple lines.
487 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
488}
489
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000490void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
491 std::string &ResultStr) {
492 ResultStr += "\nstatic ";
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +0000493 if (OMD->getResultType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000494 ResultStr += "id";
495 else
496 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000497 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000498
499 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000500 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000501
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000502 if (OMD->isInstance())
503 NameStr += "_I_";
504 else
505 NameStr += "_C_";
506
507 NameStr += OMD->getClassInterface()->getName();
508 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509
510 NamedDecl *MethodContext = OMD->getMethodContext();
511 if (ObjcCategoryImplDecl *CID =
512 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000513 NameStr += CID->getName();
514 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515 }
516 // Append selector names, replacing ':' with '_'
517 const char *selName = OMD->getSelector().getName().c_str();
518 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000519 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 else {
521 std::string selString = OMD->getSelector().getName();
522 int len = selString.size();
523 for (int i = 0; i < len; i++)
524 if (selString[i] == ':')
525 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000526 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000527 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000528 // Remember this name for metadata emission
529 MethodInternalNames[OMD] = NameStr;
530 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000531
532 // Rewrite arguments
533 ResultStr += "(";
534
535 // invisible arguments
536 if (OMD->isInstance()) {
537 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
538 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
540 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000541 ResultStr += selfTy.getAsString();
542 }
543 else
544 ResultStr += Context->getObjcIdType().getAsString();
545
546 ResultStr += " self, ";
547 ResultStr += Context->getObjcSelType().getAsString();
548 ResultStr += " _cmd";
549
550 // Method arguments.
551 for (int i = 0; i < OMD->getNumParams(); i++) {
552 ParmVarDecl *PDecl = OMD->getParamDecl(i);
553 ResultStr += ", ";
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +0000554 if (PDecl->getType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000555 ResultStr += "id";
556 else
557 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558 ResultStr += " ";
559 ResultStr += PDecl->getName();
560 }
561 ResultStr += ")";
562
563}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000564void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
565 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
566 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 if (IMD)
569 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
570 else
571 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000572
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000573 for (ObjcCategoryImplDecl::instmeth_iterator
574 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
575 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000577 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000578 RewriteObjcMethodDecl(OMD, ResultStr);
579 SourceLocation LocStart = OMD->getLocStart();
580 SourceLocation LocEnd = OMD->getBody()->getLocStart();
581
582 const char *startBuf = SM->getCharacterData(LocStart);
583 const char *endBuf = SM->getCharacterData(LocEnd);
584 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
585 ResultStr.c_str(), ResultStr.size());
586 }
587
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000588 for (ObjcCategoryImplDecl::classmeth_iterator
589 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
590 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000591 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000592 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000593 RewriteObjcMethodDecl(OMD, ResultStr);
594 SourceLocation LocStart = OMD->getLocStart();
595 SourceLocation LocEnd = OMD->getBody()->getLocStart();
596
597 const char *startBuf = SM->getCharacterData(LocStart);
598 const char *endBuf = SM->getCharacterData(LocEnd);
599 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
600 ResultStr.c_str(), ResultStr.size());
601 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000602 if (IMD)
603 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
604 else
605 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000606}
607
Steve Naroffbef11852007-10-26 20:53:56 +0000608void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000609 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000610 if (!ObjcForwardDecls.count(ClassDecl)) {
611 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000612 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000613 ResultStr += ClassDecl->getName();
614 ResultStr += "\n";
615 ResultStr += "#define _REWRITER_typedef_";
616 ResultStr += ClassDecl->getName();
617 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000618 ResultStr += "typedef struct ";
619 ResultStr += ClassDecl->getName();
620 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000621 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000622 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000623
624 // Mark this typedef as having been generated.
625 ObjcForwardDecls.insert(ClassDecl);
626 }
Steve Narofff908a872007-10-30 02:23:23 +0000627 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
628
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000629 RewriteProperties(ClassDecl->getNumPropertyDecl(),
630 ClassDecl->getPropertyDecl());
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000631 for (ObjcInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
632 E = ClassDecl->instmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
634 for (ObjcInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
635 E = ClassDecl->classmeth_end(); I != E; ++I)
636 RewriteMethodDeclaration(*I);
637
Steve Naroff2feac5e2007-10-30 03:43:13 +0000638 // Lastly, comment out the @end.
639 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000640}
641
Steve Naroff7e3411b2007-11-15 02:58:25 +0000642Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
643 ObjcIvarDecl *D = IV->getDecl();
644 if (IV->isFreeIvar()) {
645 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
646 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000647 if (Rewrite.ReplaceStmt(IV, Replacement)) {
648 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000649 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
650 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000651 SourceRange Range = IV->getSourceRange();
652 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000653 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000654 delete IV;
655 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000656 } else {
657 if (CurMethodDecl) {
658 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
659 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
660 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
661 IdentifierInfo *II = intT->getDecl()->getIdentifier();
662 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
663 II, 0);
664 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
665
666 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
667 // Don't forget the parens to enforce the proper binding.
668 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000669 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
670 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000671 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
672 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000673 SourceRange Range = IV->getBase()->getSourceRange();
674 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000675 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000676 delete IV->getBase();
677 return PE;
678 }
679 }
680 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000681 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000682 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000683}
684
Chris Lattnerf04da132007-10-24 17:06:59 +0000685//===----------------------------------------------------------------------===//
686// Function Body / Expression rewriting
687//===----------------------------------------------------------------------===//
688
Steve Narofff3473a72007-11-09 15:20:18 +0000689Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000690 // Otherwise, just rewrite all children.
691 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
692 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000693 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000694 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000695 if (newStmt)
696 *CI = newStmt;
697 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000698
699 // Handle specific things.
700 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
701 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000702
703 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
704 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000705
706 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
707 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000708
709 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
710 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000711
Steve Naroff934f2762007-10-24 22:48:43 +0000712 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
713 // Before we rewrite it, put the original message expression in a comment.
714 SourceLocation startLoc = MessExpr->getLocStart();
715 SourceLocation endLoc = MessExpr->getLocEnd();
716
717 const char *startBuf = SM->getCharacterData(startLoc);
718 const char *endBuf = SM->getCharacterData(endLoc);
719
720 std::string messString;
721 messString += "// ";
722 messString.append(startBuf, endBuf-startBuf+1);
723 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000724
Steve Naroff934f2762007-10-24 22:48:43 +0000725 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
726 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
727 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000728 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000729 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000730 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000731
732 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
733 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000734
735 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
736 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000737
738 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
739 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000740#if 0
741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
742 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
743 // Get the new text.
744 std::ostringstream Buf;
745 Replacement->printPretty(Buf);
746 const std::string &Str = Buf.str();
747
748 printf("CAST = %s\n", &Str[0]);
749 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
750 delete S;
751 return Replacement;
752 }
753#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000754 // Return this stmt unmodified.
755 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000756}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000757
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000758Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000759 // Get the start location and compute the semi location.
760 SourceLocation startLoc = S->getLocStart();
761 const char *startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '@') && "bogus @try location");
764
765 std::string buf;
766 // declare a new scope with two variables, _stack and _rethrow.
767 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
768 buf += "int buf[18/*32-bit i386*/];\n";
769 buf += "char *pointers[4];} _stack;\n";
770 buf += "id volatile _rethrow = 0;\n";
771 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000772 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000773
774 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
775
776 startLoc = S->getTryBody()->getLocEnd();
777 startBuf = SM->getCharacterData(startLoc);
778
779 assert((*startBuf == '}') && "bogus @try block");
780
781 SourceLocation lastCurlyLoc = startLoc;
782
783 startLoc = startLoc.getFileLocWithOffset(1);
784 buf = " /* @catch begin */ else {\n";
785 buf += " id _caught = objc_exception_extract(&_stack);\n";
786 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000787 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000788 buf += " _rethrow = objc_exception_extract(&_stack);\n";
789 buf += " else { /* @catch continue */";
790
Chris Lattner28d1fe82007-11-08 04:41:51 +0000791 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000792
793 bool sawIdTypedCatch = false;
794 Stmt *lastCatchBody = 0;
795 ObjcAtCatchStmt *catchList = S->getCatchStmts();
796 while (catchList) {
797 Stmt *catchStmt = catchList->getCatchParamStmt();
798
799 if (catchList == S->getCatchStmts())
800 buf = "if ("; // we are generating code for the first catch clause
801 else
802 buf = "else if (";
803 startLoc = catchList->getLocStart();
804 startBuf = SM->getCharacterData(startLoc);
805
806 assert((*startBuf == '@') && "bogus @catch location");
807
808 const char *lParenLoc = strchr(startBuf, '(');
809
810 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
811 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
812 if (t == Context->getObjcIdType()) {
813 buf += "1) { ";
814 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
815 buf.c_str(), buf.size());
816 sawIdTypedCatch = true;
817 } else if (const PointerType *pType = t->getAsPointerType()) {
818 ObjcInterfaceType *cls; // Should be a pointer to a class.
819
820 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
821 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000822 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000823 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000824 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000825 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
826 buf.c_str(), buf.size());
827 }
828 }
829 // Now rewrite the body...
830 lastCatchBody = catchList->getCatchBody();
831 SourceLocation rParenLoc = catchList->getRParenLoc();
832 SourceLocation bodyLoc = lastCatchBody->getLocStart();
833 const char *bodyBuf = SM->getCharacterData(bodyLoc);
834 const char *rParenBuf = SM->getCharacterData(rParenLoc);
835 assert((*rParenBuf == ')') && "bogus @catch paren location");
836 assert((*bodyBuf == '{') && "bogus @catch body location");
837
838 buf = " = _caught;";
839 // Here we replace ") {" with "= _caught;" (which initializes and
840 // declares the @catch parameter).
841 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
842 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000843 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000844 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000845 }
Steve Naroff75730982007-11-07 04:08:17 +0000846 catchList = catchList->getNextCatchStmt();
847 }
848 // Complete the catch list...
849 if (lastCatchBody) {
850 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
851 const char *bodyBuf = SM->getCharacterData(bodyLoc);
852 assert((*bodyBuf == '}') && "bogus @catch body location");
853 bodyLoc = bodyLoc.getFileLocWithOffset(1);
854 buf = " } } /* @catch end */\n";
855
Chris Lattner28d1fe82007-11-08 04:41:51 +0000856 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000857
858 // Set lastCurlyLoc
859 lastCurlyLoc = lastCatchBody->getLocEnd();
860 }
861 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
862 startLoc = finalStmt->getLocStart();
863 startBuf = SM->getCharacterData(startLoc);
864 assert((*startBuf == '@') && "bogus @finally start");
865
866 buf = "/* @finally */";
867 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
868
869 Stmt *body = finalStmt->getFinallyBody();
870 SourceLocation startLoc = body->getLocStart();
871 SourceLocation endLoc = body->getLocEnd();
872 const char *startBuf = SM->getCharacterData(startLoc);
873 const char *endBuf = SM->getCharacterData(endLoc);
874 assert((*startBuf == '{') && "bogus @finally body location");
875 assert((*endBuf == '}') && "bogus @finally body location");
876
877 startLoc = startLoc.getFileLocWithOffset(1);
878 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000879 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000880 endLoc = endLoc.getFileLocWithOffset(-1);
881 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000882 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000883
884 // Set lastCurlyLoc
885 lastCurlyLoc = body->getLocEnd();
886 }
887 // Now emit the final closing curly brace...
888 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
889 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000890 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000891 return 0;
892}
893
894Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
895 return 0;
896}
897
898Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
899 return 0;
900}
901
Steve Naroff2bd03922007-11-07 15:32:26 +0000902// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
903// the throw expression is typically a message expression that's already
904// been rewritten! (which implies the SourceLocation's are invalid).
905Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
906 // Get the start location and compute the semi location.
907 SourceLocation startLoc = S->getLocStart();
908 const char *startBuf = SM->getCharacterData(startLoc);
909
910 assert((*startBuf == '@') && "bogus @throw location");
911
912 std::string buf;
913 /* void objc_exception_throw(id) __attribute__((noreturn)); */
914 buf = "objc_exception_throw(";
915 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
916 const char *semiBuf = strchr(startBuf, ';');
917 assert((*semiBuf == ';') && "@throw: can't find ';'");
918 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
919 buf = ");";
920 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
921 return 0;
922}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000923
Chris Lattnere64b7772007-10-24 16:57:36 +0000924Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000925 // Create a new string expression.
926 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000927 std::string StrEncoding;
928 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
929 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
930 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000931 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000932 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
933 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000934 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
935 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +0000936 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000937 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +0000938 }
939
Chris Lattner07506182007-11-30 22:53:43 +0000940 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000941 delete Exp;
942 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000943}
944
Steve Naroffb42f8412007-11-05 14:50:49 +0000945Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
946 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
947 // Create a call to sel_registerName("selName").
948 llvm::SmallVector<Expr*, 8> SelExprs;
949 QualType argType = Context->getPointerType(Context->CharTy);
950 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
951 Exp->getSelector().getName().size(),
952 false, argType, SourceLocation(),
953 SourceLocation()));
954 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
955 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +0000956 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
957 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000958 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
959 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000960 SourceRange Range = Exp->getSourceRange();
961 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000962 }
Steve Naroffb42f8412007-11-05 14:50:49 +0000963 delete Exp;
964 return SelExp;
965}
966
Steve Naroff934f2762007-10-24 22:48:43 +0000967CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
968 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000969 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000970 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000971
972 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000973 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000974
975 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000976 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000977 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
978
979 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000980
Steve Naroff934f2762007-10-24 22:48:43 +0000981 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
982}
983
Steve Naroffd5255f52007-11-01 13:24:47 +0000984static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
985 const char *&startRef, const char *&endRef) {
986 while (startBuf < endBuf) {
987 if (*startBuf == '<')
988 startRef = startBuf; // mark the start.
989 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000990 if (startRef && *startRef == '<') {
991 endRef = startBuf; // mark the end.
992 return true;
993 }
994 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000995 }
996 startBuf++;
997 }
998 return false;
999}
1000
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001001static void scanToNextArgument(const char *&argRef) {
1002 int angle = 0;
1003 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1004 if (*argRef == '<')
1005 angle++;
1006 else if (*argRef == '>')
1007 angle--;
1008 argRef++;
1009 }
1010 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1011}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001012
Steve Naroffd5255f52007-11-01 13:24:47 +00001013bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001014
Steve Naroffd5255f52007-11-01 13:24:47 +00001015 if (T == Context->getObjcIdType())
1016 return true;
1017
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001018 if (T->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001019 return true;
1020
Steve Naroffd5255f52007-11-01 13:24:47 +00001021 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001022 Type *pointeeType = pType->getPointeeType().getTypePtr();
1023 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1024 return true; // we have "Class <Protocol> *".
1025 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001026 return false;
1027}
1028
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001029void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001030 SourceLocation Loc;
1031 QualType Type;
1032 const FunctionTypeProto *proto = 0;
1033 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1034 Loc = VD->getLocation();
1035 Type = VD->getType();
1036 }
1037 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1038 Loc = FD->getLocation();
1039 // Check for ObjC 'id' and class types that have been adorned with protocol
1040 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1041 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1042 assert(funcType && "missing function type");
1043 proto = dyn_cast<FunctionTypeProto>(funcType);
1044 if (!proto)
1045 return;
1046 Type = proto->getResultType();
1047 }
1048 else
1049 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001050
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001051 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001052 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001053
1054 const char *endBuf = SM->getCharacterData(Loc);
1055 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001056 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001057 startBuf--; // scan backward (from the decl location) for return type.
1058 const char *startRef = 0, *endRef = 0;
1059 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1060 // Get the locations of the startRef, endRef.
1061 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1062 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1063 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001064 Rewrite.InsertText(LessLoc, "/*", 2);
1065 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001066 }
1067 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001068 if (!proto)
1069 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001070 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001071 const char *startBuf = SM->getCharacterData(Loc);
1072 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001073 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1074 if (needToScanForQualifiers(proto->getArgType(i))) {
1075 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001076
Steve Naroffd5255f52007-11-01 13:24:47 +00001077 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001078 // scan forward (from the decl location) for argument types.
1079 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001080 const char *startRef = 0, *endRef = 0;
1081 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1082 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001083 SourceLocation LessLoc =
1084 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1085 SourceLocation GreaterLoc =
1086 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001087 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001088 Rewrite.InsertText(LessLoc, "/*", 2);
1089 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001090 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001091 startBuf = ++endBuf;
1092 }
1093 else {
1094 while (*startBuf != ')' && *startBuf != ',')
1095 startBuf++; // scan forward (from the decl location) for argument types.
1096 startBuf++;
1097 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001098 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001099}
1100
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001101// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1102void RewriteTest::SynthSelGetUidFunctionDecl() {
1103 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1104 llvm::SmallVector<QualType, 16> ArgTys;
1105 ArgTys.push_back(Context->getPointerType(
1106 Context->CharTy.getQualifiedType(QualType::Const)));
1107 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1108 &ArgTys[0], ArgTys.size(),
1109 false /*isVariadic*/);
1110 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1111 SelGetUidIdent, getFuncType,
1112 FunctionDecl::Extern, false, 0);
1113}
1114
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001115// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1116void RewriteTest::SynthGetProtocolFunctionDecl() {
1117 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1118 llvm::SmallVector<QualType, 16> ArgTys;
1119 ArgTys.push_back(Context->getPointerType(
1120 Context->CharTy.getQualifiedType(QualType::Const)));
1121 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1122 &ArgTys[0], ArgTys.size(),
1123 false /*isVariadic*/);
1124 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1125 SelGetProtoIdent, getFuncType,
1126 FunctionDecl::Extern, false, 0);
1127}
1128
Steve Naroff09b266e2007-10-30 23:14:51 +00001129void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1130 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001131 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001132 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001133 return;
1134 }
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001135 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001136}
1137
1138// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1139void RewriteTest::SynthMsgSendFunctionDecl() {
1140 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1141 llvm::SmallVector<QualType, 16> ArgTys;
1142 QualType argT = Context->getObjcIdType();
1143 assert(!argT.isNull() && "Can't find 'id' type");
1144 ArgTys.push_back(argT);
1145 argT = Context->getObjcSelType();
1146 assert(!argT.isNull() && "Can't find 'SEL' type");
1147 ArgTys.push_back(argT);
1148 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1149 &ArgTys[0], ArgTys.size(),
1150 true /*isVariadic*/);
1151 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1152 msgSendIdent, msgSendType,
1153 FunctionDecl::Extern, false, 0);
1154}
1155
Steve Naroff874e2322007-11-15 10:28:18 +00001156// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1157void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1158 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1159 llvm::SmallVector<QualType, 16> ArgTys;
1160 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1161 &Context->Idents.get("objc_super"), 0);
1162 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1163 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1164 ArgTys.push_back(argT);
1165 argT = Context->getObjcSelType();
1166 assert(!argT.isNull() && "Can't find 'SEL' type");
1167 ArgTys.push_back(argT);
1168 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1169 &ArgTys[0], ArgTys.size(),
1170 true /*isVariadic*/);
1171 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1172 msgSendIdent, msgSendType,
1173 FunctionDecl::Extern, false, 0);
1174}
1175
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001176// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1177void RewriteTest::SynthMsgSendStretFunctionDecl() {
1178 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1179 llvm::SmallVector<QualType, 16> ArgTys;
1180 QualType argT = Context->getObjcIdType();
1181 assert(!argT.isNull() && "Can't find 'id' type");
1182 ArgTys.push_back(argT);
1183 argT = Context->getObjcSelType();
1184 assert(!argT.isNull() && "Can't find 'SEL' type");
1185 ArgTys.push_back(argT);
1186 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1187 &ArgTys[0], ArgTys.size(),
1188 true /*isVariadic*/);
1189 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1190 msgSendIdent, msgSendType,
1191 FunctionDecl::Extern, false, 0);
1192}
1193
1194// SynthMsgSendSuperStretFunctionDecl -
1195// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1196void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1197 IdentifierInfo *msgSendIdent =
1198 &Context->Idents.get("objc_msgSendSuper_stret");
1199 llvm::SmallVector<QualType, 16> ArgTys;
1200 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1201 &Context->Idents.get("objc_super"), 0);
1202 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1203 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1204 ArgTys.push_back(argT);
1205 argT = Context->getObjcSelType();
1206 assert(!argT.isNull() && "Can't find 'SEL' type");
1207 ArgTys.push_back(argT);
1208 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1209 &ArgTys[0], ArgTys.size(),
1210 true /*isVariadic*/);
1211 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1212 msgSendIdent, msgSendType,
1213 FunctionDecl::Extern, false, 0);
1214}
1215
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001216// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1217void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1218 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1219 llvm::SmallVector<QualType, 16> ArgTys;
1220 QualType argT = Context->getObjcIdType();
1221 assert(!argT.isNull() && "Can't find 'id' type");
1222 ArgTys.push_back(argT);
1223 argT = Context->getObjcSelType();
1224 assert(!argT.isNull() && "Can't find 'SEL' type");
1225 ArgTys.push_back(argT);
1226 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1227 &ArgTys[0], ArgTys.size(),
1228 true /*isVariadic*/);
1229 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1230 msgSendIdent, msgSendType,
1231 FunctionDecl::Extern, false, 0);
1232}
1233
Steve Naroff09b266e2007-10-30 23:14:51 +00001234// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1235void RewriteTest::SynthGetClassFunctionDecl() {
1236 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1237 llvm::SmallVector<QualType, 16> ArgTys;
1238 ArgTys.push_back(Context->getPointerType(
1239 Context->CharTy.getQualifiedType(QualType::Const)));
1240 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1241 &ArgTys[0], ArgTys.size(),
1242 false /*isVariadic*/);
1243 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1244 getClassIdent, getClassType,
1245 FunctionDecl::Extern, false, 0);
1246}
1247
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001248// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1249void RewriteTest::SynthGetMetaClassFunctionDecl() {
1250 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1251 llvm::SmallVector<QualType, 16> ArgTys;
1252 ArgTys.push_back(Context->getPointerType(
1253 Context->CharTy.getQualifiedType(QualType::Const)));
1254 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1255 &ArgTys[0], ArgTys.size(),
1256 false /*isVariadic*/);
1257 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1258 getClassIdent, getClassType,
1259 FunctionDecl::Extern, false, 0);
1260}
1261
Steve Naroff96984642007-11-08 14:30:50 +00001262// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1263void RewriteTest::SynthCFStringFunctionDecl() {
1264 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1265 llvm::SmallVector<QualType, 16> ArgTys;
1266 ArgTys.push_back(Context->getPointerType(
1267 Context->CharTy.getQualifiedType(QualType::Const)));
1268 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1269 &ArgTys[0], ArgTys.size(),
1270 false /*isVariadic*/);
1271 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1272 getClassIdent, getClassType,
1273 FunctionDecl::Extern, false, 0);
1274}
1275
Steve Naroffbeaf2992007-11-03 11:27:19 +00001276Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001277#if 1
1278 // This rewrite is specific to GCC, which has builtin support for CFString.
1279 if (!CFStringFunctionDecl)
1280 SynthCFStringFunctionDecl();
1281 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1282 llvm::SmallVector<Expr*, 8> StrExpr;
1283 StrExpr.push_back(Exp->getString());
1284 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1285 &StrExpr[0], StrExpr.size());
1286 // cast to NSConstantString *
1287 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001288 if (Rewrite.ReplaceStmt(Exp, cast)) {
1289 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001290 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1291 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001292 SourceRange Range = Exp->getSourceRange();
1293 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001294 }
Steve Naroff96984642007-11-08 14:30:50 +00001295 delete Exp;
1296 return cast;
1297#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001298 assert(ConstantStringClassReference && "Can't find constant string reference");
1299 llvm::SmallVector<Expr*, 4> InitExprs;
1300
1301 // Synthesize "(Class)&_NSConstantStringClassReference"
1302 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1303 ConstantStringClassReference->getType(),
1304 SourceLocation());
1305 QualType expType = Context->getPointerType(ClsRef->getType());
1306 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1307 expType, SourceLocation());
1308 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1309 SourceLocation());
1310 InitExprs.push_back(cast); // set the 'isa'.
1311 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1312 unsigned IntSize = static_cast<unsigned>(
1313 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1314 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1315 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1316 Exp->getLocStart());
1317 InitExprs.push_back(len); // set "int numBytes".
1318
1319 // struct NSConstantString
1320 QualType CFConstantStrType = Context->getCFConstantStringType();
1321 // (struct NSConstantString) { <exprs from above> }
1322 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1323 &InitExprs[0], InitExprs.size(),
1324 SourceLocation());
1325 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1326 // struct NSConstantString *
1327 expType = Context->getPointerType(StrRep->getType());
1328 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1329 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001330 // cast to NSConstantString *
1331 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001332 Rewrite.ReplaceStmt(Exp, cast);
1333 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001334 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001335#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001336}
1337
Steve Naroff874e2322007-11-15 10:28:18 +00001338ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001339 // check if we are sending a message to 'super'
1340 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001341 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1343 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1344 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001345 // is this id<P1..> type?
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001346 if (CE->getType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001347 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001348 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1349 if (ObjcInterfaceType *IT =
1350 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1351 if (IT->getDecl() ==
1352 CurMethodDecl->getClassInterface()->getSuperClass())
1353 return IT->getDecl();
1354 }
1355 }
1356 }
1357 }
1358 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001359 }
Steve Naroff874e2322007-11-15 10:28:18 +00001360 }
1361 return 0;
1362}
1363
1364// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1365QualType RewriteTest::getSuperStructType() {
1366 if (!SuperStructDecl) {
1367 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1368 &Context->Idents.get("objc_super"), 0);
1369 QualType FieldTypes[2];
1370
1371 // struct objc_object *receiver;
1372 FieldTypes[0] = Context->getObjcIdType();
1373 // struct objc_class *super;
1374 FieldTypes[1] = Context->getObjcClassType();
1375 // Create fields
1376 FieldDecl *FieldDecls[2];
1377
1378 for (unsigned i = 0; i < 2; ++i)
1379 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1380
1381 SuperStructDecl->defineBody(FieldDecls, 4);
1382 }
1383 return Context->getTagDeclType(SuperStructDecl);
1384}
1385
Steve Naroff934f2762007-10-24 22:48:43 +00001386Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001387 if (!SelGetUidFunctionDecl)
1388 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001389 if (!MsgSendFunctionDecl)
1390 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001391 if (!MsgSendSuperFunctionDecl)
1392 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001393 if (!MsgSendStretFunctionDecl)
1394 SynthMsgSendStretFunctionDecl();
1395 if (!MsgSendSuperStretFunctionDecl)
1396 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001397 if (!MsgSendFpretFunctionDecl)
1398 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001399 if (!GetClassFunctionDecl)
1400 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001401 if (!GetMetaClassFunctionDecl)
1402 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001403
Steve Naroff874e2322007-11-15 10:28:18 +00001404 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001405 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1406 // May need to use objc_msgSend_stret() as well.
1407 FunctionDecl *MsgSendStretFlavor = 0;
1408 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1409 QualType resultType = mDecl->getResultType();
1410 if (resultType.getCanonicalType()->isStructureType()
1411 || resultType.getCanonicalType()->isUnionType())
1412 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001413 else if (resultType.getCanonicalType()->isRealFloatingType())
1414 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001415 }
Steve Naroff874e2322007-11-15 10:28:18 +00001416
Steve Naroff934f2762007-10-24 22:48:43 +00001417 // Synthesize a call to objc_msgSend().
1418 llvm::SmallVector<Expr*, 8> MsgExprs;
1419 IdentifierInfo *clsName = Exp->getClassName();
1420
1421 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1422 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001423 if (!strcmp(clsName->getName(), "super")) {
1424 MsgSendFlavor = MsgSendSuperFunctionDecl;
1425 if (MsgSendStretFlavor)
1426 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1427 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1428
1429 ObjcInterfaceDecl *SuperDecl =
1430 CurMethodDecl->getClassInterface()->getSuperClass();
1431
1432 llvm::SmallVector<Expr*, 4> InitExprs;
1433
1434 // set the receiver to self, the first argument to all methods.
1435 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1436 Context->getObjcIdType(),
1437 SourceLocation()));
1438 llvm::SmallVector<Expr*, 8> ClsExprs;
1439 QualType argType = Context->getPointerType(Context->CharTy);
1440 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1441 SuperDecl->getIdentifier()->getLength(),
1442 false, argType, SourceLocation(),
1443 SourceLocation()));
1444 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1445 &ClsExprs[0],
1446 ClsExprs.size());
1447 // To turn off a warning, type-cast to 'id'
1448 InitExprs.push_back(
1449 new CastExpr(Context->getObjcIdType(),
1450 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1451 // struct objc_super
1452 QualType superType = getSuperStructType();
1453 // (struct objc_super) { <exprs from above> }
1454 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1455 &InitExprs[0], InitExprs.size(),
1456 SourceLocation());
1457 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1458 // struct objc_super *
1459 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1460 Context->getPointerType(SuperRep->getType()),
1461 SourceLocation());
1462 MsgExprs.push_back(Unop);
1463 } else {
1464 llvm::SmallVector<Expr*, 8> ClsExprs;
1465 QualType argType = Context->getPointerType(Context->CharTy);
1466 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1467 clsName->getLength(),
1468 false, argType, SourceLocation(),
1469 SourceLocation()));
1470 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1471 &ClsExprs[0],
1472 ClsExprs.size());
1473 MsgExprs.push_back(Cls);
1474 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001475 } else { // instance message.
1476 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001477
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001478 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001479 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001480 if (MsgSendStretFlavor)
1481 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001482 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1483
1484 llvm::SmallVector<Expr*, 4> InitExprs;
1485
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001486 InitExprs.push_back(
1487 new CastExpr(Context->getObjcIdType(),
1488 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001489
1490 llvm::SmallVector<Expr*, 8> ClsExprs;
1491 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001492 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1493 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001494 false, argType, SourceLocation(),
1495 SourceLocation()));
1496 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001497 &ClsExprs[0],
1498 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001499 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001500 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001501 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001502 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001503 // struct objc_super
1504 QualType superType = getSuperStructType();
1505 // (struct objc_super) { <exprs from above> }
1506 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1507 &InitExprs[0], InitExprs.size(),
1508 SourceLocation());
1509 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1510 // struct objc_super *
1511 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1512 Context->getPointerType(SuperRep->getType()),
1513 SourceLocation());
1514 MsgExprs.push_back(Unop);
1515 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001516 // Remove all type-casts because it may contain objc-style types; e.g.
1517 // Foo<Proto> *.
1518 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1519 recExpr = CE->getSubExpr();
Steve Naroff874e2322007-11-15 10:28:18 +00001520 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1521 MsgExprs.push_back(recExpr);
1522 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001523 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001524 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001525 llvm::SmallVector<Expr*, 8> SelExprs;
1526 QualType argType = Context->getPointerType(Context->CharTy);
1527 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1528 Exp->getSelector().getName().size(),
1529 false, argType, SourceLocation(),
1530 SourceLocation()));
1531 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1532 &SelExprs[0], SelExprs.size());
1533 MsgExprs.push_back(SelExp);
1534
1535 // Now push any user supplied arguments.
1536 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001537 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001538 // Make all implicit casts explicit...ICE comes in handy:-)
1539 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1540 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001541 userExpr = new CastExpr(ICE->getType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001542 ? Context->getObjcIdType()
1543 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001544 }
1545 // Make id<P...> cast into an 'id' cast.
1546 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
1547 if (CE->getType()->isObjcQualifiedIdType()) {
1548 while ((CE = dyn_cast<CastExpr>(userExpr)))
1549 userExpr = CE->getSubExpr();
1550 userExpr = new CastExpr(Context->getObjcIdType(),
1551 userExpr, SourceLocation());
1552 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001553 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001554 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001555 // We've transferred the ownership to MsgExprs. Null out the argument in
1556 // the original expression, since we will delete it below.
1557 Exp->setArg(i, 0);
1558 }
Steve Naroffab972d32007-11-04 22:37:50 +00001559 // Generate the funky cast.
1560 CastExpr *cast;
1561 llvm::SmallVector<QualType, 8> ArgTypes;
1562 QualType returnType;
1563
1564 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001565 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1566 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1567 else
1568 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001569 ArgTypes.push_back(Context->getObjcSelType());
1570 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1571 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001572 for (int i = 0; i < mDecl->getNumParams(); i++) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001573 QualType t = mDecl->getParamDecl(i)->getType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001574 ? Context->getObjcIdType()
1575 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001576 ArgTypes.push_back(t);
1577 }
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001578 returnType = mDecl->getResultType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001579 ? Context->getObjcIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001580 } else {
1581 returnType = Context->getObjcIdType();
1582 }
1583 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001584 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001585
1586 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001587 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1588 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001589
1590 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1591 // If we don't do this cast, we get the following bizarre warning/note:
1592 // xx.m:13: warning: function called through a non-compatible type
1593 // xx.m:13: note: if this code is reached, the program will abort
1594 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1595 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001596
Steve Naroffab972d32007-11-04 22:37:50 +00001597 // Now do the "normal" pointer to function cast.
1598 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001599 &ArgTypes[0], ArgTypes.size(),
1600 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001601 castType = Context->getPointerType(castType);
1602 cast = new CastExpr(castType, cast, SourceLocation());
1603
1604 // Don't forget the parens to enforce the proper binding.
1605 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1606
1607 const FunctionType *FT = msgSendType->getAsFunctionType();
1608 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1609 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001610 if (MsgSendStretFlavor) {
1611 // We have the method which returns a struct/union. Must also generate
1612 // call to objc_msgSend_stret and hang both varieties on a conditional
1613 // expression which dictate which one to envoke depending on size of
1614 // method's return type.
1615
1616 // Create a reference to the objc_msgSend_stret() declaration.
1617 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1618 SourceLocation());
1619 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1620 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1621 SourceLocation());
1622 // Now do the "normal" pointer to function cast.
1623 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001624 &ArgTypes[0], ArgTypes.size(),
1625 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001626 castType = Context->getPointerType(castType);
1627 cast = new CastExpr(castType, cast, SourceLocation());
1628
1629 // Don't forget the parens to enforce the proper binding.
1630 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1631
1632 FT = msgSendType->getAsFunctionType();
1633 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1634 FT->getResultType(), SourceLocation());
1635
1636 // Build sizeof(returnType)
1637 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1638 returnType, Context->getSizeType(),
1639 SourceLocation(), SourceLocation());
1640 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1641 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1642 // For X86 it is more complicated and some kind of target specific routine
1643 // is needed to decide what to do.
1644 unsigned IntSize = static_cast<unsigned>(
1645 Context->getTypeSize(Context->IntTy, SourceLocation()));
1646
1647 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1648 Context->IntTy,
1649 SourceLocation());
1650 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1651 BinaryOperator::LE,
1652 Context->IntTy,
1653 SourceLocation());
1654 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1655 ConditionalOperator *CondExpr =
1656 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1657 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1658 // Now do the actual rewrite.
Steve Naroff5ca40202007-12-19 14:32:56 +00001659 if (Rewrite.ReplaceStmt(Exp, PE)) {
1660 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001661 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1662 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001663 SourceRange Range = Exp->getSourceRange();
1664 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001665 }
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001666 delete Exp;
1667 return PE;
1668 }
Steve Naroff934f2762007-10-24 22:48:43 +00001669 // Now do the actual rewrite.
Steve Naroff5ca40202007-12-19 14:32:56 +00001670 if (Rewrite.ReplaceStmt(Exp, CE)) {
1671 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001672 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1673 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001674 SourceRange Range = Exp->getSourceRange();
1675 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001676 }
Steve Naroff934f2762007-10-24 22:48:43 +00001677
Chris Lattnere64b7772007-10-24 16:57:36 +00001678 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001679 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001680}
1681
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001682/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1683/// call to objc_getProtocol("proto-name").
1684Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1685 if (!GetProtocolFunctionDecl)
1686 SynthGetProtocolFunctionDecl();
1687 // Create a call to objc_getProtocol("ProtocolName").
1688 llvm::SmallVector<Expr*, 8> ProtoExprs;
1689 QualType argType = Context->getPointerType(Context->CharTy);
1690 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1691 strlen(Exp->getProtocol()->getName()),
1692 false, argType, SourceLocation(),
1693 SourceLocation()));
1694 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1695 &ProtoExprs[0],
1696 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001697 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1698 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001699 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1700 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001701 SourceRange Range = Exp->getSourceRange();
1702 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001703 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001704 delete Exp;
1705 return ProtoExp;
1706
1707}
1708
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001709/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1710/// an objective-c class with ivars.
1711void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1712 std::string &Result) {
1713 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1714 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001715 // Do not synthesize more than once.
1716 if (ObjcSynthesizedStructs.count(CDecl))
1717 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001718 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001719 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001720 SourceLocation LocStart = CDecl->getLocStart();
1721 SourceLocation LocEnd = CDecl->getLocEnd();
1722
1723 const char *startBuf = SM->getCharacterData(LocStart);
1724 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001725 // If no ivars and no root or if its root, directly or indirectly,
1726 // have no ivars (thus not synthesized) then no need to synthesize this class.
1727 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001728 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1729 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1730 Result.c_str(), Result.size());
1731 return;
1732 }
1733
1734 // FIXME: This has potential of causing problem. If
1735 // SynthesizeObjcInternalStruct is ever called recursively.
1736 Result += "\nstruct ";
1737 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001738
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001739 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001740 const char *cursor = strchr(startBuf, '{');
1741 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001742 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001743
1744 // rewrite the original header *without* disturbing the '{'
1745 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1746 Result.c_str(), Result.size());
1747 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1748 Result = "\n struct ";
1749 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001750 // Note: We don't name the field decl. This simplifies the "codegen" for
1751 // accessing a superclasses instance variables (and is similar to what gcc
1752 // does internally). The unnamed struct field feature is enabled with
1753 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1754 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001755 Result += ";\n";
1756
1757 // insert the super class structure definition.
1758 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1759 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1760 }
1761 cursor++; // past '{'
1762
1763 // Now comment out any visibility specifiers.
1764 while (cursor < endBuf) {
1765 if (*cursor == '@') {
1766 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001767 // Skip whitespace.
1768 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1769 /*scan*/;
1770
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001771 // FIXME: presence of @public, etc. inside comment results in
1772 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001773 if (!strncmp(cursor, "public", strlen("public")) ||
1774 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001775 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001776 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001777 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001778 // FIXME: If there are cases where '<' is used in ivar declaration part
1779 // of user code, then scan the ivar list and use needToScanForQualifiers
1780 // for type checking.
1781 else if (*cursor == '<') {
1782 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1783 Rewrite.InsertText(atLoc, "/* ", 3);
1784 cursor = strchr(cursor, '>');
1785 cursor++;
1786 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1787 Rewrite.InsertText(atLoc, " */", 3);
1788 }
Steve Narofffea763e82007-11-14 19:25:57 +00001789 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001790 }
Steve Narofffea763e82007-11-14 19:25:57 +00001791 // Don't forget to add a ';'!!
1792 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1793 } else { // we don't have any instance variables - insert super struct.
1794 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1795 Result += " {\n struct ";
1796 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001797 // Note: We don't name the field decl. This simplifies the "codegen" for
1798 // accessing a superclasses instance variables (and is similar to what gcc
1799 // does internally). The unnamed struct field feature is enabled with
1800 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1801 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001802 Result += ";\n};\n";
1803 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1804 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001805 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001806 // Mark this struct as having been generated.
1807 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001808 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001809}
1810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001811// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1812/// class methods.
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001813void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1814 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001815 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001816 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001817 const char *ClassName,
1818 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001819 if (MethodBegin == MethodEnd) return;
1820
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001821 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001822 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001823 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001824 SEL _cmd;
1825 char *method_types;
1826 void *_imp;
1827 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001828 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001829 Result += "\nstruct _objc_method {\n";
1830 Result += "\tSEL _cmd;\n";
1831 Result += "\tchar *method_types;\n";
1832 Result += "\tvoid *_imp;\n";
1833 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001834
1835 /* struct _objc_method_list {
1836 struct _objc_method_list *next_method;
1837 int method_count;
1838 struct _objc_method method_list[];
1839 }
1840 */
1841 Result += "\nstruct _objc_method_list {\n";
1842 Result += "\tstruct _objc_method_list *next_method;\n";
1843 Result += "\tint method_count;\n";
1844 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001845 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001846 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001847
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001848 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001849 Result += "\nstatic struct _objc_method_list _OBJC_";
1850 Result += prefix;
1851 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1852 Result += "_METHODS_";
1853 Result += ClassName;
1854 Result += " __attribute__ ((section (\"__OBJC, __";
1855 Result += IsInstanceMethod ? "inst" : "cls";
1856 Result += "_meth\")))= ";
1857 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001858
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001859 Result += "\t,{{(SEL)\"";
1860 Result += (*MethodBegin)->getSelector().getName().c_str();
1861 std::string MethodTypeString;
1862 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1863 Result += "\", \"";
1864 Result += MethodTypeString;
1865 Result += "\", ";
1866 Result += MethodInternalNames[*MethodBegin];
1867 Result += "}\n";
1868 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1869 Result += "\t ,{(SEL)\"";
1870 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001871 std::string MethodTypeString;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001872 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001873 Result += "\", \"";
1874 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001875 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001876 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001877 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001878 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001879 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001880}
1881
1882/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1883void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1884 int NumProtocols,
1885 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001886 const char *ClassName,
1887 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001888 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001889 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001890 for (int i = 0; i < NumProtocols; i++) {
1891 ObjcProtocolDecl *PDecl = Protocols[i];
1892 // Output struct protocol_methods holder of method selector and type.
1893 if (!objc_protocol_methods &&
1894 (PDecl->getNumInstanceMethods() > 0
1895 || PDecl->getNumClassMethods() > 0)) {
1896 /* struct protocol_methods {
1897 SEL _cmd;
1898 char *method_types;
1899 }
1900 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001901 Result += "\nstruct protocol_methods {\n";
1902 Result += "\tSEL _cmd;\n";
1903 Result += "\tchar *method_types;\n";
1904 Result += "};\n";
1905
1906 /* struct _objc_protocol_method_list {
1907 int protocol_method_count;
1908 struct protocol_methods protocols[];
1909 }
1910 */
1911 Result += "\nstruct _objc_protocol_method_list {\n";
1912 Result += "\tint protocol_method_count;\n";
1913 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001914 objc_protocol_methods = true;
1915 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001916
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001917 int NumMethods = PDecl->getNumInstanceMethods();
1918 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001919 Result += "\nstatic struct _objc_protocol_method_list "
1920 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1921 Result += PDecl->getName();
1922 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1923 "{\n\t" + utostr(NumMethods) + "\n";
1924
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001925 // Output instance methods declared in this protocol.
1926 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1927 E = PDecl->instmeth_end(); I != E; ++I) {
1928 if (I == PDecl->instmeth_begin())
1929 Result += "\t ,{{(SEL)\"";
1930 else
1931 Result += "\t ,{(SEL)\"";
1932 Result += (*I)->getSelector().getName().c_str();
1933 std::string MethodTypeString;
1934 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
1935 Result += "\", \"";
1936 Result += MethodTypeString;
1937 Result += "\"}\n";
1938 }
1939 Result += "\t }\n};\n";
1940 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001941
1942 // Output class methods declared in this protocol.
1943 NumMethods = PDecl->getNumClassMethods();
1944 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001945 Result += "\nstatic struct _objc_protocol_method_list "
1946 "_OBJC_PROTOCOL_CLASS_METHODS_";
1947 Result += PDecl->getName();
1948 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1949 "{\n\t";
1950 Result += utostr(NumMethods);
1951 Result += "\n";
1952
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00001953 // Output instance methods declared in this protocol.
1954 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
1955 E = PDecl->classmeth_end(); I != E; ++I) {
1956 if (I == PDecl->classmeth_begin())
1957 Result += "\t ,{{(SEL)\"";
1958 else
1959 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001960 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001961 std::string MethodTypeString;
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001962 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001963 Result += "\", \"";
1964 Result += MethodTypeString;
1965 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001966 }
1967 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001968 }
1969 // Output:
1970 /* struct _objc_protocol {
1971 // Objective-C 1.0 extensions
1972 struct _objc_protocol_extension *isa;
1973 char *protocol_name;
1974 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001975 struct _objc_protocol_method_list *instance_methods;
1976 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001977 };
1978 */
1979 static bool objc_protocol = false;
1980 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001981 Result += "\nstruct _objc_protocol {\n";
1982 Result += "\tstruct _objc_protocol_extension *isa;\n";
1983 Result += "\tchar *protocol_name;\n";
1984 Result += "\tstruct _objc_protocol **protocol_list;\n";
1985 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1986 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1987 Result += "};\n";
1988
1989 /* struct _objc_protocol_list {
1990 struct _objc_protocol_list *next;
1991 int protocol_count;
1992 struct _objc_protocol *class_protocols[];
1993 }
1994 */
1995 Result += "\nstruct _objc_protocol_list {\n";
1996 Result += "\tstruct _objc_protocol_list *next;\n";
1997 Result += "\tint protocol_count;\n";
1998 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1999 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002000 objc_protocol = true;
2001 }
2002
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002003 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2004 Result += PDecl->getName();
2005 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2006 "{\n\t0, \"";
2007 Result += PDecl->getName();
2008 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002009 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002010 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2011 Result += PDecl->getName();
2012 Result += ", ";
2013 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002014 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002015 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002016 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002017 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2018 Result += PDecl->getName();
2019 Result += "\n";
2020 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002021 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002022 Result += "0\n";
2023 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002024 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002025 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002026 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2027 Result += prefix;
2028 Result += "_PROTOCOLS_";
2029 Result += ClassName;
2030 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2031 "{\n\t0, ";
2032 Result += utostr(NumProtocols);
2033 Result += "\n";
2034
2035 Result += "\t,{&_OBJC_PROTOCOL_";
2036 Result += Protocols[0]->getName();
2037 Result += " \n";
2038
2039 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002040 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002041 Result += "\t ,&_OBJC_PROTOCOL_";
2042 Result += PDecl->getName();
2043 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002044 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002045 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002046 }
2047}
2048
2049/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
2050/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002051void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
2052 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002053 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
2054 // Find category declaration for this implementation.
2055 ObjcCategoryDecl *CDecl;
2056 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2057 CDecl = CDecl->getNextClassCategory())
2058 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2059 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002060
Chris Lattnereb44eee2007-12-23 01:40:15 +00002061 std::string FullCategoryName = ClassDecl->getName();
2062 FullCategoryName += '_';
2063 FullCategoryName += IDecl->getName();
2064
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002065 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002066 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002067 true, "CATEGORY_", FullCategoryName.c_str(),
2068 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002069
2070 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002071 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002072 false, "CATEGORY_", FullCategoryName.c_str(),
2073 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002074
2075 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002076 // Null CDecl is case of a category implementation with no category interface
2077 if (CDecl)
2078 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2079 CDecl->getNumReferencedProtocols(),
2080 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002081 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002082
2083 /* struct _objc_category {
2084 char *category_name;
2085 char *class_name;
2086 struct _objc_method_list *instance_methods;
2087 struct _objc_method_list *class_methods;
2088 struct _objc_protocol_list *protocols;
2089 // Objective-C 1.0 extensions
2090 uint32_t size; // sizeof (struct _objc_category)
2091 struct _objc_property_list *instance_properties; // category's own
2092 // @property decl.
2093 };
2094 */
2095
2096 static bool objc_category = false;
2097 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002098 Result += "\nstruct _objc_category {\n";
2099 Result += "\tchar *category_name;\n";
2100 Result += "\tchar *class_name;\n";
2101 Result += "\tstruct _objc_method_list *instance_methods;\n";
2102 Result += "\tstruct _objc_method_list *class_methods;\n";
2103 Result += "\tstruct _objc_protocol_list *protocols;\n";
2104 Result += "\tunsigned int size;\n";
2105 Result += "\tstruct _objc_property_list *instance_properties;\n";
2106 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002107 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002108 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002109 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2110 Result += FullCategoryName;
2111 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2112 Result += IDecl->getName();
2113 Result += "\"\n\t, \"";
2114 Result += ClassDecl->getName();
2115 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002116
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002117 if (IDecl->getNumInstanceMethods() > 0) {
2118 Result += "\t, (struct _objc_method_list *)"
2119 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2120 Result += FullCategoryName;
2121 Result += "\n";
2122 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002123 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002124 Result += "\t, 0\n";
2125 if (IDecl->getNumClassMethods() > 0) {
2126 Result += "\t, (struct _objc_method_list *)"
2127 "&_OBJC_CATEGORY_CLASS_METHODS_";
2128 Result += FullCategoryName;
2129 Result += "\n";
2130 }
2131 else
2132 Result += "\t, 0\n";
2133
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002134 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002135 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2136 Result += FullCategoryName;
2137 Result += "\n";
2138 }
2139 else
2140 Result += "\t, 0\n";
2141 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002142}
2143
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002144/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2145/// ivar offset.
2146void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2147 ObjcIvarDecl *ivar,
2148 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002149 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002150 Result += IDecl->getName();
2151 Result += ", ";
2152 Result += ivar->getName();
2153 Result += ")";
2154}
2155
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002156//===----------------------------------------------------------------------===//
2157// Meta Data Emission
2158//===----------------------------------------------------------------------===//
2159
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002160void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2161 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002162 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2163
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002164 // Explictly declared @interface's are already synthesized.
2165 if (CDecl->ImplicitInterfaceDecl()) {
2166 // FIXME: Implementation of a class with no @interface (legacy) doese not
2167 // produce correct synthesis as yet.
2168 SynthesizeObjcInternalStruct(CDecl, Result);
2169 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002170
Chris Lattnerbe6df082007-12-12 07:56:42 +00002171 // Build _objc_ivar_list metadata for classes ivars if needed
2172 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2173 ? IDecl->getImplDeclNumIvars()
2174 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002175 if (NumIvars > 0) {
2176 static bool objc_ivar = false;
2177 if (!objc_ivar) {
2178 /* struct _objc_ivar {
2179 char *ivar_name;
2180 char *ivar_type;
2181 int ivar_offset;
2182 };
2183 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002184 Result += "\nstruct _objc_ivar {\n";
2185 Result += "\tchar *ivar_name;\n";
2186 Result += "\tchar *ivar_type;\n";
2187 Result += "\tint ivar_offset;\n";
2188 Result += "};\n";
2189
2190 /* struct _objc_ivar_list {
2191 int ivar_count;
2192 struct _objc_ivar ivar_list[];
2193 };
2194 */
2195 Result += "\nstruct _objc_ivar_list {\n";
2196 Result += "\tint ivar_count;\n";
2197 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002198 objc_ivar = true;
2199 }
2200
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002201 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2202 Result += IDecl->getName();
2203 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2204 "{\n\t";
2205 Result += utostr(NumIvars);
2206 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002207
2208 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2209 if (IDecl->getImplDeclNumIvars() > 0) {
2210 IVI = IDecl->ivar_begin();
2211 IVE = IDecl->ivar_end();
2212 } else {
2213 IVI = CDecl->ivar_begin();
2214 IVE = CDecl->ivar_end();
2215 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002216 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002217 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002218 Result += "\", \"";
2219 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002220 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002221 Result += StrEncoding;
2222 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002223 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002224 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002225 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002226 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002227 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002228 Result += "\", \"";
2229 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002230 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002231 Result += StrEncoding;
2232 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002233 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002234 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002235 }
2236
2237 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002238 }
2239
2240 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002241 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2242 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002243
2244 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002245 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2246 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002247
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002248 // Protocols referenced in class declaration?
2249 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2250 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002251 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002252
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002253
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002254 // Declaration of class/meta-class metadata
2255 /* struct _objc_class {
2256 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002257 const char *super_class_name;
2258 char *name;
2259 long version;
2260 long info;
2261 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002262 struct _objc_ivar_list *ivars;
2263 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002264 struct objc_cache *cache;
2265 struct objc_protocol_list *protocols;
2266 const char *ivar_layout;
2267 struct _objc_class_ext *ext;
2268 };
2269 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002270 static bool objc_class = false;
2271 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002272 Result += "\nstruct _objc_class {\n";
2273 Result += "\tstruct _objc_class *isa;\n";
2274 Result += "\tconst char *super_class_name;\n";
2275 Result += "\tchar *name;\n";
2276 Result += "\tlong version;\n";
2277 Result += "\tlong info;\n";
2278 Result += "\tlong instance_size;\n";
2279 Result += "\tstruct _objc_ivar_list *ivars;\n";
2280 Result += "\tstruct _objc_method_list *methods;\n";
2281 Result += "\tstruct objc_cache *cache;\n";
2282 Result += "\tstruct _objc_protocol_list *protocols;\n";
2283 Result += "\tconst char *ivar_layout;\n";
2284 Result += "\tstruct _objc_class_ext *ext;\n";
2285 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002286 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002287 }
2288
2289 // Meta-class metadata generation.
2290 ObjcInterfaceDecl *RootClass = 0;
2291 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2292 while (SuperClass) {
2293 RootClass = SuperClass;
2294 SuperClass = SuperClass->getSuperClass();
2295 }
2296 SuperClass = CDecl->getSuperClass();
2297
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002298 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2299 Result += CDecl->getName();
2300 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2301 "{\n\t(struct _objc_class *)\"";
2302 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2303 Result += "\"";
2304
2305 if (SuperClass) {
2306 Result += ", \"";
2307 Result += SuperClass->getName();
2308 Result += "\", \"";
2309 Result += CDecl->getName();
2310 Result += "\"";
2311 }
2312 else {
2313 Result += ", 0, \"";
2314 Result += CDecl->getName();
2315 Result += "\"";
2316 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002317 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002318 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002319 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002320 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002321 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002322 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002323 Result += "\n";
2324 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002325 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002326 Result += ", 0\n";
2327 if (CDecl->getNumIntfRefProtocols() > 0) {
2328 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2329 Result += CDecl->getName();
2330 Result += ",0,0\n";
2331 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002332 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002333 Result += "\t,0,0,0,0\n";
2334 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002335
2336 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002337 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2338 Result += CDecl->getName();
2339 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2340 "{\n\t&_OBJC_METACLASS_";
2341 Result += CDecl->getName();
2342 if (SuperClass) {
2343 Result += ", \"";
2344 Result += SuperClass->getName();
2345 Result += "\", \"";
2346 Result += CDecl->getName();
2347 Result += "\"";
2348 }
2349 else {
2350 Result += ", 0, \"";
2351 Result += CDecl->getName();
2352 Result += "\"";
2353 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002354 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002355 Result += ", 0,1";
2356 if (!ObjcSynthesizedStructs.count(CDecl))
2357 Result += ",0";
2358 else {
2359 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002360 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002361 Result += CDecl->getName();
2362 Result += ")";
2363 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002364 if (NumIvars > 0) {
2365 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2366 Result += CDecl->getName();
2367 Result += "\n\t";
2368 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002369 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002370 Result += ",0";
2371 if (IDecl->getNumInstanceMethods() > 0) {
2372 Result += ", &_OBJC_INSTANCE_METHODS_";
2373 Result += CDecl->getName();
2374 Result += ", 0\n\t";
2375 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002376 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002377 Result += ",0,0";
2378 if (CDecl->getNumIntfRefProtocols() > 0) {
2379 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2380 Result += CDecl->getName();
2381 Result += ", 0,0\n";
2382 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002383 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002384 Result += ",0,0,0\n";
2385 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002386}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002387
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002388/// RewriteImplementations - This routine rewrites all method implementations
2389/// and emits meta-data.
2390
2391void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002392 int ClsDefCount = ClassImplementation.size();
2393 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002394
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002395 if (ClsDefCount == 0 && CatDefCount == 0)
2396 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002397 // Rewrite implemented methods
2398 for (int i = 0; i < ClsDefCount; i++)
2399 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002400
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002401 for (int i = 0; i < CatDefCount; i++)
2402 RewriteImplementationDecl(CategoryImplementation[i]);
2403
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002404 // This is needed for use of offsetof
2405 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002406
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002407 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002408 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002409 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002410
2411 // For each implemented category, write out all its meta data.
2412 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002413 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002414
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002415 // Write objc_symtab metadata
2416 /*
2417 struct _objc_symtab
2418 {
2419 long sel_ref_cnt;
2420 SEL *refs;
2421 short cls_def_cnt;
2422 short cat_def_cnt;
2423 void *defs[cls_def_cnt + cat_def_cnt];
2424 };
2425 */
2426
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002427 Result += "\nstruct _objc_symtab {\n";
2428 Result += "\tlong sel_ref_cnt;\n";
2429 Result += "\tSEL *refs;\n";
2430 Result += "\tshort cls_def_cnt;\n";
2431 Result += "\tshort cat_def_cnt;\n";
2432 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2433 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002434
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002435 Result += "static struct _objc_symtab "
2436 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2437 Result += "\t0, 0, " + utostr(ClsDefCount)
2438 + ", " + utostr(CatDefCount) + "\n";
2439 for (int i = 0; i < ClsDefCount; i++) {
2440 Result += "\t,&_OBJC_CLASS_";
2441 Result += ClassImplementation[i]->getName();
2442 Result += "\n";
2443 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002444
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002445 for (int i = 0; i < CatDefCount; i++) {
2446 Result += "\t,&_OBJC_CATEGORY_";
2447 Result += CategoryImplementation[i]->getClassInterface()->getName();
2448 Result += "_";
2449 Result += CategoryImplementation[i]->getName();
2450 Result += "\n";
2451 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002452
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002453 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002454
2455 // Write objc_module metadata
2456
2457 /*
2458 struct _objc_module {
2459 long version;
2460 long size;
2461 const char *name;
2462 struct _objc_symtab *symtab;
2463 }
2464 */
2465
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002466 Result += "\nstruct _objc_module {\n";
2467 Result += "\tlong version;\n";
2468 Result += "\tlong size;\n";
2469 Result += "\tconst char *name;\n";
2470 Result += "\tstruct _objc_symtab *symtab;\n";
2471 Result += "};\n\n";
2472 Result += "static struct _objc_module "
2473 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002474 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2475 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002476 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002477
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002478}
Chris Lattner311ff022007-10-16 22:36:42 +00002479