blob: 529f524d59ffb837d2b5aed58964d21261b055e0 [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;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 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.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000060 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 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 Jahanian33b9c4e2008-01-08 22:06:28 +0000124 "#include <objc/objc.h>\n"
125 "struct __objcFastEnumerationState {\n\t"
126 "unsigned long state;\n\t"
127 "id *itemsPtr;\n\t"
128 "unsigned long *mutationsPtr;\n\t"
129 "unsigned long extra[5];\n};\n";
130
Ted Kremenek95041a22007-12-19 22:51:13 +0000131 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroffab972d32007-11-04 22:37:50 +0000132 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000133 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000138 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 ~RewriteTest();
140
141 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000142 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000143 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000145 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
146 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000147 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
149 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
150 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
151 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
152 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
153 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000154 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000155 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000156 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000158 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000159
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000161 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000162 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000163 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000164 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000165 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000166 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000167 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000168 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
169 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
170 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
171 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000172 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000173 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
174 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000175 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
176 void SynthCountByEnumWithState(std::string &buf);
177
Steve Naroff09b266e2007-10-30 23:14:51 +0000178 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000179 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000180 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000181 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000182 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000183 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000184 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000185 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000191 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000192
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000194 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000195
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
197 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000198 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000199 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000200 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000201 const char *ClassName,
202 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000204 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000205 int NumProtocols,
206 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000207 const char *ClassName,
208 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000210 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
212 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000213 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000214 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000215 };
216}
217
Chris Lattnere365c502007-11-30 22:25:36 +0000218ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
219 return new RewriteTest(Diags);
220}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222//===----------------------------------------------------------------------===//
223// Top Level Driver Code
224//===----------------------------------------------------------------------===//
225
Chris Lattner8a12c272007-10-11 18:38:32 +0000226void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000227 // Two cases: either the decl could be in the main file, or it could be in a
228 // #included file. If the former, rewrite it now. If the later, check to see
229 // if we rewrote the #include/#import.
230 SourceLocation Loc = D->getLocation();
231 Loc = SM->getLogicalLoc(Loc);
232
233 // If this is for a builtin, ignore it.
234 if (Loc.isInvalid()) return;
235
Steve Naroffebf2b562007-10-23 23:50:29 +0000236 // Look for built-in declarations that we need to refer during the rewrite.
237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000238 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000239 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
240 // declared in <Foundation/NSString.h>
241 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
242 ConstantStringClassReference = FVD;
243 return;
244 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000246 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000248 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000250 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000251 } else if (ObjCForwardProtocolDecl *FP =
252 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000253 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000254 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000255 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000256 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
257 return HandleDeclInMainFile(D);
258
Chris Lattnerf04da132007-10-24 17:06:59 +0000259 // Otherwise, see if there is a #import in the main file that should be
260 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000261 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000262}
263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264/// HandleDeclInMainFile - This is called for each top-level decl defined in the
265/// main file of the input.
266void RewriteTest::HandleDeclInMainFile(Decl *D) {
267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
268 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000269 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000270
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000271 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000272 if (Stmt *Body = MD->getBody()) {
273 //Body->dump();
274 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000275 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000276 CurMethodDecl = 0;
277 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000278 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000279 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000280 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000281 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000282 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000284 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000285 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000287 if (VD->getInit())
288 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
289 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000290 // Nothing yet.
291}
292
293RewriteTest::~RewriteTest() {
294 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000295
296 // Rewrite tabs if we care.
297 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000298
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000299 // Rewrite Objective-c meta data*
300 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000301 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000302
Chris Lattnerf04da132007-10-24 17:06:59 +0000303 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
304 // we are done.
305 if (const RewriteBuffer *RewriteBuf =
306 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000307 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000308 std::string S(RewriteBuf->begin(), RewriteBuf->end());
309 printf("%s\n", S.c_str());
310 } else {
311 printf("No changes\n");
312 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000313 // Emit metadata.
314 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000315}
316
Chris Lattnerf04da132007-10-24 17:06:59 +0000317//===----------------------------------------------------------------------===//
318// Syntactic (non-AST) Rewriting Code
319//===----------------------------------------------------------------------===//
320
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000321void RewriteTest::RewriteInclude(SourceLocation Loc) {
322 // Rip up the #include stack to the main file.
323 SourceLocation IncLoc = Loc, NextLoc = Loc;
324 do {
325 IncLoc = Loc;
326 Loc = SM->getLogicalLoc(NextLoc);
327 NextLoc = SM->getIncludeLoc(Loc);
328 } while (!NextLoc.isInvalid());
329
330 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
331 // IncLoc indicates the header that was included if it is useful.
332 IncLoc = SM->getLogicalLoc(IncLoc);
333 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
334 Loc == LastIncLoc)
335 return;
336 LastIncLoc = Loc;
337
338 unsigned IncCol = SM->getColumnNumber(Loc);
339 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
340
341 // Replace the #import with #include.
342 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
343}
344
Chris Lattnerf04da132007-10-24 17:06:59 +0000345void RewriteTest::RewriteTabs() {
346 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
347 const char *MainBufStart = MainBuf.first;
348 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000349
Chris Lattnerf04da132007-10-24 17:06:59 +0000350 // Loop over the whole file, looking for tabs.
351 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
352 if (*BufPtr != '\t')
353 continue;
354
355 // Okay, we found a tab. This tab will turn into at least one character,
356 // but it depends on which 'virtual column' it is in. Compute that now.
357 unsigned VCol = 0;
358 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
359 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
360 ++VCol;
361
362 // Okay, now that we know the virtual column, we know how many spaces to
363 // insert. We assume 8-character tab-stops.
364 unsigned Spaces = 8-(VCol & 7);
365
366 // Get the location of the tab.
367 SourceLocation TabLoc =
368 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
369
370 // Rewrite the single tab character into a sequence of spaces.
371 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
372 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000373}
374
375
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000377 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000379
380 // Get the start location and compute the semi location.
381 SourceLocation startLoc = ClassDecl->getLocation();
382 const char *startBuf = SM->getCharacterData(startLoc);
383 const char *semiPtr = strchr(startBuf, ';');
384
385 // Translate to typedef's that forward reference structs with the same name
386 // as the class. As a convenience, we include the original declaration
387 // as a comment.
388 std::string typedefString;
389 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000390 typedefString.append(startBuf, semiPtr-startBuf+1);
391 typedefString += "\n";
392 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000393 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000394 typedefString += "#ifndef _REWRITER_typedef_";
395 typedefString += ForwardDecl->getName();
396 typedefString += "\n";
397 typedefString += "#define _REWRITER_typedef_";
398 typedefString += ForwardDecl->getName();
399 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000400 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000401 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000402 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000403 }
404
405 // Replace the @class with typedefs corresponding to the classes.
406 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
407 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000408}
409
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000411 SourceLocation LocStart = Method->getLocStart();
412 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000413
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000414 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
415 Rewrite.InsertText(LocStart, "/* ", 3);
416 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
417 } else {
418 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000419 }
420}
421
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000423{
424 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000426 SourceLocation Loc = Property->getLocation();
427
428 Rewrite.ReplaceText(Loc, 0, "// ", 3);
429
430 // FIXME: handle properties that are declared across multiple lines.
431 }
432}
433
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000434void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000435 SourceLocation LocStart = CatDecl->getLocStart();
436
437 // FIXME: handle category headers that are declared across multiple lines.
438 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
439
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000440 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000441 E = CatDecl->instmeth_end(); I != E; ++I)
442 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000443 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000444 E = CatDecl->classmeth_end(); I != E; ++I)
445 RewriteMethodDeclaration(*I);
446
Steve Naroff423cb562007-10-30 13:30:57 +0000447 // Lastly, comment out the @end.
448 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
449}
450
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000451void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000452 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000453
Steve Naroff752d6ef2007-10-30 16:42:30 +0000454 SourceLocation LocStart = PDecl->getLocStart();
455
456 // FIXME: handle protocol headers that are declared across multiple lines.
457 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
458
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000459 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000460 E = PDecl->instmeth_end(); I != E; ++I)
461 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000462 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000463 E = PDecl->classmeth_end(); I != E; ++I)
464 RewriteMethodDeclaration(*I);
465
Steve Naroff752d6ef2007-10-30 16:42:30 +0000466 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000467 SourceLocation LocEnd = PDecl->getAtEndLoc();
468 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000469
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000470 // Must comment out @optional/@required
471 const char *startBuf = SM->getCharacterData(LocStart);
472 const char *endBuf = SM->getCharacterData(LocEnd);
473 for (const char *p = startBuf; p < endBuf; p++) {
474 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
475 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000476 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000477 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
478 CommentedOptional.c_str(), CommentedOptional.size());
479
480 }
481 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
482 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000483 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000484 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
485 CommentedRequired.c_str(), CommentedRequired.size());
486
487 }
488 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000489}
490
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000491void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000492 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000493 if (LocStart.isInvalid())
494 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000495 // FIXME: handle forward protocol that are declared across multiple lines.
496 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
497}
498
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000499void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000500 std::string &ResultStr) {
501 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000503 ResultStr += "id";
504 else
505 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000506 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000507
508 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000509 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000510
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000511 if (OMD->isInstance())
512 NameStr += "_I_";
513 else
514 NameStr += "_C_";
515
516 NameStr += OMD->getClassInterface()->getName();
517 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000518
519 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000520 if (ObjCCategoryImplDecl *CID =
521 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000522 NameStr += CID->getName();
523 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524 }
525 // Append selector names, replacing ':' with '_'
526 const char *selName = OMD->getSelector().getName().c_str();
527 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000528 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000529 else {
530 std::string selString = OMD->getSelector().getName();
531 int len = selString.size();
532 for (int i = 0; i < len; i++)
533 if (selString[i] == ':')
534 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000535 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000536 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000537 // Remember this name for metadata emission
538 MethodInternalNames[OMD] = NameStr;
539 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000540
541 // Rewrite arguments
542 ResultStr += "(";
543
544 // invisible arguments
545 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000546 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000547 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000549 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000550 ResultStr += selfTy.getAsString();
551 }
552 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000554
555 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000556 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557 ResultStr += " _cmd";
558
559 // Method arguments.
560 for (int i = 0; i < OMD->getNumParams(); i++) {
561 ParmVarDecl *PDecl = OMD->getParamDecl(i);
562 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000563 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000564 ResultStr += "id";
565 else
566 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567 ResultStr += " ";
568 ResultStr += PDecl->getName();
569 }
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000570 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000571
572}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000573void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
575 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000577 if (IMD)
578 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
579 else
580 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000581
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000582 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000583 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
584 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000586 ObjCMethodDecl *OMD = *I;
587 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000588 SourceLocation LocStart = OMD->getLocStart();
589 SourceLocation LocEnd = OMD->getBody()->getLocStart();
590
591 const char *startBuf = SM->getCharacterData(LocStart);
592 const char *endBuf = SM->getCharacterData(LocEnd);
593 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
594 ResultStr.c_str(), ResultStr.size());
595 }
596
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000598 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
599 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000600 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000601 ObjCMethodDecl *OMD = *I;
602 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000603 SourceLocation LocStart = OMD->getLocStart();
604 SourceLocation LocEnd = OMD->getBody()->getLocStart();
605
606 const char *startBuf = SM->getCharacterData(LocStart);
607 const char *endBuf = SM->getCharacterData(LocEnd);
608 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
609 ResultStr.c_str(), ResultStr.size());
610 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000611 if (IMD)
612 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
613 else
614 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000615}
616
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000617void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000618 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000619 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000620 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000621 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000622 ResultStr += ClassDecl->getName();
623 ResultStr += "\n";
624 ResultStr += "#define _REWRITER_typedef_";
625 ResultStr += ClassDecl->getName();
626 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000627 ResultStr += "typedef struct ";
628 ResultStr += ClassDecl->getName();
629 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000630 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000631 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000632
633 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000635 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000636 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000637
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000638 RewriteProperties(ClassDecl->getNumPropertyDecl(),
639 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000641 E = ClassDecl->instmeth_end(); I != E; ++I)
642 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000644 E = ClassDecl->classmeth_end(); I != E; ++I)
645 RewriteMethodDeclaration(*I);
646
Steve Naroff2feac5e2007-10-30 03:43:13 +0000647 // Lastly, comment out the @end.
648 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000649}
650
Steve Naroff7e3411b2007-11-15 02:58:25 +0000651Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000652 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000653 if (IV->isFreeIvar()) {
654 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
655 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000656 if (Rewrite.ReplaceStmt(IV, Replacement)) {
657 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000658 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
659 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000660 SourceRange Range = IV->getSourceRange();
661 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000662 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000663 delete IV;
664 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000665 } else {
666 if (CurMethodDecl) {
667 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000669 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
670 IdentifierInfo *II = intT->getDecl()->getIdentifier();
671 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
672 II, 0);
673 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
674
675 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
676 // Don't forget the parens to enforce the proper binding.
677 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000678 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
679 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000680 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
681 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000682 SourceRange Range = IV->getBase()->getSourceRange();
683 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000684 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000685 delete IV->getBase();
686 return PE;
687 }
688 }
689 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000690 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000691 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000692}
693
Chris Lattnerf04da132007-10-24 17:06:59 +0000694//===----------------------------------------------------------------------===//
695// Function Body / Expression rewriting
696//===----------------------------------------------------------------------===//
697
Steve Narofff3473a72007-11-09 15:20:18 +0000698Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000699 // Otherwise, just rewrite all children.
700 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
701 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000702 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000703 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000704 if (newStmt)
705 *CI = newStmt;
706 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000707
708 // Handle specific things.
709 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
710 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000711
712 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
713 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000714
715 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
716 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000717
718 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
719 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000720
Steve Naroff934f2762007-10-24 22:48:43 +0000721 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
722 // Before we rewrite it, put the original message expression in a comment.
723 SourceLocation startLoc = MessExpr->getLocStart();
724 SourceLocation endLoc = MessExpr->getLocEnd();
725
726 const char *startBuf = SM->getCharacterData(startLoc);
727 const char *endBuf = SM->getCharacterData(endLoc);
728
729 std::string messString;
730 messString += "// ";
731 messString.append(startBuf, endBuf-startBuf+1);
732 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000733
Steve Naroff934f2762007-10-24 22:48:43 +0000734 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
735 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
736 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000737 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000738 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000739 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000740
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000741 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
742 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000743
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000744 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
745 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000746
747 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
748 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000749
750 if (ObjCForCollectionStmt *StmtForCollection =
751 dyn_cast<ObjCForCollectionStmt>(S))
752 return RewriteObjCForCollectionStmt(StmtForCollection);
753
Steve Naroff874e2322007-11-15 10:28:18 +0000754#if 0
755 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
756 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
757 // Get the new text.
758 std::ostringstream Buf;
759 Replacement->printPretty(Buf);
760 const std::string &Str = Buf.str();
761
762 printf("CAST = %s\n", &Str[0]);
763 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
764 delete S;
765 return Replacement;
766 }
767#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000768 // Return this stmt unmodified.
769 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000770}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000771
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000772/// SynthCountByEnumWithState - To print:
773/// ((unsigned int (*)
774/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
775/// (void *)objc_msgSend)((id)l_collection,
776/// sel_registerName(
777/// "countByEnumeratingWithState:objects:count:"),
778/// &enumState,
779/// (id *)items, (unsigned int)16)
780///
781void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
782 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
783 "id *, unsigned int))(void *)objc_msgSend)";
784 buf += "\n\t\t";
785 buf += "((id)l_collection,\n\t\t";
786 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
787 buf += "\n\t\t";
788 buf += "&enumState, "
789 "(id *)items, (unsigned int)16)";
790}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000791
Fariborz Jahaniane84b0402008-01-09 01:25:54 +0000792/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000793/// It rewrites:
794/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000795
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000796/// Into:
797/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000798/// type elem;
799/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000800/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000801/// id l_collection = (id)collection;
802/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
803/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000804/// if (limit) {
805/// unsigned long startMutations = *enumState.mutationsPtr;
806/// do {
807/// unsigned long counter = 0;
808/// do {
809/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000810/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000811/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000812/// stmts;
813/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000814/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
815/// objects:items count:16]);
816/// elem = nil;
817/// loopend: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000818/// }
819/// else
820/// elem = nil;
821/// }
822///
823Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000824 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000825 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000826 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000827 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000828 std::string buf;
829 buf = "\n{\n\t";
830 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
831 // type elem;
832 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000833 elementTypeAsString = ElementType.getAsString();
834 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000835 buf += " ";
836 elementName = DS->getDecl()->getName();
837 buf += elementName;
838 buf += ";\n\t";
839 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000840 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000841 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000842 elementTypeAsString = DR->getDecl()->getType().getAsString();
843 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000844 else
845 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
846
847 // struct __objcFastEnumerationState enumState = { 0 };
848 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
849 // id items[16];
850 buf += "id items[16];\n\t";
851 // id l_collection = (id)
852 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +0000853 // Find start location of 'collection' the hard way!
854 const char *startCollectionBuf = startBuf;
855 startCollectionBuf += 3; // skip 'for'
856 startCollectionBuf = strchr(startCollectionBuf, '(');
857 startCollectionBuf++; // skip '('
858 // find 'in' and skip it.
859 while (*startCollectionBuf != ' ' ||
860 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
861 (*(startCollectionBuf+3) != ' ' &&
862 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
863 startCollectionBuf++;
864 startCollectionBuf += 3;
865
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000866 // Replace: "for (type element in" with string constructed thus far.
867 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
868 buf.c_str(), buf.size());
869 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +0000870 SourceLocation rightParenLoc = S->getRParenLoc();
871 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
872 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000873 buf = ";\n\t";
874
875 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
876 // objects:items count:16];
877 // which is synthesized into:
878 // unsigned int limit =
879 // ((unsigned int (*)
880 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
881 // (void *)objc_msgSend)((id)l_collection,
882 // sel_registerName(
883 // "countByEnumeratingWithState:objects:count:"),
884 // (struct __objcFastEnumerationState *)&state,
885 // (id *)items, (unsigned int)16);
886 buf += "unsigned long limit =\n\t\t";
887 SynthCountByEnumWithState(buf);
888 buf += ";\n\t";
889 /// if (limit) {
890 /// unsigned long startMutations = *enumState.mutationsPtr;
891 /// do {
892 /// unsigned long counter = 0;
893 /// do {
894 /// if (startMutations != *enumState.mutationsPtr)
895 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000896 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000897 buf += "if (limit) {\n\t";
898 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
899 buf += "do {\n\t\t";
900 buf += "unsigned long counter = 0;\n\t\t";
901 buf += "do {\n\t\t\t";
902 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
903 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
904 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000905 buf += " = (";
906 buf += elementTypeAsString;
907 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000908 // Replace ')' in for '(' type elem in collection ')' with all of these.
909 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
910
911 /// } while (counter < limit);
912 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
913 /// objects:items count:16]);
914 /// elem = nil;
915 /// loopend: ;
916 /// }
917 /// else
918 /// elem = nil;
919 /// }
920 buf = ";\n\t\t";
921 buf += "} while (counter < limit);\n\t";
922 buf += "} while (limit = ";
923 SynthCountByEnumWithState(buf);
924 buf += ");\n\t";
925 buf += elementName;
926 buf += " = nil;\n\t";
927 // TODO: Generate a unique label to exit the for loop on break statement.
928 // buf += "loopend: ;\n\t";
929 buf += "}\n\t";
930 buf += "else\n\t\t";
931 buf += elementName;
932 buf += " = nil;\n";
933 buf += "}\n";
934 // Insert all these *after* the statement body.
935 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
936 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
937 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
938 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
939
940 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000941}
942
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000943Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000944 // Get the start location and compute the semi location.
945 SourceLocation startLoc = S->getLocStart();
946 const char *startBuf = SM->getCharacterData(startLoc);
947
948 assert((*startBuf == '@') && "bogus @try location");
949
950 std::string buf;
951 // declare a new scope with two variables, _stack and _rethrow.
952 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
953 buf += "int buf[18/*32-bit i386*/];\n";
954 buf += "char *pointers[4];} _stack;\n";
955 buf += "id volatile _rethrow = 0;\n";
956 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000957 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000958
959 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
960
961 startLoc = S->getTryBody()->getLocEnd();
962 startBuf = SM->getCharacterData(startLoc);
963
964 assert((*startBuf == '}') && "bogus @try block");
965
966 SourceLocation lastCurlyLoc = startLoc;
967
968 startLoc = startLoc.getFileLocWithOffset(1);
969 buf = " /* @catch begin */ else {\n";
970 buf += " id _caught = objc_exception_extract(&_stack);\n";
971 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000972 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000973 buf += " _rethrow = objc_exception_extract(&_stack);\n";
974 buf += " else { /* @catch continue */";
975
Chris Lattner28d1fe82007-11-08 04:41:51 +0000976 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000977
978 bool sawIdTypedCatch = false;
979 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000980 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +0000981 while (catchList) {
982 Stmt *catchStmt = catchList->getCatchParamStmt();
983
984 if (catchList == S->getCatchStmts())
985 buf = "if ("; // we are generating code for the first catch clause
986 else
987 buf = "else if (";
988 startLoc = catchList->getLocStart();
989 startBuf = SM->getCharacterData(startLoc);
990
991 assert((*startBuf == '@') && "bogus @catch location");
992
993 const char *lParenLoc = strchr(startBuf, '(');
994
995 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
996 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000997 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +0000998 buf += "1) { ";
999 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1000 buf.c_str(), buf.size());
1001 sawIdTypedCatch = true;
1002 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001006 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001007 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001008 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001009 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +00001010 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1011 buf.c_str(), buf.size());
1012 }
1013 }
1014 // Now rewrite the body...
1015 lastCatchBody = catchList->getCatchBody();
1016 SourceLocation rParenLoc = catchList->getRParenLoc();
1017 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1018 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1019 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1020 assert((*rParenBuf == ')') && "bogus @catch paren location");
1021 assert((*bodyBuf == '{') && "bogus @catch body location");
1022
1023 buf = " = _caught;";
1024 // Here we replace ") {" with "= _caught;" (which initializes and
1025 // declares the @catch parameter).
1026 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1027 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001028 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001029 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001030 }
Steve Naroff75730982007-11-07 04:08:17 +00001031 catchList = catchList->getNextCatchStmt();
1032 }
1033 // Complete the catch list...
1034 if (lastCatchBody) {
1035 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1036 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1037 assert((*bodyBuf == '}') && "bogus @catch body location");
1038 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1039 buf = " } } /* @catch end */\n";
1040
Chris Lattner28d1fe82007-11-08 04:41:51 +00001041 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001042
1043 // Set lastCurlyLoc
1044 lastCurlyLoc = lastCatchBody->getLocEnd();
1045 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001046 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001047 startLoc = finalStmt->getLocStart();
1048 startBuf = SM->getCharacterData(startLoc);
1049 assert((*startBuf == '@') && "bogus @finally start");
1050
1051 buf = "/* @finally */";
1052 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1053
1054 Stmt *body = finalStmt->getFinallyBody();
1055 SourceLocation startLoc = body->getLocStart();
1056 SourceLocation endLoc = body->getLocEnd();
1057 const char *startBuf = SM->getCharacterData(startLoc);
1058 const char *endBuf = SM->getCharacterData(endLoc);
1059 assert((*startBuf == '{') && "bogus @finally body location");
1060 assert((*endBuf == '}') && "bogus @finally body location");
1061
1062 startLoc = startLoc.getFileLocWithOffset(1);
1063 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001064 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001065 endLoc = endLoc.getFileLocWithOffset(-1);
1066 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001067 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001068
1069 // Set lastCurlyLoc
1070 lastCurlyLoc = body->getLocEnd();
1071 }
1072 // Now emit the final closing curly brace...
1073 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1074 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001075 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001076 return 0;
1077}
1078
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001079Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001080 return 0;
1081}
1082
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001083Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001084 return 0;
1085}
1086
Steve Naroff2bd03922007-11-07 15:32:26 +00001087// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1088// the throw expression is typically a message expression that's already
1089// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001091 // Get the start location and compute the semi location.
1092 SourceLocation startLoc = S->getLocStart();
1093 const char *startBuf = SM->getCharacterData(startLoc);
1094
1095 assert((*startBuf == '@') && "bogus @throw location");
1096
1097 std::string buf;
1098 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1099 buf = "objc_exception_throw(";
1100 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1101 const char *semiBuf = strchr(startBuf, ';');
1102 assert((*semiBuf == ';') && "@throw: can't find ';'");
1103 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1104 buf = ");";
1105 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1106 return 0;
1107}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001108
Chris Lattnere64b7772007-10-24 16:57:36 +00001109Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001110 // Create a new string expression.
1111 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001112 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001113 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001114 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1115 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001116 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +00001117 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1118 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001119 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1120 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +00001121 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001122 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +00001123 }
1124
Chris Lattner07506182007-11-30 22:53:43 +00001125 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001126 delete Exp;
1127 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001128}
1129
Steve Naroffb42f8412007-11-05 14:50:49 +00001130Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1131 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1132 // Create a call to sel_registerName("selName").
1133 llvm::SmallVector<Expr*, 8> SelExprs;
1134 QualType argType = Context->getPointerType(Context->CharTy);
1135 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1136 Exp->getSelector().getName().size(),
1137 false, argType, SourceLocation(),
1138 SourceLocation()));
1139 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1140 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001141 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1142 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001143 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1144 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001145 SourceRange Range = Exp->getSourceRange();
1146 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001147 }
Steve Naroffb42f8412007-11-05 14:50:49 +00001148 delete Exp;
1149 return SelExp;
1150}
1151
Steve Naroff934f2762007-10-24 22:48:43 +00001152CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1153 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001154 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001155 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001156
1157 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001158 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001159
1160 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001161 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001162 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1163
1164 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001165
Steve Naroff934f2762007-10-24 22:48:43 +00001166 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1167}
1168
Steve Naroffd5255f52007-11-01 13:24:47 +00001169static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1170 const char *&startRef, const char *&endRef) {
1171 while (startBuf < endBuf) {
1172 if (*startBuf == '<')
1173 startRef = startBuf; // mark the start.
1174 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001175 if (startRef && *startRef == '<') {
1176 endRef = startBuf; // mark the end.
1177 return true;
1178 }
1179 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001180 }
1181 startBuf++;
1182 }
1183 return false;
1184}
1185
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001186static void scanToNextArgument(const char *&argRef) {
1187 int angle = 0;
1188 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1189 if (*argRef == '<')
1190 angle++;
1191 else if (*argRef == '>')
1192 angle--;
1193 argRef++;
1194 }
1195 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1196}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001197
Steve Naroffd5255f52007-11-01 13:24:47 +00001198bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001199
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001200 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001201 return true;
1202
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001204 return true;
1205
Steve Naroffd5255f52007-11-01 13:24:47 +00001206 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001207 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001209 return true; // we have "Class <Protocol> *".
1210 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001211 return false;
1212}
1213
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001214void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001215 SourceLocation Loc;
1216 QualType Type;
1217 const FunctionTypeProto *proto = 0;
1218 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1219 Loc = VD->getLocation();
1220 Type = VD->getType();
1221 }
1222 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1223 Loc = FD->getLocation();
1224 // Check for ObjC 'id' and class types that have been adorned with protocol
1225 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1226 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1227 assert(funcType && "missing function type");
1228 proto = dyn_cast<FunctionTypeProto>(funcType);
1229 if (!proto)
1230 return;
1231 Type = proto->getResultType();
1232 }
1233 else
1234 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001235
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001236 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001237 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001238
1239 const char *endBuf = SM->getCharacterData(Loc);
1240 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001241 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001242 startBuf--; // scan backward (from the decl location) for return type.
1243 const char *startRef = 0, *endRef = 0;
1244 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1245 // Get the locations of the startRef, endRef.
1246 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1247 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1248 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001249 Rewrite.InsertText(LessLoc, "/*", 2);
1250 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001251 }
1252 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001253 if (!proto)
1254 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001255 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001256 const char *startBuf = SM->getCharacterData(Loc);
1257 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001258 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1259 if (needToScanForQualifiers(proto->getArgType(i))) {
1260 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001261
Steve Naroffd5255f52007-11-01 13:24:47 +00001262 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001263 // scan forward (from the decl location) for argument types.
1264 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001265 const char *startRef = 0, *endRef = 0;
1266 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1267 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001268 SourceLocation LessLoc =
1269 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1270 SourceLocation GreaterLoc =
1271 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001272 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001273 Rewrite.InsertText(LessLoc, "/*", 2);
1274 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001275 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001276 startBuf = ++endBuf;
1277 }
1278 else {
1279 while (*startBuf != ')' && *startBuf != ',')
1280 startBuf++; // scan forward (from the decl location) for argument types.
1281 startBuf++;
1282 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001283 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001284}
1285
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001286// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1287void RewriteTest::SynthSelGetUidFunctionDecl() {
1288 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1289 llvm::SmallVector<QualType, 16> ArgTys;
1290 ArgTys.push_back(Context->getPointerType(
1291 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001292 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001293 &ArgTys[0], ArgTys.size(),
1294 false /*isVariadic*/);
1295 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1296 SelGetUidIdent, getFuncType,
1297 FunctionDecl::Extern, false, 0);
1298}
1299
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001300// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1301void RewriteTest::SynthGetProtocolFunctionDecl() {
1302 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1303 llvm::SmallVector<QualType, 16> ArgTys;
1304 ArgTys.push_back(Context->getPointerType(
1305 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001306 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001307 &ArgTys[0], ArgTys.size(),
1308 false /*isVariadic*/);
1309 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1310 SelGetProtoIdent, getFuncType,
1311 FunctionDecl::Extern, false, 0);
1312}
1313
Steve Naroff09b266e2007-10-30 23:14:51 +00001314void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1315 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001316 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001317 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001318 return;
1319 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001320 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001321}
1322
1323// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1324void RewriteTest::SynthMsgSendFunctionDecl() {
1325 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1326 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001327 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001328 assert(!argT.isNull() && "Can't find 'id' type");
1329 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001331 assert(!argT.isNull() && "Can't find 'SEL' type");
1332 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001333 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001334 &ArgTys[0], ArgTys.size(),
1335 true /*isVariadic*/);
1336 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1337 msgSendIdent, msgSendType,
1338 FunctionDecl::Extern, false, 0);
1339}
1340
Steve Naroff874e2322007-11-15 10:28:18 +00001341// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1342void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1343 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1344 llvm::SmallVector<QualType, 16> ArgTys;
1345 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1346 &Context->Idents.get("objc_super"), 0);
1347 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1348 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1349 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001350 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001351 assert(!argT.isNull() && "Can't find 'SEL' type");
1352 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001353 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001354 &ArgTys[0], ArgTys.size(),
1355 true /*isVariadic*/);
1356 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1357 msgSendIdent, msgSendType,
1358 FunctionDecl::Extern, false, 0);
1359}
1360
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001361// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1362void RewriteTest::SynthMsgSendStretFunctionDecl() {
1363 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1364 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001365 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001366 assert(!argT.isNull() && "Can't find 'id' type");
1367 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001368 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001369 assert(!argT.isNull() && "Can't find 'SEL' type");
1370 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001371 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001372 &ArgTys[0], ArgTys.size(),
1373 true /*isVariadic*/);
1374 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1375 msgSendIdent, msgSendType,
1376 FunctionDecl::Extern, false, 0);
1377}
1378
1379// SynthMsgSendSuperStretFunctionDecl -
1380// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1381void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1382 IdentifierInfo *msgSendIdent =
1383 &Context->Idents.get("objc_msgSendSuper_stret");
1384 llvm::SmallVector<QualType, 16> ArgTys;
1385 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1386 &Context->Idents.get("objc_super"), 0);
1387 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1388 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1389 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001390 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001391 assert(!argT.isNull() && "Can't find 'SEL' type");
1392 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001393 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001394 &ArgTys[0], ArgTys.size(),
1395 true /*isVariadic*/);
1396 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1397 msgSendIdent, msgSendType,
1398 FunctionDecl::Extern, false, 0);
1399}
1400
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001401// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1402void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1403 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1404 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001405 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001406 assert(!argT.isNull() && "Can't find 'id' type");
1407 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001408 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001409 assert(!argT.isNull() && "Can't find 'SEL' type");
1410 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001411 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001412 &ArgTys[0], ArgTys.size(),
1413 true /*isVariadic*/);
1414 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1415 msgSendIdent, msgSendType,
1416 FunctionDecl::Extern, false, 0);
1417}
1418
Steve Naroff09b266e2007-10-30 23:14:51 +00001419// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1420void RewriteTest::SynthGetClassFunctionDecl() {
1421 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1422 llvm::SmallVector<QualType, 16> ArgTys;
1423 ArgTys.push_back(Context->getPointerType(
1424 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001425 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001426 &ArgTys[0], ArgTys.size(),
1427 false /*isVariadic*/);
1428 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1429 getClassIdent, getClassType,
1430 FunctionDecl::Extern, false, 0);
1431}
1432
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001433// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1434void RewriteTest::SynthGetMetaClassFunctionDecl() {
1435 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1436 llvm::SmallVector<QualType, 16> ArgTys;
1437 ArgTys.push_back(Context->getPointerType(
1438 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001439 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001440 &ArgTys[0], ArgTys.size(),
1441 false /*isVariadic*/);
1442 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1443 getClassIdent, getClassType,
1444 FunctionDecl::Extern, false, 0);
1445}
1446
Steve Naroff96984642007-11-08 14:30:50 +00001447// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1448void RewriteTest::SynthCFStringFunctionDecl() {
1449 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1450 llvm::SmallVector<QualType, 16> ArgTys;
1451 ArgTys.push_back(Context->getPointerType(
1452 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001453 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001454 &ArgTys[0], ArgTys.size(),
1455 false /*isVariadic*/);
1456 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1457 getClassIdent, getClassType,
1458 FunctionDecl::Extern, false, 0);
1459}
1460
Steve Naroffbeaf2992007-11-03 11:27:19 +00001461Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001462#if 1
1463 // This rewrite is specific to GCC, which has builtin support for CFString.
1464 if (!CFStringFunctionDecl)
1465 SynthCFStringFunctionDecl();
1466 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1467 llvm::SmallVector<Expr*, 8> StrExpr;
1468 StrExpr.push_back(Exp->getString());
1469 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1470 &StrExpr[0], StrExpr.size());
1471 // cast to NSConstantString *
1472 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001473 if (Rewrite.ReplaceStmt(Exp, cast)) {
1474 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001475 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1476 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001477 SourceRange Range = Exp->getSourceRange();
1478 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001479 }
Steve Naroff96984642007-11-08 14:30:50 +00001480 delete Exp;
1481 return cast;
1482#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001483 assert(ConstantStringClassReference && "Can't find constant string reference");
1484 llvm::SmallVector<Expr*, 4> InitExprs;
1485
1486 // Synthesize "(Class)&_NSConstantStringClassReference"
1487 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1488 ConstantStringClassReference->getType(),
1489 SourceLocation());
1490 QualType expType = Context->getPointerType(ClsRef->getType());
1491 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1492 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001493 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001494 SourceLocation());
1495 InitExprs.push_back(cast); // set the 'isa'.
1496 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1497 unsigned IntSize = static_cast<unsigned>(
1498 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1499 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1500 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1501 Exp->getLocStart());
1502 InitExprs.push_back(len); // set "int numBytes".
1503
1504 // struct NSConstantString
1505 QualType CFConstantStrType = Context->getCFConstantStringType();
1506 // (struct NSConstantString) { <exprs from above> }
1507 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1508 &InitExprs[0], InitExprs.size(),
1509 SourceLocation());
1510 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1511 // struct NSConstantString *
1512 expType = Context->getPointerType(StrRep->getType());
1513 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1514 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001515 // cast to NSConstantString *
1516 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001517 Rewrite.ReplaceStmt(Exp, cast);
1518 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001519 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001520#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001521}
1522
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001523ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001524 // check if we are sending a message to 'super'
1525 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001526 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1527 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1528 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1529 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001530 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001531 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001532 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001533 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001534 if (ObjCInterfaceType *IT =
1535 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001536 if (IT->getDecl() ==
1537 CurMethodDecl->getClassInterface()->getSuperClass())
1538 return IT->getDecl();
1539 }
1540 }
1541 }
1542 }
1543 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001544 }
Steve Naroff874e2322007-11-15 10:28:18 +00001545 }
1546 return 0;
1547}
1548
1549// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1550QualType RewriteTest::getSuperStructType() {
1551 if (!SuperStructDecl) {
1552 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1553 &Context->Idents.get("objc_super"), 0);
1554 QualType FieldTypes[2];
1555
1556 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001557 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001558 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001559 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001560 // Create fields
1561 FieldDecl *FieldDecls[2];
1562
1563 for (unsigned i = 0; i < 2; ++i)
1564 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1565
1566 SuperStructDecl->defineBody(FieldDecls, 4);
1567 }
1568 return Context->getTagDeclType(SuperStructDecl);
1569}
1570
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001572 if (!SelGetUidFunctionDecl)
1573 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001574 if (!MsgSendFunctionDecl)
1575 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001576 if (!MsgSendSuperFunctionDecl)
1577 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001578 if (!MsgSendStretFunctionDecl)
1579 SynthMsgSendStretFunctionDecl();
1580 if (!MsgSendSuperStretFunctionDecl)
1581 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001582 if (!MsgSendFpretFunctionDecl)
1583 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001584 if (!GetClassFunctionDecl)
1585 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001586 if (!GetMetaClassFunctionDecl)
1587 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001588
Steve Naroff874e2322007-11-15 10:28:18 +00001589 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001590 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1591 // May need to use objc_msgSend_stret() as well.
1592 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001593 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001594 QualType resultType = mDecl->getResultType();
1595 if (resultType.getCanonicalType()->isStructureType()
1596 || resultType.getCanonicalType()->isUnionType())
1597 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001598 else if (resultType.getCanonicalType()->isRealFloatingType())
1599 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001600 }
Steve Naroff874e2322007-11-15 10:28:18 +00001601
Steve Naroff934f2762007-10-24 22:48:43 +00001602 // Synthesize a call to objc_msgSend().
1603 llvm::SmallVector<Expr*, 8> MsgExprs;
1604 IdentifierInfo *clsName = Exp->getClassName();
1605
1606 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1607 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001608 if (!strcmp(clsName->getName(), "super")) {
1609 MsgSendFlavor = MsgSendSuperFunctionDecl;
1610 if (MsgSendStretFlavor)
1611 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1612 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001615 CurMethodDecl->getClassInterface()->getSuperClass();
1616
1617 llvm::SmallVector<Expr*, 4> InitExprs;
1618
1619 // set the receiver to self, the first argument to all methods.
1620 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001621 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001622 SourceLocation()));
1623 llvm::SmallVector<Expr*, 8> ClsExprs;
1624 QualType argType = Context->getPointerType(Context->CharTy);
1625 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1626 SuperDecl->getIdentifier()->getLength(),
1627 false, argType, SourceLocation(),
1628 SourceLocation()));
1629 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1630 &ClsExprs[0],
1631 ClsExprs.size());
1632 // To turn off a warning, type-cast to 'id'
1633 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001634 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001635 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1636 // struct objc_super
1637 QualType superType = getSuperStructType();
1638 // (struct objc_super) { <exprs from above> }
1639 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1640 &InitExprs[0], InitExprs.size(),
1641 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001642 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1643 superType, ILE);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001644 // struct objc_super *
1645 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1646 Context->getPointerType(SuperRep->getType()),
1647 SourceLocation());
1648 MsgExprs.push_back(Unop);
1649 } else {
1650 llvm::SmallVector<Expr*, 8> ClsExprs;
1651 QualType argType = Context->getPointerType(Context->CharTy);
1652 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1653 clsName->getLength(),
1654 false, argType, SourceLocation(),
1655 SourceLocation()));
1656 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1657 &ClsExprs[0],
1658 ClsExprs.size());
1659 MsgExprs.push_back(Cls);
1660 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001661 } else { // instance message.
1662 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001663
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001665 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001666 if (MsgSendStretFlavor)
1667 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001668 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1669
1670 llvm::SmallVector<Expr*, 4> InitExprs;
1671
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001672 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001673 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001674 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001675
1676 llvm::SmallVector<Expr*, 8> ClsExprs;
1677 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001678 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1679 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001680 false, argType, SourceLocation(),
1681 SourceLocation()));
1682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001683 &ClsExprs[0],
1684 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001685 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001686 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001687 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001688 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001689 // struct objc_super
1690 QualType superType = getSuperStructType();
1691 // (struct objc_super) { <exprs from above> }
1692 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1693 &InitExprs[0], InitExprs.size(),
1694 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001695 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1696 superType, ILE);
Steve Naroff874e2322007-11-15 10:28:18 +00001697 // struct objc_super *
1698 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1699 Context->getPointerType(SuperRep->getType()),
1700 SourceLocation());
1701 MsgExprs.push_back(Unop);
1702 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001703 // Remove all type-casts because it may contain objc-style types; e.g.
1704 // Foo<Proto> *.
1705 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1706 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001708 MsgExprs.push_back(recExpr);
1709 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001710 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001711 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001712 llvm::SmallVector<Expr*, 8> SelExprs;
1713 QualType argType = Context->getPointerType(Context->CharTy);
1714 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1715 Exp->getSelector().getName().size(),
1716 false, argType, SourceLocation(),
1717 SourceLocation()));
1718 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1719 &SelExprs[0], SelExprs.size());
1720 MsgExprs.push_back(SelExp);
1721
1722 // Now push any user supplied arguments.
1723 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001724 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001725 // Make all implicit casts explicit...ICE comes in handy:-)
1726 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1727 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001728 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1729 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001730 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001731 }
1732 // Make id<P...> cast into an 'id' cast.
1733 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001734 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001735 while ((CE = dyn_cast<CastExpr>(userExpr)))
1736 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001737 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001738 userExpr, SourceLocation());
1739 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001740 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001741 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001742 // We've transferred the ownership to MsgExprs. Null out the argument in
1743 // the original expression, since we will delete it below.
1744 Exp->setArg(i, 0);
1745 }
Steve Naroffab972d32007-11-04 22:37:50 +00001746 // Generate the funky cast.
1747 CastExpr *cast;
1748 llvm::SmallVector<QualType, 8> ArgTypes;
1749 QualType returnType;
1750
1751 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001752 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1753 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1754 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001755 ArgTypes.push_back(Context->getObjCIdType());
1756 ArgTypes.push_back(Context->getObjCSelType());
1757 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001758 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001759 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001760 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1761 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001762 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001763 ArgTypes.push_back(t);
1764 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001765 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1766 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001767 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001768 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001769 }
1770 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001771 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001772
1773 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001774 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1775 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001776
1777 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1778 // If we don't do this cast, we get the following bizarre warning/note:
1779 // xx.m:13: warning: function called through a non-compatible type
1780 // xx.m:13: note: if this code is reached, the program will abort
1781 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1782 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001783
Steve Naroffab972d32007-11-04 22:37:50 +00001784 // Now do the "normal" pointer to function cast.
1785 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001786 &ArgTypes[0], ArgTypes.size(),
1787 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001788 castType = Context->getPointerType(castType);
1789 cast = new CastExpr(castType, cast, SourceLocation());
1790
1791 // Don't forget the parens to enforce the proper binding.
1792 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1793
1794 const FunctionType *FT = msgSendType->getAsFunctionType();
1795 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1796 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001797 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001798 if (MsgSendStretFlavor) {
1799 // We have the method which returns a struct/union. Must also generate
1800 // call to objc_msgSend_stret and hang both varieties on a conditional
1801 // expression which dictate which one to envoke depending on size of
1802 // method's return type.
1803
1804 // Create a reference to the objc_msgSend_stret() declaration.
1805 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1806 SourceLocation());
1807 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1808 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1809 SourceLocation());
1810 // Now do the "normal" pointer to function cast.
1811 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001812 &ArgTypes[0], ArgTypes.size(),
1813 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001814 castType = Context->getPointerType(castType);
1815 cast = new CastExpr(castType, cast, SourceLocation());
1816
1817 // Don't forget the parens to enforce the proper binding.
1818 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1819
1820 FT = msgSendType->getAsFunctionType();
1821 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1822 FT->getResultType(), SourceLocation());
1823
1824 // Build sizeof(returnType)
1825 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1826 returnType, Context->getSizeType(),
1827 SourceLocation(), SourceLocation());
1828 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1829 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1830 // For X86 it is more complicated and some kind of target specific routine
1831 // is needed to decide what to do.
1832 unsigned IntSize = static_cast<unsigned>(
1833 Context->getTypeSize(Context->IntTy, SourceLocation()));
1834
1835 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1836 Context->IntTy,
1837 SourceLocation());
1838 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1839 BinaryOperator::LE,
1840 Context->IntTy,
1841 SourceLocation());
1842 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1843 ConditionalOperator *CondExpr =
1844 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001845 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001846 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001847 return ReplacingStmt;
1848}
1849
1850Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1851 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00001852 // Now do the actual rewrite.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001853 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroff5ca40202007-12-19 14:32:56 +00001854 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001855 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1856 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001857 SourceRange Range = Exp->getSourceRange();
1858 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001859 }
Steve Naroff934f2762007-10-24 22:48:43 +00001860
Chris Lattnere64b7772007-10-24 16:57:36 +00001861 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001862 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00001863}
1864
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001865/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1866/// call to objc_getProtocol("proto-name").
1867Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1868 if (!GetProtocolFunctionDecl)
1869 SynthGetProtocolFunctionDecl();
1870 // Create a call to objc_getProtocol("ProtocolName").
1871 llvm::SmallVector<Expr*, 8> ProtoExprs;
1872 QualType argType = Context->getPointerType(Context->CharTy);
1873 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1874 strlen(Exp->getProtocol()->getName()),
1875 false, argType, SourceLocation(),
1876 SourceLocation()));
1877 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1878 &ProtoExprs[0],
1879 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001880 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1881 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001882 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1883 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001884 SourceRange Range = Exp->getSourceRange();
1885 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001886 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001887 delete Exp;
1888 return ProtoExp;
1889
1890}
1891
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001892/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001893/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001895 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001896 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1897 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001898 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001899 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001900 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001901 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001902 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001903 SourceLocation LocStart = CDecl->getLocStart();
1904 SourceLocation LocEnd = CDecl->getLocEnd();
1905
1906 const char *startBuf = SM->getCharacterData(LocStart);
1907 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001908 // If no ivars and no root or if its root, directly or indirectly,
1909 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001911 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1912 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1913 Result.c_str(), Result.size());
1914 return;
1915 }
1916
1917 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001918 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001919 Result += "\nstruct ";
1920 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001921
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001922 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001923 const char *cursor = strchr(startBuf, '{');
1924 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001925 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001926
1927 // rewrite the original header *without* disturbing the '{'
1928 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1929 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001930 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00001931 Result = "\n struct ";
1932 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001933 // Note: We don't name the field decl. This simplifies the "codegen" for
1934 // accessing a superclasses instance variables (and is similar to what gcc
1935 // does internally). The unnamed struct field feature is enabled with
1936 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1937 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001938 Result += ";\n";
1939
1940 // insert the super class structure definition.
1941 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1942 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1943 }
1944 cursor++; // past '{'
1945
1946 // Now comment out any visibility specifiers.
1947 while (cursor < endBuf) {
1948 if (*cursor == '@') {
1949 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001950 // Skip whitespace.
1951 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1952 /*scan*/;
1953
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001954 // FIXME: presence of @public, etc. inside comment results in
1955 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001956 if (!strncmp(cursor, "public", strlen("public")) ||
1957 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001958 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001959 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001960 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001961 // FIXME: If there are cases where '<' is used in ivar declaration part
1962 // of user code, then scan the ivar list and use needToScanForQualifiers
1963 // for type checking.
1964 else if (*cursor == '<') {
1965 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1966 Rewrite.InsertText(atLoc, "/* ", 3);
1967 cursor = strchr(cursor, '>');
1968 cursor++;
1969 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1970 Rewrite.InsertText(atLoc, " */", 3);
1971 }
Steve Narofffea763e82007-11-14 19:25:57 +00001972 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001973 }
Steve Narofffea763e82007-11-14 19:25:57 +00001974 // Don't forget to add a ';'!!
1975 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1976 } else { // we don't have any instance variables - insert super struct.
1977 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1978 Result += " {\n struct ";
1979 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001980 // Note: We don't name the field decl. This simplifies the "codegen" for
1981 // accessing a superclasses instance variables (and is similar to what gcc
1982 // does internally). The unnamed struct field feature is enabled with
1983 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1984 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001985 Result += ";\n};\n";
1986 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1987 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001988 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001989 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001990 if (!ObjCSynthesizedStructs.insert(CDecl))
1991 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001992}
1993
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001994// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001995/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001996void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001997 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001998 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001999 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002000 const char *ClassName,
2001 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002002 if (MethodBegin == MethodEnd) return;
2003
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002004 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002005 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002006 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002007 SEL _cmd;
2008 char *method_types;
2009 void *_imp;
2010 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002011 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002012 Result += "\nstruct _objc_method {\n";
2013 Result += "\tSEL _cmd;\n";
2014 Result += "\tchar *method_types;\n";
2015 Result += "\tvoid *_imp;\n";
2016 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002017
2018 /* struct _objc_method_list {
2019 struct _objc_method_list *next_method;
2020 int method_count;
2021 struct _objc_method method_list[];
2022 }
2023 */
2024 Result += "\nstruct _objc_method_list {\n";
2025 Result += "\tstruct _objc_method_list *next_method;\n";
2026 Result += "\tint method_count;\n";
2027 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002028 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002029 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002030
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002031 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002032 Result += "\nstatic struct _objc_method_list _OBJC_";
2033 Result += prefix;
2034 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2035 Result += "_METHODS_";
2036 Result += ClassName;
2037 Result += " __attribute__ ((section (\"__OBJC, __";
2038 Result += IsInstanceMethod ? "inst" : "cls";
2039 Result += "_meth\")))= ";
2040 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002041
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002042 Result += "\t,{{(SEL)\"";
2043 Result += (*MethodBegin)->getSelector().getName().c_str();
2044 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002045 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002046 Result += "\", \"";
2047 Result += MethodTypeString;
2048 Result += "\", ";
2049 Result += MethodInternalNames[*MethodBegin];
2050 Result += "}\n";
2051 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2052 Result += "\t ,{(SEL)\"";
2053 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002054 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002055 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002056 Result += "\", \"";
2057 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002058 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002059 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002060 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002061 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002062 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002063}
2064
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002065/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2066void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002067 int NumProtocols,
2068 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002069 const char *ClassName,
2070 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002071 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002072 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002073 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002074 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002075 // Output struct protocol_methods holder of method selector and type.
2076 if (!objc_protocol_methods &&
2077 (PDecl->getNumInstanceMethods() > 0
2078 || PDecl->getNumClassMethods() > 0)) {
2079 /* struct protocol_methods {
2080 SEL _cmd;
2081 char *method_types;
2082 }
2083 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002084 Result += "\nstruct protocol_methods {\n";
2085 Result += "\tSEL _cmd;\n";
2086 Result += "\tchar *method_types;\n";
2087 Result += "};\n";
2088
2089 /* struct _objc_protocol_method_list {
2090 int protocol_method_count;
2091 struct protocol_methods protocols[];
2092 }
2093 */
2094 Result += "\nstruct _objc_protocol_method_list {\n";
2095 Result += "\tint protocol_method_count;\n";
2096 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002097 objc_protocol_methods = true;
2098 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002099
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002100 int NumMethods = PDecl->getNumInstanceMethods();
2101 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002102 Result += "\nstatic struct _objc_protocol_method_list "
2103 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2104 Result += PDecl->getName();
2105 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2106 "{\n\t" + utostr(NumMethods) + "\n";
2107
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002108 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002109 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002110 E = PDecl->instmeth_end(); I != E; ++I) {
2111 if (I == PDecl->instmeth_begin())
2112 Result += "\t ,{{(SEL)\"";
2113 else
2114 Result += "\t ,{(SEL)\"";
2115 Result += (*I)->getSelector().getName().c_str();
2116 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002117 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002118 Result += "\", \"";
2119 Result += MethodTypeString;
2120 Result += "\"}\n";
2121 }
2122 Result += "\t }\n};\n";
2123 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002124
2125 // Output class methods declared in this protocol.
2126 NumMethods = PDecl->getNumClassMethods();
2127 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002128 Result += "\nstatic struct _objc_protocol_method_list "
2129 "_OBJC_PROTOCOL_CLASS_METHODS_";
2130 Result += PDecl->getName();
2131 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2132 "{\n\t";
2133 Result += utostr(NumMethods);
2134 Result += "\n";
2135
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002136 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002137 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002138 E = PDecl->classmeth_end(); I != E; ++I) {
2139 if (I == PDecl->classmeth_begin())
2140 Result += "\t ,{{(SEL)\"";
2141 else
2142 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002143 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002144 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002145 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002146 Result += "\", \"";
2147 Result += MethodTypeString;
2148 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002149 }
2150 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002151 }
2152 // Output:
2153 /* struct _objc_protocol {
2154 // Objective-C 1.0 extensions
2155 struct _objc_protocol_extension *isa;
2156 char *protocol_name;
2157 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002158 struct _objc_protocol_method_list *instance_methods;
2159 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002160 };
2161 */
2162 static bool objc_protocol = false;
2163 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002164 Result += "\nstruct _objc_protocol {\n";
2165 Result += "\tstruct _objc_protocol_extension *isa;\n";
2166 Result += "\tchar *protocol_name;\n";
2167 Result += "\tstruct _objc_protocol **protocol_list;\n";
2168 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2169 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2170 Result += "};\n";
2171
2172 /* struct _objc_protocol_list {
2173 struct _objc_protocol_list *next;
2174 int protocol_count;
2175 struct _objc_protocol *class_protocols[];
2176 }
2177 */
2178 Result += "\nstruct _objc_protocol_list {\n";
2179 Result += "\tstruct _objc_protocol_list *next;\n";
2180 Result += "\tint protocol_count;\n";
2181 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2182 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002183 objc_protocol = true;
2184 }
2185
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002186 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2187 Result += PDecl->getName();
2188 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2189 "{\n\t0, \"";
2190 Result += PDecl->getName();
2191 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002192 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002193 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2194 Result += PDecl->getName();
2195 Result += ", ";
2196 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002197 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002198 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002199 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002200 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2201 Result += PDecl->getName();
2202 Result += "\n";
2203 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002204 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002205 Result += "0\n";
2206 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002207 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002208 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002209 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2210 Result += prefix;
2211 Result += "_PROTOCOLS_";
2212 Result += ClassName;
2213 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2214 "{\n\t0, ";
2215 Result += utostr(NumProtocols);
2216 Result += "\n";
2217
2218 Result += "\t,{&_OBJC_PROTOCOL_";
2219 Result += Protocols[0]->getName();
2220 Result += " \n";
2221
2222 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002224 Result += "\t ,&_OBJC_PROTOCOL_";
2225 Result += PDecl->getName();
2226 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002227 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002228 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002229 }
2230}
2231
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002232/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002233/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002234void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002235 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002237 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002238 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002239 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2240 CDecl = CDecl->getNextClassCategory())
2241 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2242 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002243
Chris Lattnereb44eee2007-12-23 01:40:15 +00002244 std::string FullCategoryName = ClassDecl->getName();
2245 FullCategoryName += '_';
2246 FullCategoryName += IDecl->getName();
2247
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002248 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002250 true, "CATEGORY_", FullCategoryName.c_str(),
2251 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002252
2253 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002255 false, "CATEGORY_", FullCategoryName.c_str(),
2256 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002257
2258 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002259 // Null CDecl is case of a category implementation with no category interface
2260 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002262 CDecl->getNumReferencedProtocols(),
2263 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002264 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002265
2266 /* struct _objc_category {
2267 char *category_name;
2268 char *class_name;
2269 struct _objc_method_list *instance_methods;
2270 struct _objc_method_list *class_methods;
2271 struct _objc_protocol_list *protocols;
2272 // Objective-C 1.0 extensions
2273 uint32_t size; // sizeof (struct _objc_category)
2274 struct _objc_property_list *instance_properties; // category's own
2275 // @property decl.
2276 };
2277 */
2278
2279 static bool objc_category = false;
2280 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002281 Result += "\nstruct _objc_category {\n";
2282 Result += "\tchar *category_name;\n";
2283 Result += "\tchar *class_name;\n";
2284 Result += "\tstruct _objc_method_list *instance_methods;\n";
2285 Result += "\tstruct _objc_method_list *class_methods;\n";
2286 Result += "\tstruct _objc_protocol_list *protocols;\n";
2287 Result += "\tunsigned int size;\n";
2288 Result += "\tstruct _objc_property_list *instance_properties;\n";
2289 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002290 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002291 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002292 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2293 Result += FullCategoryName;
2294 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2295 Result += IDecl->getName();
2296 Result += "\"\n\t, \"";
2297 Result += ClassDecl->getName();
2298 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002299
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002300 if (IDecl->getNumInstanceMethods() > 0) {
2301 Result += "\t, (struct _objc_method_list *)"
2302 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2303 Result += FullCategoryName;
2304 Result += "\n";
2305 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002306 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002307 Result += "\t, 0\n";
2308 if (IDecl->getNumClassMethods() > 0) {
2309 Result += "\t, (struct _objc_method_list *)"
2310 "&_OBJC_CATEGORY_CLASS_METHODS_";
2311 Result += FullCategoryName;
2312 Result += "\n";
2313 }
2314 else
2315 Result += "\t, 0\n";
2316
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002317 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002318 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2319 Result += FullCategoryName;
2320 Result += "\n";
2321 }
2322 else
2323 Result += "\t, 0\n";
2324 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002325}
2326
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002327/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2328/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002329void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2330 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002331 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002332 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002333 Result += IDecl->getName();
2334 Result += ", ";
2335 Result += ivar->getName();
2336 Result += ")";
2337}
2338
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002339//===----------------------------------------------------------------------===//
2340// Meta Data Emission
2341//===----------------------------------------------------------------------===//
2342
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002343void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002344 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002345 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002346
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002347 // Explictly declared @interface's are already synthesized.
2348 if (CDecl->ImplicitInterfaceDecl()) {
2349 // FIXME: Implementation of a class with no @interface (legacy) doese not
2350 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002352 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002353
Chris Lattnerbe6df082007-12-12 07:56:42 +00002354 // Build _objc_ivar_list metadata for classes ivars if needed
2355 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2356 ? IDecl->getImplDeclNumIvars()
2357 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002358 if (NumIvars > 0) {
2359 static bool objc_ivar = false;
2360 if (!objc_ivar) {
2361 /* struct _objc_ivar {
2362 char *ivar_name;
2363 char *ivar_type;
2364 int ivar_offset;
2365 };
2366 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002367 Result += "\nstruct _objc_ivar {\n";
2368 Result += "\tchar *ivar_name;\n";
2369 Result += "\tchar *ivar_type;\n";
2370 Result += "\tint ivar_offset;\n";
2371 Result += "};\n";
2372
2373 /* struct _objc_ivar_list {
2374 int ivar_count;
2375 struct _objc_ivar ivar_list[];
2376 };
2377 */
2378 Result += "\nstruct _objc_ivar_list {\n";
2379 Result += "\tint ivar_count;\n";
2380 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002381 objc_ivar = true;
2382 }
2383
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002384 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2385 Result += IDecl->getName();
2386 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2387 "{\n\t";
2388 Result += utostr(NumIvars);
2389 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002390
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002391 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002392 if (IDecl->getImplDeclNumIvars() > 0) {
2393 IVI = IDecl->ivar_begin();
2394 IVE = IDecl->ivar_end();
2395 } else {
2396 IVI = CDecl->ivar_begin();
2397 IVE = CDecl->ivar_end();
2398 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002399 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002400 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002401 Result += "\", \"";
2402 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002404 Result += StrEncoding;
2405 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002406 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002407 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002408 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002409 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002410 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002411 Result += "\", \"";
2412 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002414 Result += StrEncoding;
2415 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002416 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002417 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002418 }
2419
2420 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002421 }
2422
2423 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002425 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002426
2427 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002429 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002430
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002431 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002432 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002433 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002434 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002435
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002436
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002437 // Declaration of class/meta-class metadata
2438 /* struct _objc_class {
2439 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002440 const char *super_class_name;
2441 char *name;
2442 long version;
2443 long info;
2444 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002445 struct _objc_ivar_list *ivars;
2446 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002447 struct objc_cache *cache;
2448 struct objc_protocol_list *protocols;
2449 const char *ivar_layout;
2450 struct _objc_class_ext *ext;
2451 };
2452 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002453 static bool objc_class = false;
2454 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 Result += "\nstruct _objc_class {\n";
2456 Result += "\tstruct _objc_class *isa;\n";
2457 Result += "\tconst char *super_class_name;\n";
2458 Result += "\tchar *name;\n";
2459 Result += "\tlong version;\n";
2460 Result += "\tlong info;\n";
2461 Result += "\tlong instance_size;\n";
2462 Result += "\tstruct _objc_ivar_list *ivars;\n";
2463 Result += "\tstruct _objc_method_list *methods;\n";
2464 Result += "\tstruct objc_cache *cache;\n";
2465 Result += "\tstruct _objc_protocol_list *protocols;\n";
2466 Result += "\tconst char *ivar_layout;\n";
2467 Result += "\tstruct _objc_class_ext *ext;\n";
2468 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002469 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002470 }
2471
2472 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002473 ObjCInterfaceDecl *RootClass = 0;
2474 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002475 while (SuperClass) {
2476 RootClass = SuperClass;
2477 SuperClass = SuperClass->getSuperClass();
2478 }
2479 SuperClass = CDecl->getSuperClass();
2480
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002481 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2482 Result += CDecl->getName();
2483 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2484 "{\n\t(struct _objc_class *)\"";
2485 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2486 Result += "\"";
2487
2488 if (SuperClass) {
2489 Result += ", \"";
2490 Result += SuperClass->getName();
2491 Result += "\", \"";
2492 Result += CDecl->getName();
2493 Result += "\"";
2494 }
2495 else {
2496 Result += ", 0, \"";
2497 Result += CDecl->getName();
2498 Result += "\"";
2499 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002500 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002501 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002502 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002503 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002504 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002505 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002506 Result += "\n";
2507 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002508 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 Result += ", 0\n";
2510 if (CDecl->getNumIntfRefProtocols() > 0) {
2511 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2512 Result += CDecl->getName();
2513 Result += ",0,0\n";
2514 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002515 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002516 Result += "\t,0,0,0,0\n";
2517 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002518
2519 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002520 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2521 Result += CDecl->getName();
2522 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2523 "{\n\t&_OBJC_METACLASS_";
2524 Result += CDecl->getName();
2525 if (SuperClass) {
2526 Result += ", \"";
2527 Result += SuperClass->getName();
2528 Result += "\", \"";
2529 Result += CDecl->getName();
2530 Result += "\"";
2531 }
2532 else {
2533 Result += ", 0, \"";
2534 Result += CDecl->getName();
2535 Result += "\"";
2536 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002537 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002538 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002539 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002540 Result += ",0";
2541 else {
2542 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002543 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002544 Result += CDecl->getName();
2545 Result += ")";
2546 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002547 if (NumIvars > 0) {
2548 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2549 Result += CDecl->getName();
2550 Result += "\n\t";
2551 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002552 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002553 Result += ",0";
2554 if (IDecl->getNumInstanceMethods() > 0) {
2555 Result += ", &_OBJC_INSTANCE_METHODS_";
2556 Result += CDecl->getName();
2557 Result += ", 0\n\t";
2558 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002559 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002560 Result += ",0,0";
2561 if (CDecl->getNumIntfRefProtocols() > 0) {
2562 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2563 Result += CDecl->getName();
2564 Result += ", 0,0\n";
2565 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002566 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002567 Result += ",0,0,0\n";
2568 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002569}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002570
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002571/// RewriteImplementations - This routine rewrites all method implementations
2572/// and emits meta-data.
2573
2574void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002575 int ClsDefCount = ClassImplementation.size();
2576 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002577
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002578 if (ClsDefCount == 0 && CatDefCount == 0)
2579 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002580 // Rewrite implemented methods
2581 for (int i = 0; i < ClsDefCount; i++)
2582 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002583
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002584 for (int i = 0; i < CatDefCount; i++)
2585 RewriteImplementationDecl(CategoryImplementation[i]);
2586
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002587 // This is needed for use of offsetof
2588 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002589
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002590 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002591 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002593
2594 // For each implemented category, write out all its meta data.
2595 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002596 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002597
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002598 // Write objc_symtab metadata
2599 /*
2600 struct _objc_symtab
2601 {
2602 long sel_ref_cnt;
2603 SEL *refs;
2604 short cls_def_cnt;
2605 short cat_def_cnt;
2606 void *defs[cls_def_cnt + cat_def_cnt];
2607 };
2608 */
2609
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002610 Result += "\nstruct _objc_symtab {\n";
2611 Result += "\tlong sel_ref_cnt;\n";
2612 Result += "\tSEL *refs;\n";
2613 Result += "\tshort cls_def_cnt;\n";
2614 Result += "\tshort cat_def_cnt;\n";
2615 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2616 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002617
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002618 Result += "static struct _objc_symtab "
2619 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2620 Result += "\t0, 0, " + utostr(ClsDefCount)
2621 + ", " + utostr(CatDefCount) + "\n";
2622 for (int i = 0; i < ClsDefCount; i++) {
2623 Result += "\t,&_OBJC_CLASS_";
2624 Result += ClassImplementation[i]->getName();
2625 Result += "\n";
2626 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002627
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002628 for (int i = 0; i < CatDefCount; i++) {
2629 Result += "\t,&_OBJC_CATEGORY_";
2630 Result += CategoryImplementation[i]->getClassInterface()->getName();
2631 Result += "_";
2632 Result += CategoryImplementation[i]->getName();
2633 Result += "\n";
2634 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002635
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002636 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002637
2638 // Write objc_module metadata
2639
2640 /*
2641 struct _objc_module {
2642 long version;
2643 long size;
2644 const char *name;
2645 struct _objc_symtab *symtab;
2646 }
2647 */
2648
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002649 Result += "\nstruct _objc_module {\n";
2650 Result += "\tlong version;\n";
2651 Result += "\tlong size;\n";
2652 Result += "\tconst char *name;\n";
2653 Result += "\tstruct _objc_symtab *symtab;\n";
2654 Result += "};\n\n";
2655 Result += "static struct _objc_module "
2656 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002657 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2658 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002659 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002660
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002661}
Chris Lattner311ff022007-10-16 22:36:42 +00002662