blob: 8d3035bd1212618a99bc3be818118d0f54a71624 [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;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000043 llvm::SmallVector<Stmt *, 32> Stmts;
44 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000045
46 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000047 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000048 FunctionDecl *MsgSendStretFunctionDecl;
49 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000050 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000051 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000052 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000053 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000054 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000055 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 // ObjC string constant support.
58 FileVarDecl *ConstantStringClassReference;
59 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000060
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000061 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000062 int BcLabelCount;
63
Steve Naroff874e2322007-11-15 10:28:18 +000064 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000065 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 RecordDecl *SuperStructDecl;
67
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000068 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000069 public:
Ted Kremenek95041a22007-12-19 22:51:13 +000070 void Initialize(ASTContext &context) {
Chris Lattner01c57482007-10-17 22:35:30 +000071 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000072 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000073 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000074 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000075 MsgSendStretFunctionDecl = 0;
76 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000077 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000078 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000079 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000080 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000081 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000082 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000083 ConstantStringClassReference = 0;
84 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000085 CurMethodDecl = 0;
86 SuperStructDecl = 0;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000087 BcLabelCount = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Chris Lattner26de4652007-12-02 01:13:47 +000089 // Get the ID and start/end of the main file.
Ted Kremenek95041a22007-12-19 22:51:13 +000090 MainFileID = SM->getMainFileID();
Chris Lattner26de4652007-12-02 01:13:47 +000091 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
92 MainFileStart = MainBuf->getBufferStart();
93 MainFileEnd = MainBuf->getBufferEnd();
94
95
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000096 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000097 // declaring objc_selector outside the parameter list removes a silly
98 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000099 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000100 "#ifndef OBJC_SUPER\n"
101 "struct objc_super { struct objc_object *o; "
102 "struct objc_object *superClass; };\n"
103 "#define OBJC_SUPER\n"
104 "#endif\n"
105 "#ifndef _REWRITER_typedef_Protocol\n"
106 "typedef struct objc_object Protocol;\n"
107 "#define _REWRITER_typedef_Protocol\n"
108 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000109 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000110 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000111 "extern struct objc_object *objc_msgSendSuper"
112 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000113 "extern struct objc_object *objc_msgSend_stret"
114 "(struct objc_object *, struct objc_selector *, ...);\n"
115 "extern struct objc_object *objc_msgSendSuper_stret"
116 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000117 "extern struct objc_object *objc_msgSend_fpret"
118 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000119 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000120 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000121 "extern struct objc_object *objc_getMetaClass"
122 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000123 "extern void objc_exception_throw(struct objc_object *);\n"
124 "extern void objc_exception_try_enter(void *);\n"
125 "extern void objc_exception_try_exit(void *);\n"
126 "extern struct objc_object *objc_exception_extract(void *);\n"
127 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000128 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000129 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000130 "#include <objc/objc.h>\n"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000131 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000132 "struct __objcFastEnumerationState {\n\t"
133 "unsigned long state;\n\t"
134 "id *itemsPtr;\n\t"
135 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000136 "unsigned long extra[5];\n};\n"
137 "#define __FASTENUMERATIONSTATE\n"
138 "#endif\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000139
Ted Kremenek95041a22007-12-19 22:51:13 +0000140 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroffab972d32007-11-04 22:37:50 +0000141 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000142 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 // Top Level Driver code.
145 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000146 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000147 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000148 ~RewriteTest();
149
150 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000151 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000152 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000154 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
155 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000156 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
158 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
159 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
160 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
161 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
162 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000163 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000164 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000165 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000166 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000167 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000168
Chris Lattnerf04da132007-10-24 17:06:59 +0000169 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000170 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000171 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000172 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000173 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000174 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000175 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000176 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000177 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
178 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
179 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
180 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000181 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000182 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
183 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000184 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000185 Stmt *RewriteBreakStmt(BreakStmt *S);
186 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000187 void SynthCountByEnumWithState(std::string &buf);
188
Steve Naroff09b266e2007-10-30 23:14:51 +0000189 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000190 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000191 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000192 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000193 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000194 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000195 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000196 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000197 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000198 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000199
Chris Lattnerf04da132007-10-24 17:06:59 +0000200 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000201 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000202 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000204 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000205 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000206
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
208 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000209 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000210 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000212 const char *ClassName,
213 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000214
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000216 int NumProtocols,
217 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000218 const char *ClassName,
219 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000220 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000221 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
223 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000224 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000225 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000226 };
227}
228
Chris Lattnere365c502007-11-30 22:25:36 +0000229ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
230 return new RewriteTest(Diags);
231}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000232
Chris Lattnerf04da132007-10-24 17:06:59 +0000233//===----------------------------------------------------------------------===//
234// Top Level Driver Code
235//===----------------------------------------------------------------------===//
236
Chris Lattner8a12c272007-10-11 18:38:32 +0000237void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000238 // Two cases: either the decl could be in the main file, or it could be in a
239 // #included file. If the former, rewrite it now. If the later, check to see
240 // if we rewrote the #include/#import.
241 SourceLocation Loc = D->getLocation();
242 Loc = SM->getLogicalLoc(Loc);
243
244 // If this is for a builtin, ignore it.
245 if (Loc.isInvalid()) return;
246
Steve Naroffebf2b562007-10-23 23:50:29 +0000247 // Look for built-in declarations that we need to refer during the rewrite.
248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000249 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000250 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
251 // declared in <Foundation/NSString.h>
252 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
253 ConstantStringClassReference = FVD;
254 return;
255 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000257 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000259 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000261 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 } else if (ObjCForwardProtocolDecl *FP =
263 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000264 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000265 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000266 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000267 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
268 return HandleDeclInMainFile(D);
269
Chris Lattnerf04da132007-10-24 17:06:59 +0000270 // Otherwise, see if there is a #import in the main file that should be
271 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000272 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000273}
274
Chris Lattnerf04da132007-10-24 17:06:59 +0000275/// HandleDeclInMainFile - This is called for each top-level decl defined in the
276/// main file of the input.
277void RewriteTest::HandleDeclInMainFile(Decl *D) {
278 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
279 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000280 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000281
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000282 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000283 if (Stmt *Body = MD->getBody()) {
284 //Body->dump();
285 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000286 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000287 CurMethodDecl = 0;
288 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000289 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000290 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000291 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000294 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000295 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000296 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000298 if (VD->getInit())
299 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
300 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000301 // Nothing yet.
302}
303
304RewriteTest::~RewriteTest() {
305 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000306
307 // Rewrite tabs if we care.
308 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000309
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000310 // Rewrite Objective-c meta data*
311 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000312 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000313
Chris Lattnerf04da132007-10-24 17:06:59 +0000314 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
315 // we are done.
316 if (const RewriteBuffer *RewriteBuf =
317 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000318 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000319 std::string S(RewriteBuf->begin(), RewriteBuf->end());
320 printf("%s\n", S.c_str());
321 } else {
322 printf("No changes\n");
323 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000324 // Emit metadata.
325 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000326}
327
Chris Lattnerf04da132007-10-24 17:06:59 +0000328//===----------------------------------------------------------------------===//
329// Syntactic (non-AST) Rewriting Code
330//===----------------------------------------------------------------------===//
331
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000332void RewriteTest::RewriteInclude(SourceLocation Loc) {
333 // Rip up the #include stack to the main file.
334 SourceLocation IncLoc = Loc, NextLoc = Loc;
335 do {
336 IncLoc = Loc;
337 Loc = SM->getLogicalLoc(NextLoc);
338 NextLoc = SM->getIncludeLoc(Loc);
339 } while (!NextLoc.isInvalid());
340
341 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
342 // IncLoc indicates the header that was included if it is useful.
343 IncLoc = SM->getLogicalLoc(IncLoc);
344 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
345 Loc == LastIncLoc)
346 return;
347 LastIncLoc = Loc;
348
349 unsigned IncCol = SM->getColumnNumber(Loc);
350 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
351
352 // Replace the #import with #include.
353 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
354}
355
Chris Lattnerf04da132007-10-24 17:06:59 +0000356void RewriteTest::RewriteTabs() {
357 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
358 const char *MainBufStart = MainBuf.first;
359 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000360
Chris Lattnerf04da132007-10-24 17:06:59 +0000361 // Loop over the whole file, looking for tabs.
362 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
363 if (*BufPtr != '\t')
364 continue;
365
366 // Okay, we found a tab. This tab will turn into at least one character,
367 // but it depends on which 'virtual column' it is in. Compute that now.
368 unsigned VCol = 0;
369 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
370 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
371 ++VCol;
372
373 // Okay, now that we know the virtual column, we know how many spaces to
374 // insert. We assume 8-character tab-stops.
375 unsigned Spaces = 8-(VCol & 7);
376
377 // Get the location of the tab.
378 SourceLocation TabLoc =
379 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
380
381 // Rewrite the single tab character into a sequence of spaces.
382 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
383 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000384}
385
386
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000388 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000389 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000390
391 // Get the start location and compute the semi location.
392 SourceLocation startLoc = ClassDecl->getLocation();
393 const char *startBuf = SM->getCharacterData(startLoc);
394 const char *semiPtr = strchr(startBuf, ';');
395
396 // Translate to typedef's that forward reference structs with the same name
397 // as the class. As a convenience, we include the original declaration
398 // as a comment.
399 std::string typedefString;
400 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000401 typedefString.append(startBuf, semiPtr-startBuf+1);
402 typedefString += "\n";
403 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000405 typedefString += "#ifndef _REWRITER_typedef_";
406 typedefString += ForwardDecl->getName();
407 typedefString += "\n";
408 typedefString += "#define _REWRITER_typedef_";
409 typedefString += ForwardDecl->getName();
410 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000411 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000412 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000413 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000414 }
415
416 // Replace the @class with typedefs corresponding to the classes.
417 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
418 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000419}
420
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000421void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000422 SourceLocation LocStart = Method->getLocStart();
423 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000424
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000425 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
426 Rewrite.InsertText(LocStart, "/* ", 3);
427 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
428 } else {
429 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000430 }
431}
432
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000433void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000434{
435 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000436 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000437 SourceLocation Loc = Property->getLocation();
438
439 Rewrite.ReplaceText(Loc, 0, "// ", 3);
440
441 // FIXME: handle properties that are declared across multiple lines.
442 }
443}
444
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000445void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000446 SourceLocation LocStart = CatDecl->getLocStart();
447
448 // FIXME: handle category headers that are declared across multiple lines.
449 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
450
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000451 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000452 E = CatDecl->instmeth_end(); I != E; ++I)
453 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000454 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000455 E = CatDecl->classmeth_end(); I != E; ++I)
456 RewriteMethodDeclaration(*I);
457
Steve Naroff423cb562007-10-30 13:30:57 +0000458 // Lastly, comment out the @end.
459 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
460}
461
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000462void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000463 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000464
Steve Naroff752d6ef2007-10-30 16:42:30 +0000465 SourceLocation LocStart = PDecl->getLocStart();
466
467 // FIXME: handle protocol headers that are declared across multiple lines.
468 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
469
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000470 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000471 E = PDecl->instmeth_end(); I != E; ++I)
472 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000473 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000474 E = PDecl->classmeth_end(); I != E; ++I)
475 RewriteMethodDeclaration(*I);
476
Steve Naroff752d6ef2007-10-30 16:42:30 +0000477 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000478 SourceLocation LocEnd = PDecl->getAtEndLoc();
479 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000480
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000481 // Must comment out @optional/@required
482 const char *startBuf = SM->getCharacterData(LocStart);
483 const char *endBuf = SM->getCharacterData(LocEnd);
484 for (const char *p = startBuf; p < endBuf; p++) {
485 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
486 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000487 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000488 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
489 CommentedOptional.c_str(), CommentedOptional.size());
490
491 }
492 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
493 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000494 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000495 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
496 CommentedRequired.c_str(), CommentedRequired.size());
497
498 }
499 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000500}
501
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000503 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000504 if (LocStart.isInvalid())
505 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000506 // FIXME: handle forward protocol that are declared across multiple lines.
507 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
508}
509
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000510void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000511 std::string &ResultStr) {
512 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000513 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000514 ResultStr += "id";
515 else
516 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000517 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000518
519 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000520 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000521
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000522 if (OMD->isInstance())
523 NameStr += "_I_";
524 else
525 NameStr += "_C_";
526
527 NameStr += OMD->getClassInterface()->getName();
528 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000529
530 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000531 if (ObjCCategoryImplDecl *CID =
532 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000533 NameStr += CID->getName();
534 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000535 }
536 // Append selector names, replacing ':' with '_'
537 const char *selName = OMD->getSelector().getName().c_str();
538 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000539 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000540 else {
541 std::string selString = OMD->getSelector().getName();
542 int len = selString.size();
543 for (int i = 0; i < len; i++)
544 if (selString[i] == ':')
545 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000546 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000547 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000548 // Remember this name for metadata emission
549 MethodInternalNames[OMD] = NameStr;
550 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000551
552 // Rewrite arguments
553 ResultStr += "(";
554
555 // invisible arguments
556 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000557 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000559 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000560 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000561 ResultStr += selfTy.getAsString();
562 }
563 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000564 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000565
566 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000567 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000568 ResultStr += " _cmd";
569
570 // Method arguments.
571 for (int i = 0; i < OMD->getNumParams(); i++) {
572 ParmVarDecl *PDecl = OMD->getParamDecl(i);
573 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000575 ResultStr += "id";
576 else
577 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000578 ResultStr += " ";
579 ResultStr += PDecl->getName();
580 }
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000581 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000582
583}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000584void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
586 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000587
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000588 if (IMD)
589 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
590 else
591 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000592
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000593 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000594 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
595 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000596 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 ObjCMethodDecl *OMD = *I;
598 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000599 SourceLocation LocStart = OMD->getLocStart();
600 SourceLocation LocEnd = OMD->getBody()->getLocStart();
601
602 const char *startBuf = SM->getCharacterData(LocStart);
603 const char *endBuf = SM->getCharacterData(LocEnd);
604 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
605 ResultStr.c_str(), ResultStr.size());
606 }
607
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000609 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
610 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000611 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612 ObjCMethodDecl *OMD = *I;
613 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000614 SourceLocation LocStart = OMD->getLocStart();
615 SourceLocation LocEnd = OMD->getBody()->getLocStart();
616
617 const char *startBuf = SM->getCharacterData(LocStart);
618 const char *endBuf = SM->getCharacterData(LocEnd);
619 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
620 ResultStr.c_str(), ResultStr.size());
621 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000622 if (IMD)
623 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
624 else
625 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000626}
627
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000628void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000629 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000630 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000631 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000632 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000633 ResultStr += ClassDecl->getName();
634 ResultStr += "\n";
635 ResultStr += "#define _REWRITER_typedef_";
636 ResultStr += ClassDecl->getName();
637 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000638 ResultStr += "typedef struct ";
639 ResultStr += ClassDecl->getName();
640 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000641 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000642 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000643
644 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000646 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000647 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000648
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000649 RewriteProperties(ClassDecl->getNumPropertyDecl(),
650 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000651 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000652 E = ClassDecl->instmeth_end(); I != E; ++I)
653 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000654 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000655 E = ClassDecl->classmeth_end(); I != E; ++I)
656 RewriteMethodDeclaration(*I);
657
Steve Naroff2feac5e2007-10-30 03:43:13 +0000658 // Lastly, comment out the @end.
659 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000660}
661
Steve Naroff7e3411b2007-11-15 02:58:25 +0000662Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000664 if (IV->isFreeIvar()) {
665 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
666 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000667 if (Rewrite.ReplaceStmt(IV, Replacement)) {
668 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000669 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
670 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000671 SourceRange Range = IV->getSourceRange();
672 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000673 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000674 delete IV;
675 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000676 } else {
677 if (CurMethodDecl) {
678 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000679 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000680 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
681 IdentifierInfo *II = intT->getDecl()->getIdentifier();
682 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
683 II, 0);
684 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
685
686 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
687 // Don't forget the parens to enforce the proper binding.
688 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000689 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
690 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000691 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
692 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000693 SourceRange Range = IV->getBase()->getSourceRange();
694 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000695 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000696 delete IV->getBase();
697 return PE;
698 }
699 }
700 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000701 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000702 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000703}
704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Function Body / Expression rewriting
707//===----------------------------------------------------------------------===//
708
Steve Narofff3473a72007-11-09 15:20:18 +0000709Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000710 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
711 isa<DoStmt>(S) || isa<ForStmt>(S))
712 Stmts.push_back(S);
713 else if (isa<ObjCForCollectionStmt>(S)) {
714 Stmts.push_back(S);
715 ObjCBcLabelNo.push_back(++BcLabelCount);
716 }
717
Chris Lattner311ff022007-10-16 22:36:42 +0000718 // Otherwise, just rewrite all children.
719 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
720 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000721 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000722 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000723 if (newStmt)
724 *CI = newStmt;
725 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000726
727 // Handle specific things.
728 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
729 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000730
731 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
732 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000733
734 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
735 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000736
737 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
738 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000739
Steve Naroff934f2762007-10-24 22:48:43 +0000740 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
741 // Before we rewrite it, put the original message expression in a comment.
742 SourceLocation startLoc = MessExpr->getLocStart();
743 SourceLocation endLoc = MessExpr->getLocEnd();
744
745 const char *startBuf = SM->getCharacterData(startLoc);
746 const char *endBuf = SM->getCharacterData(endLoc);
747
748 std::string messString;
749 messString += "// ";
750 messString.append(startBuf, endBuf-startBuf+1);
751 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000752
Steve Naroff934f2762007-10-24 22:48:43 +0000753 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
754 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
755 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000756 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000757 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000758 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000759
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000760 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
761 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000762
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000763 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
764 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000765
766 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
767 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000768
769 if (ObjCForCollectionStmt *StmtForCollection =
770 dyn_cast<ObjCForCollectionStmt>(S))
771 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000772 if (BreakStmt *StmtBreakStmt =
773 dyn_cast<BreakStmt>(S))
774 return RewriteBreakStmt(StmtBreakStmt);
775 if (ContinueStmt *StmtContinueStmt =
776 dyn_cast<ContinueStmt>(S))
777 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000778
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000779 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
780 isa<DoStmt>(S) || isa<ForStmt>(S)) {
781 assert(!Stmts.empty() && "Statement stack is empty");
782 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
783 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
784 && "Statement stack mismatch");
785 Stmts.pop_back();
786 }
Steve Naroff874e2322007-11-15 10:28:18 +0000787#if 0
788 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
789 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
790 // Get the new text.
791 std::ostringstream Buf;
792 Replacement->printPretty(Buf);
793 const std::string &Str = Buf.str();
794
795 printf("CAST = %s\n", &Str[0]);
796 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
797 delete S;
798 return Replacement;
799 }
800#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000801 // Return this stmt unmodified.
802 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000803}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000804
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000805/// SynthCountByEnumWithState - To print:
806/// ((unsigned int (*)
807/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
808/// (void *)objc_msgSend)((id)l_collection,
809/// sel_registerName(
810/// "countByEnumeratingWithState:objects:count:"),
811/// &enumState,
812/// (id *)items, (unsigned int)16)
813///
814void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
815 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
816 "id *, unsigned int))(void *)objc_msgSend)";
817 buf += "\n\t\t";
818 buf += "((id)l_collection,\n\t\t";
819 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
820 buf += "\n\t\t";
821 buf += "&enumState, "
822 "(id *)items, (unsigned int)16)";
823}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000824
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000825/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
826/// statement to exit to its outer synthesized loop.
827///
828Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
829 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
830 return S;
831 // replace break with goto __break_label
832 std::string buf;
833
834 SourceLocation startLoc = S->getLocStart();
835 buf = "goto __break_label_";
836 buf += utostr(ObjCBcLabelNo.back());
837 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
838
839 return 0;
840}
841
842/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
843/// statement to continue with its inner synthesized loop.
844///
845Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
846 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
847 return S;
848 // replace continue with goto __continue_label
849 std::string buf;
850
851 SourceLocation startLoc = S->getLocStart();
852 buf = "goto __continue_label_";
853 buf += utostr(ObjCBcLabelNo.back());
854 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
855
856 return 0;
857}
858
Fariborz Jahaniane84b0402008-01-09 01:25:54 +0000859/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000860/// It rewrites:
861/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000862
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000863/// Into:
864/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000865/// type elem;
866/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000867/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000868/// id l_collection = (id)collection;
869/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
870/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000871/// if (limit) {
872/// unsigned long startMutations = *enumState.mutationsPtr;
873/// do {
874/// unsigned long counter = 0;
875/// do {
876/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000877/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000878/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000879/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000880/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000881/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000882/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
883/// objects:items count:16]);
884/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000885/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000886/// }
887/// else
888/// elem = nil;
889/// }
890///
891Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000892 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
893 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
894 "ObjCForCollectionStmt Statement stack mismatch");
895 assert(!ObjCBcLabelNo.empty() &&
896 "ObjCForCollectionStmt - Label No stack empty");
897
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000898 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000899 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000900 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000901 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000902 std::string buf;
903 buf = "\n{\n\t";
904 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
905 // type elem;
906 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000907 elementTypeAsString = ElementType.getAsString();
908 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000909 buf += " ";
910 elementName = DS->getDecl()->getName();
911 buf += elementName;
912 buf += ";\n\t";
913 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000914 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000915 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000916 elementTypeAsString = DR->getDecl()->getType().getAsString();
917 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000918 else
919 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
920
921 // struct __objcFastEnumerationState enumState = { 0 };
922 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
923 // id items[16];
924 buf += "id items[16];\n\t";
925 // id l_collection = (id)
926 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +0000927 // Find start location of 'collection' the hard way!
928 const char *startCollectionBuf = startBuf;
929 startCollectionBuf += 3; // skip 'for'
930 startCollectionBuf = strchr(startCollectionBuf, '(');
931 startCollectionBuf++; // skip '('
932 // find 'in' and skip it.
933 while (*startCollectionBuf != ' ' ||
934 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
935 (*(startCollectionBuf+3) != ' ' &&
936 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
937 startCollectionBuf++;
938 startCollectionBuf += 3;
939
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000940 // Replace: "for (type element in" with string constructed thus far.
941 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
942 buf.c_str(), buf.size());
943 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +0000944 SourceLocation rightParenLoc = S->getRParenLoc();
945 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
946 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000947 buf = ";\n\t";
948
949 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
950 // objects:items count:16];
951 // which is synthesized into:
952 // unsigned int limit =
953 // ((unsigned int (*)
954 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
955 // (void *)objc_msgSend)((id)l_collection,
956 // sel_registerName(
957 // "countByEnumeratingWithState:objects:count:"),
958 // (struct __objcFastEnumerationState *)&state,
959 // (id *)items, (unsigned int)16);
960 buf += "unsigned long limit =\n\t\t";
961 SynthCountByEnumWithState(buf);
962 buf += ";\n\t";
963 /// if (limit) {
964 /// unsigned long startMutations = *enumState.mutationsPtr;
965 /// do {
966 /// unsigned long counter = 0;
967 /// do {
968 /// if (startMutations != *enumState.mutationsPtr)
969 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000970 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000971 buf += "if (limit) {\n\t";
972 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
973 buf += "do {\n\t\t";
974 buf += "unsigned long counter = 0;\n\t\t";
975 buf += "do {\n\t\t\t";
976 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
977 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
978 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000979 buf += " = (";
980 buf += elementTypeAsString;
981 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000982 // Replace ')' in for '(' type elem in collection ')' with all of these.
983 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
984
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000985 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000986 /// } while (counter < limit);
987 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
988 /// objects:items count:16]);
989 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000990 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000991 /// }
992 /// else
993 /// elem = nil;
994 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000995 ///
996 buf = ";\n\t";
997 buf += "__continue_label_";
998 buf += utostr(ObjCBcLabelNo.back());
999 buf += ": ;";
1000 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001001 buf += "} while (counter < limit);\n\t";
1002 buf += "} while (limit = ";
1003 SynthCountByEnumWithState(buf);
1004 buf += ");\n\t";
1005 buf += elementName;
1006 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001007 buf += "__break_label_";
1008 buf += utostr(ObjCBcLabelNo.back());
1009 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001010 buf += "}\n\t";
1011 buf += "else\n\t\t";
1012 buf += elementName;
1013 buf += " = nil;\n";
1014 buf += "}\n";
1015 // Insert all these *after* the statement body.
1016 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1017 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1018 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1019 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001020 Stmts.pop_back();
1021 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001022
1023 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001024}
1025
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001027 // Get the start location and compute the semi location.
1028 SourceLocation startLoc = S->getLocStart();
1029 const char *startBuf = SM->getCharacterData(startLoc);
1030
1031 assert((*startBuf == '@') && "bogus @try location");
1032
1033 std::string buf;
1034 // declare a new scope with two variables, _stack and _rethrow.
1035 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1036 buf += "int buf[18/*32-bit i386*/];\n";
1037 buf += "char *pointers[4];} _stack;\n";
1038 buf += "id volatile _rethrow = 0;\n";
1039 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001040 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001041
1042 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1043
1044 startLoc = S->getTryBody()->getLocEnd();
1045 startBuf = SM->getCharacterData(startLoc);
1046
1047 assert((*startBuf == '}') && "bogus @try block");
1048
1049 SourceLocation lastCurlyLoc = startLoc;
1050
1051 startLoc = startLoc.getFileLocWithOffset(1);
1052 buf = " /* @catch begin */ else {\n";
1053 buf += " id _caught = objc_exception_extract(&_stack);\n";
1054 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001055 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001056 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1057 buf += " else { /* @catch continue */";
1058
Chris Lattner28d1fe82007-11-08 04:41:51 +00001059 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001060
1061 bool sawIdTypedCatch = false;
1062 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001063 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001064 while (catchList) {
1065 Stmt *catchStmt = catchList->getCatchParamStmt();
1066
1067 if (catchList == S->getCatchStmts())
1068 buf = "if ("; // we are generating code for the first catch clause
1069 else
1070 buf = "else if (";
1071 startLoc = catchList->getLocStart();
1072 startBuf = SM->getCharacterData(startLoc);
1073
1074 assert((*startBuf == '@') && "bogus @catch location");
1075
1076 const char *lParenLoc = strchr(startBuf, '(');
1077
1078 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1079 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001080 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001081 buf += "1) { ";
1082 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1083 buf.c_str(), buf.size());
1084 sawIdTypedCatch = true;
1085 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001086 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001087
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001088 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001089 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001090 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001091 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001092 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +00001093 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1094 buf.c_str(), buf.size());
1095 }
1096 }
1097 // Now rewrite the body...
1098 lastCatchBody = catchList->getCatchBody();
1099 SourceLocation rParenLoc = catchList->getRParenLoc();
1100 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1101 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1102 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1103 assert((*rParenBuf == ')') && "bogus @catch paren location");
1104 assert((*bodyBuf == '{') && "bogus @catch body location");
1105
1106 buf = " = _caught;";
1107 // Here we replace ") {" with "= _caught;" (which initializes and
1108 // declares the @catch parameter).
1109 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1110 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001111 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001112 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001113 }
Steve Naroff75730982007-11-07 04:08:17 +00001114 catchList = catchList->getNextCatchStmt();
1115 }
1116 // Complete the catch list...
1117 if (lastCatchBody) {
1118 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1119 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1120 assert((*bodyBuf == '}') && "bogus @catch body location");
1121 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1122 buf = " } } /* @catch end */\n";
1123
Chris Lattner28d1fe82007-11-08 04:41:51 +00001124 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001125
1126 // Set lastCurlyLoc
1127 lastCurlyLoc = lastCatchBody->getLocEnd();
1128 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001129 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001130 startLoc = finalStmt->getLocStart();
1131 startBuf = SM->getCharacterData(startLoc);
1132 assert((*startBuf == '@') && "bogus @finally start");
1133
1134 buf = "/* @finally */";
1135 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1136
1137 Stmt *body = finalStmt->getFinallyBody();
1138 SourceLocation startLoc = body->getLocStart();
1139 SourceLocation endLoc = body->getLocEnd();
1140 const char *startBuf = SM->getCharacterData(startLoc);
1141 const char *endBuf = SM->getCharacterData(endLoc);
1142 assert((*startBuf == '{') && "bogus @finally body location");
1143 assert((*endBuf == '}') && "bogus @finally body location");
1144
1145 startLoc = startLoc.getFileLocWithOffset(1);
1146 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001147 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001148 endLoc = endLoc.getFileLocWithOffset(-1);
1149 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001150 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001151
1152 // Set lastCurlyLoc
1153 lastCurlyLoc = body->getLocEnd();
1154 }
1155 // Now emit the final closing curly brace...
1156 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1157 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001158 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001159 return 0;
1160}
1161
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001162Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001163 return 0;
1164}
1165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001166Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001167 return 0;
1168}
1169
Steve Naroff2bd03922007-11-07 15:32:26 +00001170// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1171// the throw expression is typically a message expression that's already
1172// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001173Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001174 // Get the start location and compute the semi location.
1175 SourceLocation startLoc = S->getLocStart();
1176 const char *startBuf = SM->getCharacterData(startLoc);
1177
1178 assert((*startBuf == '@') && "bogus @throw location");
1179
1180 std::string buf;
1181 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1182 buf = "objc_exception_throw(";
1183 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1184 const char *semiBuf = strchr(startBuf, ';');
1185 assert((*semiBuf == ';') && "@throw: can't find ';'");
1186 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1187 buf = ");";
1188 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1189 return 0;
1190}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001191
Chris Lattnere64b7772007-10-24 16:57:36 +00001192Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001193 // Create a new string expression.
1194 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001195 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001197 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1198 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001199 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +00001200 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1201 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001202 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1203 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +00001204 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001205 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +00001206 }
1207
Chris Lattner07506182007-11-30 22:53:43 +00001208 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001209 delete Exp;
1210 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001211}
1212
Steve Naroffb42f8412007-11-05 14:50:49 +00001213Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1214 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1215 // Create a call to sel_registerName("selName").
1216 llvm::SmallVector<Expr*, 8> SelExprs;
1217 QualType argType = Context->getPointerType(Context->CharTy);
1218 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1219 Exp->getSelector().getName().size(),
1220 false, argType, SourceLocation(),
1221 SourceLocation()));
1222 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1223 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001224 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1225 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001226 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1227 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001228 SourceRange Range = Exp->getSourceRange();
1229 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001230 }
Steve Naroffb42f8412007-11-05 14:50:49 +00001231 delete Exp;
1232 return SelExp;
1233}
1234
Steve Naroff934f2762007-10-24 22:48:43 +00001235CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1236 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001237 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001238 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001239
1240 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001241 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001242
1243 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001244 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001245 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1246
1247 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001248
Steve Naroff934f2762007-10-24 22:48:43 +00001249 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1250}
1251
Steve Naroffd5255f52007-11-01 13:24:47 +00001252static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1253 const char *&startRef, const char *&endRef) {
1254 while (startBuf < endBuf) {
1255 if (*startBuf == '<')
1256 startRef = startBuf; // mark the start.
1257 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001258 if (startRef && *startRef == '<') {
1259 endRef = startBuf; // mark the end.
1260 return true;
1261 }
1262 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001263 }
1264 startBuf++;
1265 }
1266 return false;
1267}
1268
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001269static void scanToNextArgument(const char *&argRef) {
1270 int angle = 0;
1271 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1272 if (*argRef == '<')
1273 angle++;
1274 else if (*argRef == '>')
1275 angle--;
1276 argRef++;
1277 }
1278 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1279}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001280
Steve Naroffd5255f52007-11-01 13:24:47 +00001281bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001282
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001283 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001284 return true;
1285
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001286 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001287 return true;
1288
Steve Naroffd5255f52007-11-01 13:24:47 +00001289 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001290 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001291 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001292 return true; // we have "Class <Protocol> *".
1293 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001294 return false;
1295}
1296
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001297void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001298 SourceLocation Loc;
1299 QualType Type;
1300 const FunctionTypeProto *proto = 0;
1301 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1302 Loc = VD->getLocation();
1303 Type = VD->getType();
1304 }
1305 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1306 Loc = FD->getLocation();
1307 // Check for ObjC 'id' and class types that have been adorned with protocol
1308 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1309 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1310 assert(funcType && "missing function type");
1311 proto = dyn_cast<FunctionTypeProto>(funcType);
1312 if (!proto)
1313 return;
1314 Type = proto->getResultType();
1315 }
1316 else
1317 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001318
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001319 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001320 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001321
1322 const char *endBuf = SM->getCharacterData(Loc);
1323 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001324 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001325 startBuf--; // scan backward (from the decl location) for return type.
1326 const char *startRef = 0, *endRef = 0;
1327 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1328 // Get the locations of the startRef, endRef.
1329 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1330 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1331 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001332 Rewrite.InsertText(LessLoc, "/*", 2);
1333 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001334 }
1335 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001336 if (!proto)
1337 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001338 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001339 const char *startBuf = SM->getCharacterData(Loc);
1340 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001341 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1342 if (needToScanForQualifiers(proto->getArgType(i))) {
1343 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001344
Steve Naroffd5255f52007-11-01 13:24:47 +00001345 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001346 // scan forward (from the decl location) for argument types.
1347 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001348 const char *startRef = 0, *endRef = 0;
1349 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1350 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001351 SourceLocation LessLoc =
1352 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1353 SourceLocation GreaterLoc =
1354 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001355 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001356 Rewrite.InsertText(LessLoc, "/*", 2);
1357 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001358 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001359 startBuf = ++endBuf;
1360 }
1361 else {
1362 while (*startBuf != ')' && *startBuf != ',')
1363 startBuf++; // scan forward (from the decl location) for argument types.
1364 startBuf++;
1365 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001366 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001367}
1368
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001369// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1370void RewriteTest::SynthSelGetUidFunctionDecl() {
1371 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1372 llvm::SmallVector<QualType, 16> ArgTys;
1373 ArgTys.push_back(Context->getPointerType(
1374 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001375 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001376 &ArgTys[0], ArgTys.size(),
1377 false /*isVariadic*/);
1378 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1379 SelGetUidIdent, getFuncType,
1380 FunctionDecl::Extern, false, 0);
1381}
1382
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001383// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1384void RewriteTest::SynthGetProtocolFunctionDecl() {
1385 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1386 llvm::SmallVector<QualType, 16> ArgTys;
1387 ArgTys.push_back(Context->getPointerType(
1388 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001389 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001390 &ArgTys[0], ArgTys.size(),
1391 false /*isVariadic*/);
1392 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1393 SelGetProtoIdent, getFuncType,
1394 FunctionDecl::Extern, false, 0);
1395}
1396
Steve Naroff09b266e2007-10-30 23:14:51 +00001397void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1398 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001399 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001400 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001401 return;
1402 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001403 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001404}
1405
1406// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1407void RewriteTest::SynthMsgSendFunctionDecl() {
1408 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1409 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001410 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001411 assert(!argT.isNull() && "Can't find 'id' type");
1412 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001413 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001414 assert(!argT.isNull() && "Can't find 'SEL' type");
1415 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001416 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001417 &ArgTys[0], ArgTys.size(),
1418 true /*isVariadic*/);
1419 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1420 msgSendIdent, msgSendType,
1421 FunctionDecl::Extern, false, 0);
1422}
1423
Steve Naroff874e2322007-11-15 10:28:18 +00001424// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1425void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1427 llvm::SmallVector<QualType, 16> ArgTys;
1428 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1429 &Context->Idents.get("objc_super"), 0);
1430 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1431 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1432 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001433 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001434 assert(!argT.isNull() && "Can't find 'SEL' type");
1435 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001437 &ArgTys[0], ArgTys.size(),
1438 true /*isVariadic*/);
1439 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1440 msgSendIdent, msgSendType,
1441 FunctionDecl::Extern, false, 0);
1442}
1443
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001444// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1445void RewriteTest::SynthMsgSendStretFunctionDecl() {
1446 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1447 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001448 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001449 assert(!argT.isNull() && "Can't find 'id' type");
1450 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001451 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001452 assert(!argT.isNull() && "Can't find 'SEL' type");
1453 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001454 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001455 &ArgTys[0], ArgTys.size(),
1456 true /*isVariadic*/);
1457 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1458 msgSendIdent, msgSendType,
1459 FunctionDecl::Extern, false, 0);
1460}
1461
1462// SynthMsgSendSuperStretFunctionDecl -
1463// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1464void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1465 IdentifierInfo *msgSendIdent =
1466 &Context->Idents.get("objc_msgSendSuper_stret");
1467 llvm::SmallVector<QualType, 16> ArgTys;
1468 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1469 &Context->Idents.get("objc_super"), 0);
1470 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1471 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1472 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001473 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001474 assert(!argT.isNull() && "Can't find 'SEL' type");
1475 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001476 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001477 &ArgTys[0], ArgTys.size(),
1478 true /*isVariadic*/);
1479 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1480 msgSendIdent, msgSendType,
1481 FunctionDecl::Extern, false, 0);
1482}
1483
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001484// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1485void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1486 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1487 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001488 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001489 assert(!argT.isNull() && "Can't find 'id' type");
1490 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001491 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001492 assert(!argT.isNull() && "Can't find 'SEL' type");
1493 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001494 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001495 &ArgTys[0], ArgTys.size(),
1496 true /*isVariadic*/);
1497 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1498 msgSendIdent, msgSendType,
1499 FunctionDecl::Extern, false, 0);
1500}
1501
Steve Naroff09b266e2007-10-30 23:14:51 +00001502// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1503void RewriteTest::SynthGetClassFunctionDecl() {
1504 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1505 llvm::SmallVector<QualType, 16> ArgTys;
1506 ArgTys.push_back(Context->getPointerType(
1507 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001508 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001509 &ArgTys[0], ArgTys.size(),
1510 false /*isVariadic*/);
1511 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1512 getClassIdent, getClassType,
1513 FunctionDecl::Extern, false, 0);
1514}
1515
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001516// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1517void RewriteTest::SynthGetMetaClassFunctionDecl() {
1518 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1519 llvm::SmallVector<QualType, 16> ArgTys;
1520 ArgTys.push_back(Context->getPointerType(
1521 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001522 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001523 &ArgTys[0], ArgTys.size(),
1524 false /*isVariadic*/);
1525 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1526 getClassIdent, getClassType,
1527 FunctionDecl::Extern, false, 0);
1528}
1529
Steve Naroff96984642007-11-08 14:30:50 +00001530// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1531void RewriteTest::SynthCFStringFunctionDecl() {
1532 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1533 llvm::SmallVector<QualType, 16> ArgTys;
1534 ArgTys.push_back(Context->getPointerType(
1535 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001536 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001537 &ArgTys[0], ArgTys.size(),
1538 false /*isVariadic*/);
1539 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1540 getClassIdent, getClassType,
1541 FunctionDecl::Extern, false, 0);
1542}
1543
Steve Naroffbeaf2992007-11-03 11:27:19 +00001544Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001545#if 1
1546 // This rewrite is specific to GCC, which has builtin support for CFString.
1547 if (!CFStringFunctionDecl)
1548 SynthCFStringFunctionDecl();
1549 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1550 llvm::SmallVector<Expr*, 8> StrExpr;
1551 StrExpr.push_back(Exp->getString());
1552 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1553 &StrExpr[0], StrExpr.size());
1554 // cast to NSConstantString *
1555 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001556 if (Rewrite.ReplaceStmt(Exp, cast)) {
1557 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001558 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1559 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001560 SourceRange Range = Exp->getSourceRange();
1561 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001562 }
Steve Naroff96984642007-11-08 14:30:50 +00001563 delete Exp;
1564 return cast;
1565#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001566 assert(ConstantStringClassReference && "Can't find constant string reference");
1567 llvm::SmallVector<Expr*, 4> InitExprs;
1568
1569 // Synthesize "(Class)&_NSConstantStringClassReference"
1570 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1571 ConstantStringClassReference->getType(),
1572 SourceLocation());
1573 QualType expType = Context->getPointerType(ClsRef->getType());
1574 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1575 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001576 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001577 SourceLocation());
1578 InitExprs.push_back(cast); // set the 'isa'.
1579 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1580 unsigned IntSize = static_cast<unsigned>(
1581 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1582 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1583 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1584 Exp->getLocStart());
1585 InitExprs.push_back(len); // set "int numBytes".
1586
1587 // struct NSConstantString
1588 QualType CFConstantStrType = Context->getCFConstantStringType();
1589 // (struct NSConstantString) { <exprs from above> }
1590 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1591 &InitExprs[0], InitExprs.size(),
1592 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001593 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001594 // struct NSConstantString *
1595 expType = Context->getPointerType(StrRep->getType());
1596 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1597 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001598 // cast to NSConstantString *
1599 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001600 Rewrite.ReplaceStmt(Exp, cast);
1601 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001602 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001603#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001604}
1605
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001606ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001607 // check if we are sending a message to 'super'
1608 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001609 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1610 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1611 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1612 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001613 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001615 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001616 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001617 if (ObjCInterfaceType *IT =
1618 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001619 if (IT->getDecl() ==
1620 CurMethodDecl->getClassInterface()->getSuperClass())
1621 return IT->getDecl();
1622 }
1623 }
1624 }
1625 }
1626 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001627 }
Steve Naroff874e2322007-11-15 10:28:18 +00001628 }
1629 return 0;
1630}
1631
1632// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1633QualType RewriteTest::getSuperStructType() {
1634 if (!SuperStructDecl) {
1635 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1636 &Context->Idents.get("objc_super"), 0);
1637 QualType FieldTypes[2];
1638
1639 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001640 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001641 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001643 // Create fields
1644 FieldDecl *FieldDecls[2];
1645
1646 for (unsigned i = 0; i < 2; ++i)
1647 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1648
1649 SuperStructDecl->defineBody(FieldDecls, 4);
1650 }
1651 return Context->getTagDeclType(SuperStructDecl);
1652}
1653
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001655 if (!SelGetUidFunctionDecl)
1656 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001657 if (!MsgSendFunctionDecl)
1658 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001659 if (!MsgSendSuperFunctionDecl)
1660 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001661 if (!MsgSendStretFunctionDecl)
1662 SynthMsgSendStretFunctionDecl();
1663 if (!MsgSendSuperStretFunctionDecl)
1664 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001665 if (!MsgSendFpretFunctionDecl)
1666 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001667 if (!GetClassFunctionDecl)
1668 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001669 if (!GetMetaClassFunctionDecl)
1670 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001671
Steve Naroff874e2322007-11-15 10:28:18 +00001672 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001673 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1674 // May need to use objc_msgSend_stret() as well.
1675 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001676 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001677 QualType resultType = mDecl->getResultType();
1678 if (resultType.getCanonicalType()->isStructureType()
1679 || resultType.getCanonicalType()->isUnionType())
1680 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001681 else if (resultType.getCanonicalType()->isRealFloatingType())
1682 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001683 }
Steve Naroff874e2322007-11-15 10:28:18 +00001684
Steve Naroff934f2762007-10-24 22:48:43 +00001685 // Synthesize a call to objc_msgSend().
1686 llvm::SmallVector<Expr*, 8> MsgExprs;
1687 IdentifierInfo *clsName = Exp->getClassName();
1688
1689 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1690 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001691 if (!strcmp(clsName->getName(), "super")) {
1692 MsgSendFlavor = MsgSendSuperFunctionDecl;
1693 if (MsgSendStretFlavor)
1694 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1695 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1696
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001697 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001698 CurMethodDecl->getClassInterface()->getSuperClass();
1699
1700 llvm::SmallVector<Expr*, 4> InitExprs;
1701
1702 // set the receiver to self, the first argument to all methods.
1703 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001704 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001705 SourceLocation()));
1706 llvm::SmallVector<Expr*, 8> ClsExprs;
1707 QualType argType = Context->getPointerType(Context->CharTy);
1708 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1709 SuperDecl->getIdentifier()->getLength(),
1710 false, argType, SourceLocation(),
1711 SourceLocation()));
1712 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1713 &ClsExprs[0],
1714 ClsExprs.size());
1715 // To turn off a warning, type-cast to 'id'
1716 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001717 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001718 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1719 // struct objc_super
1720 QualType superType = getSuperStructType();
1721 // (struct objc_super) { <exprs from above> }
1722 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1723 &InitExprs[0], InitExprs.size(),
1724 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001725 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001726 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001727 // struct objc_super *
1728 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1729 Context->getPointerType(SuperRep->getType()),
1730 SourceLocation());
1731 MsgExprs.push_back(Unop);
1732 } else {
1733 llvm::SmallVector<Expr*, 8> ClsExprs;
1734 QualType argType = Context->getPointerType(Context->CharTy);
1735 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1736 clsName->getLength(),
1737 false, argType, SourceLocation(),
1738 SourceLocation()));
1739 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1740 &ClsExprs[0],
1741 ClsExprs.size());
1742 MsgExprs.push_back(Cls);
1743 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001744 } else { // instance message.
1745 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001746
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001747 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001748 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001749 if (MsgSendStretFlavor)
1750 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001751 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1752
1753 llvm::SmallVector<Expr*, 4> InitExprs;
1754
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001755 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001756 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001757 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001758
1759 llvm::SmallVector<Expr*, 8> ClsExprs;
1760 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001761 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1762 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001763 false, argType, SourceLocation(),
1764 SourceLocation()));
1765 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001766 &ClsExprs[0],
1767 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001768 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001769 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001770 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001771 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001772 // struct objc_super
1773 QualType superType = getSuperStructType();
1774 // (struct objc_super) { <exprs from above> }
1775 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1776 &InitExprs[0], InitExprs.size(),
1777 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001778 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001779 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001780 // struct objc_super *
1781 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1782 Context->getPointerType(SuperRep->getType()),
1783 SourceLocation());
1784 MsgExprs.push_back(Unop);
1785 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001786 // Remove all type-casts because it may contain objc-style types; e.g.
1787 // Foo<Proto> *.
1788 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1789 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001790 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001791 MsgExprs.push_back(recExpr);
1792 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001793 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001794 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001795 llvm::SmallVector<Expr*, 8> SelExprs;
1796 QualType argType = Context->getPointerType(Context->CharTy);
1797 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1798 Exp->getSelector().getName().size(),
1799 false, argType, SourceLocation(),
1800 SourceLocation()));
1801 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1802 &SelExprs[0], SelExprs.size());
1803 MsgExprs.push_back(SelExp);
1804
1805 // Now push any user supplied arguments.
1806 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001807 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001808 // Make all implicit casts explicit...ICE comes in handy:-)
1809 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1810 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001811 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1812 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001813 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001814 }
1815 // Make id<P...> cast into an 'id' cast.
1816 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001817 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001818 while ((CE = dyn_cast<CastExpr>(userExpr)))
1819 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001820 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001821 userExpr, SourceLocation());
1822 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001823 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001824 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001825 // We've transferred the ownership to MsgExprs. Null out the argument in
1826 // the original expression, since we will delete it below.
1827 Exp->setArg(i, 0);
1828 }
Steve Naroffab972d32007-11-04 22:37:50 +00001829 // Generate the funky cast.
1830 CastExpr *cast;
1831 llvm::SmallVector<QualType, 8> ArgTypes;
1832 QualType returnType;
1833
1834 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001835 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1836 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1837 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 ArgTypes.push_back(Context->getObjCIdType());
1839 ArgTypes.push_back(Context->getObjCSelType());
1840 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001841 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001842 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001843 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1844 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001845 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001846 ArgTypes.push_back(t);
1847 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1849 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001850 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001851 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001852 }
1853 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001854 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001855
1856 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001857 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1858 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001859
1860 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1861 // If we don't do this cast, we get the following bizarre warning/note:
1862 // xx.m:13: warning: function called through a non-compatible type
1863 // xx.m:13: note: if this code is reached, the program will abort
1864 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1865 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001866
Steve Naroffab972d32007-11-04 22:37:50 +00001867 // Now do the "normal" pointer to function cast.
1868 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001869 &ArgTypes[0], ArgTypes.size(),
1870 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001871 castType = Context->getPointerType(castType);
1872 cast = new CastExpr(castType, cast, SourceLocation());
1873
1874 // Don't forget the parens to enforce the proper binding.
1875 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1876
1877 const FunctionType *FT = msgSendType->getAsFunctionType();
1878 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1879 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001880 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001881 if (MsgSendStretFlavor) {
1882 // We have the method which returns a struct/union. Must also generate
1883 // call to objc_msgSend_stret and hang both varieties on a conditional
1884 // expression which dictate which one to envoke depending on size of
1885 // method's return type.
1886
1887 // Create a reference to the objc_msgSend_stret() declaration.
1888 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1889 SourceLocation());
1890 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1891 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1892 SourceLocation());
1893 // Now do the "normal" pointer to function cast.
1894 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001895 &ArgTypes[0], ArgTypes.size(),
1896 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001897 castType = Context->getPointerType(castType);
1898 cast = new CastExpr(castType, cast, SourceLocation());
1899
1900 // Don't forget the parens to enforce the proper binding.
1901 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1902
1903 FT = msgSendType->getAsFunctionType();
1904 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1905 FT->getResultType(), SourceLocation());
1906
1907 // Build sizeof(returnType)
1908 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1909 returnType, Context->getSizeType(),
1910 SourceLocation(), SourceLocation());
1911 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1912 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1913 // For X86 it is more complicated and some kind of target specific routine
1914 // is needed to decide what to do.
1915 unsigned IntSize = static_cast<unsigned>(
1916 Context->getTypeSize(Context->IntTy, SourceLocation()));
1917
1918 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1919 Context->IntTy,
1920 SourceLocation());
1921 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1922 BinaryOperator::LE,
1923 Context->IntTy,
1924 SourceLocation());
1925 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1926 ConditionalOperator *CondExpr =
1927 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001928 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001929 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001930 return ReplacingStmt;
1931}
1932
1933Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1934 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00001935 // Now do the actual rewrite.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001936 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroff5ca40202007-12-19 14:32:56 +00001937 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001938 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1939 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001940 SourceRange Range = Exp->getSourceRange();
1941 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001942 }
Steve Naroff934f2762007-10-24 22:48:43 +00001943
Chris Lattnere64b7772007-10-24 16:57:36 +00001944 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001945 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00001946}
1947
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001948/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1949/// call to objc_getProtocol("proto-name").
1950Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1951 if (!GetProtocolFunctionDecl)
1952 SynthGetProtocolFunctionDecl();
1953 // Create a call to objc_getProtocol("ProtocolName").
1954 llvm::SmallVector<Expr*, 8> ProtoExprs;
1955 QualType argType = Context->getPointerType(Context->CharTy);
1956 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1957 strlen(Exp->getProtocol()->getName()),
1958 false, argType, SourceLocation(),
1959 SourceLocation()));
1960 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1961 &ProtoExprs[0],
1962 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001963 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1964 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001965 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1966 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001967 SourceRange Range = Exp->getSourceRange();
1968 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001969 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001970 delete Exp;
1971 return ProtoExp;
1972
1973}
1974
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001975/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001976/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001977void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001978 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1980 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001981 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001982 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001983 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001985 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001986 SourceLocation LocStart = CDecl->getLocStart();
1987 SourceLocation LocEnd = CDecl->getLocEnd();
1988
1989 const char *startBuf = SM->getCharacterData(LocStart);
1990 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001991 // If no ivars and no root or if its root, directly or indirectly,
1992 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001994 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1995 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1996 Result.c_str(), Result.size());
1997 return;
1998 }
1999
2000 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002002 Result += "\nstruct ";
2003 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002004
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002005 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002006 const char *cursor = strchr(startBuf, '{');
2007 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002009
2010 // rewrite the original header *without* disturbing the '{'
2011 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2012 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002014 Result = "\n struct ";
2015 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002016 // Note: We don't name the field decl. This simplifies the "codegen" for
2017 // accessing a superclasses instance variables (and is similar to what gcc
2018 // does internally). The unnamed struct field feature is enabled with
2019 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2020 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002021 Result += ";\n";
2022
2023 // insert the super class structure definition.
2024 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2025 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2026 }
2027 cursor++; // past '{'
2028
2029 // Now comment out any visibility specifiers.
2030 while (cursor < endBuf) {
2031 if (*cursor == '@') {
2032 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002033 // Skip whitespace.
2034 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2035 /*scan*/;
2036
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002037 // FIXME: presence of @public, etc. inside comment results in
2038 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002039 if (!strncmp(cursor, "public", strlen("public")) ||
2040 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002041 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00002042 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002043 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002044 // FIXME: If there are cases where '<' is used in ivar declaration part
2045 // of user code, then scan the ivar list and use needToScanForQualifiers
2046 // for type checking.
2047 else if (*cursor == '<') {
2048 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2049 Rewrite.InsertText(atLoc, "/* ", 3);
2050 cursor = strchr(cursor, '>');
2051 cursor++;
2052 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2053 Rewrite.InsertText(atLoc, " */", 3);
2054 }
Steve Narofffea763e82007-11-14 19:25:57 +00002055 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002056 }
Steve Narofffea763e82007-11-14 19:25:57 +00002057 // Don't forget to add a ';'!!
2058 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2059 } else { // we don't have any instance variables - insert super struct.
2060 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2061 Result += " {\n struct ";
2062 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002063 // Note: We don't name the field decl. This simplifies the "codegen" for
2064 // accessing a superclasses instance variables (and is similar to what gcc
2065 // does internally). The unnamed struct field feature is enabled with
2066 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2067 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002068 Result += ";\n};\n";
2069 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2070 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002071 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002072 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 if (!ObjCSynthesizedStructs.insert(CDecl))
2074 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002075}
2076
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002077// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002078/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002080 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002081 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002082 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002083 const char *ClassName,
2084 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002085 if (MethodBegin == MethodEnd) return;
2086
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002087 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002088 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002089 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002090 SEL _cmd;
2091 char *method_types;
2092 void *_imp;
2093 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002094 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002095 Result += "\nstruct _objc_method {\n";
2096 Result += "\tSEL _cmd;\n";
2097 Result += "\tchar *method_types;\n";
2098 Result += "\tvoid *_imp;\n";
2099 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002100
2101 /* struct _objc_method_list {
2102 struct _objc_method_list *next_method;
2103 int method_count;
2104 struct _objc_method method_list[];
2105 }
2106 */
2107 Result += "\nstruct _objc_method_list {\n";
2108 Result += "\tstruct _objc_method_list *next_method;\n";
2109 Result += "\tint method_count;\n";
2110 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002111 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002112 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002113
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002114 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002115 Result += "\nstatic struct _objc_method_list _OBJC_";
2116 Result += prefix;
2117 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2118 Result += "_METHODS_";
2119 Result += ClassName;
2120 Result += " __attribute__ ((section (\"__OBJC, __";
2121 Result += IsInstanceMethod ? "inst" : "cls";
2122 Result += "_meth\")))= ";
2123 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002124
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002125 Result += "\t,{{(SEL)\"";
2126 Result += (*MethodBegin)->getSelector().getName().c_str();
2127 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002128 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002129 Result += "\", \"";
2130 Result += MethodTypeString;
2131 Result += "\", ";
2132 Result += MethodInternalNames[*MethodBegin];
2133 Result += "}\n";
2134 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2135 Result += "\t ,{(SEL)\"";
2136 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002137 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002138 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002139 Result += "\", \"";
2140 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002141 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002142 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002143 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002144 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002145 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002146}
2147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002148/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2149void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002150 int NumProtocols,
2151 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002152 const char *ClassName,
2153 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002154 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002155 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002156 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002157 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002158 // Output struct protocol_methods holder of method selector and type.
2159 if (!objc_protocol_methods &&
2160 (PDecl->getNumInstanceMethods() > 0
2161 || PDecl->getNumClassMethods() > 0)) {
2162 /* struct protocol_methods {
2163 SEL _cmd;
2164 char *method_types;
2165 }
2166 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002167 Result += "\nstruct protocol_methods {\n";
2168 Result += "\tSEL _cmd;\n";
2169 Result += "\tchar *method_types;\n";
2170 Result += "};\n";
2171
2172 /* struct _objc_protocol_method_list {
2173 int protocol_method_count;
2174 struct protocol_methods protocols[];
2175 }
2176 */
2177 Result += "\nstruct _objc_protocol_method_list {\n";
2178 Result += "\tint protocol_method_count;\n";
2179 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002180 objc_protocol_methods = true;
2181 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002182
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002183 int NumMethods = PDecl->getNumInstanceMethods();
2184 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002185 Result += "\nstatic struct _objc_protocol_method_list "
2186 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2187 Result += PDecl->getName();
2188 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2189 "{\n\t" + utostr(NumMethods) + "\n";
2190
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002191 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002192 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002193 E = PDecl->instmeth_end(); I != E; ++I) {
2194 if (I == PDecl->instmeth_begin())
2195 Result += "\t ,{{(SEL)\"";
2196 else
2197 Result += "\t ,{(SEL)\"";
2198 Result += (*I)->getSelector().getName().c_str();
2199 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002200 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002201 Result += "\", \"";
2202 Result += MethodTypeString;
2203 Result += "\"}\n";
2204 }
2205 Result += "\t }\n};\n";
2206 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002207
2208 // Output class methods declared in this protocol.
2209 NumMethods = PDecl->getNumClassMethods();
2210 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002211 Result += "\nstatic struct _objc_protocol_method_list "
2212 "_OBJC_PROTOCOL_CLASS_METHODS_";
2213 Result += PDecl->getName();
2214 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2215 "{\n\t";
2216 Result += utostr(NumMethods);
2217 Result += "\n";
2218
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002219 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002220 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002221 E = PDecl->classmeth_end(); I != E; ++I) {
2222 if (I == PDecl->classmeth_begin())
2223 Result += "\t ,{{(SEL)\"";
2224 else
2225 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002226 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002227 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002228 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002229 Result += "\", \"";
2230 Result += MethodTypeString;
2231 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002232 }
2233 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002234 }
2235 // Output:
2236 /* struct _objc_protocol {
2237 // Objective-C 1.0 extensions
2238 struct _objc_protocol_extension *isa;
2239 char *protocol_name;
2240 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002241 struct _objc_protocol_method_list *instance_methods;
2242 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002243 };
2244 */
2245 static bool objc_protocol = false;
2246 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002247 Result += "\nstruct _objc_protocol {\n";
2248 Result += "\tstruct _objc_protocol_extension *isa;\n";
2249 Result += "\tchar *protocol_name;\n";
2250 Result += "\tstruct _objc_protocol **protocol_list;\n";
2251 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2252 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2253 Result += "};\n";
2254
2255 /* struct _objc_protocol_list {
2256 struct _objc_protocol_list *next;
2257 int protocol_count;
2258 struct _objc_protocol *class_protocols[];
2259 }
2260 */
2261 Result += "\nstruct _objc_protocol_list {\n";
2262 Result += "\tstruct _objc_protocol_list *next;\n";
2263 Result += "\tint protocol_count;\n";
2264 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2265 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002266 objc_protocol = true;
2267 }
2268
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002269 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2270 Result += PDecl->getName();
2271 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2272 "{\n\t0, \"";
2273 Result += PDecl->getName();
2274 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002275 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002276 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2277 Result += PDecl->getName();
2278 Result += ", ";
2279 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002280 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002281 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002282 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002283 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2284 Result += PDecl->getName();
2285 Result += "\n";
2286 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002287 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002288 Result += "0\n";
2289 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002290 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002291 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002292 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2293 Result += prefix;
2294 Result += "_PROTOCOLS_";
2295 Result += ClassName;
2296 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2297 "{\n\t0, ";
2298 Result += utostr(NumProtocols);
2299 Result += "\n";
2300
2301 Result += "\t,{&_OBJC_PROTOCOL_";
2302 Result += Protocols[0]->getName();
2303 Result += " \n";
2304
2305 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002306 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002307 Result += "\t ,&_OBJC_PROTOCOL_";
2308 Result += PDecl->getName();
2309 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002310 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002311 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002312 }
2313}
2314
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002315/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002316/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002317void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002318 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002319 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002320 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002321 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002322 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2323 CDecl = CDecl->getNextClassCategory())
2324 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2325 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002326
Chris Lattnereb44eee2007-12-23 01:40:15 +00002327 std::string FullCategoryName = ClassDecl->getName();
2328 FullCategoryName += '_';
2329 FullCategoryName += IDecl->getName();
2330
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002331 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002332 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002333 true, "CATEGORY_", FullCategoryName.c_str(),
2334 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002335
2336 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002337 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002338 false, "CATEGORY_", FullCategoryName.c_str(),
2339 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002340
2341 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002342 // Null CDecl is case of a category implementation with no category interface
2343 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002344 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002345 CDecl->getNumReferencedProtocols(),
2346 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002347 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002348
2349 /* struct _objc_category {
2350 char *category_name;
2351 char *class_name;
2352 struct _objc_method_list *instance_methods;
2353 struct _objc_method_list *class_methods;
2354 struct _objc_protocol_list *protocols;
2355 // Objective-C 1.0 extensions
2356 uint32_t size; // sizeof (struct _objc_category)
2357 struct _objc_property_list *instance_properties; // category's own
2358 // @property decl.
2359 };
2360 */
2361
2362 static bool objc_category = false;
2363 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002364 Result += "\nstruct _objc_category {\n";
2365 Result += "\tchar *category_name;\n";
2366 Result += "\tchar *class_name;\n";
2367 Result += "\tstruct _objc_method_list *instance_methods;\n";
2368 Result += "\tstruct _objc_method_list *class_methods;\n";
2369 Result += "\tstruct _objc_protocol_list *protocols;\n";
2370 Result += "\tunsigned int size;\n";
2371 Result += "\tstruct _objc_property_list *instance_properties;\n";
2372 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002373 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002374 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002375 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2376 Result += FullCategoryName;
2377 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2378 Result += IDecl->getName();
2379 Result += "\"\n\t, \"";
2380 Result += ClassDecl->getName();
2381 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002382
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383 if (IDecl->getNumInstanceMethods() > 0) {
2384 Result += "\t, (struct _objc_method_list *)"
2385 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2386 Result += FullCategoryName;
2387 Result += "\n";
2388 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002389 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002390 Result += "\t, 0\n";
2391 if (IDecl->getNumClassMethods() > 0) {
2392 Result += "\t, (struct _objc_method_list *)"
2393 "&_OBJC_CATEGORY_CLASS_METHODS_";
2394 Result += FullCategoryName;
2395 Result += "\n";
2396 }
2397 else
2398 Result += "\t, 0\n";
2399
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002400 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002401 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2402 Result += FullCategoryName;
2403 Result += "\n";
2404 }
2405 else
2406 Result += "\t, 0\n";
2407 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002408}
2409
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002410/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2411/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2413 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002414 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002415 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002416 Result += IDecl->getName();
2417 Result += ", ";
2418 Result += ivar->getName();
2419 Result += ")";
2420}
2421
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002422//===----------------------------------------------------------------------===//
2423// Meta Data Emission
2424//===----------------------------------------------------------------------===//
2425
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002426void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002427 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002429
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002430 // Explictly declared @interface's are already synthesized.
2431 if (CDecl->ImplicitInterfaceDecl()) {
2432 // FIXME: Implementation of a class with no @interface (legacy) doese not
2433 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002435 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002436
Chris Lattnerbe6df082007-12-12 07:56:42 +00002437 // Build _objc_ivar_list metadata for classes ivars if needed
2438 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2439 ? IDecl->getImplDeclNumIvars()
2440 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002441 if (NumIvars > 0) {
2442 static bool objc_ivar = false;
2443 if (!objc_ivar) {
2444 /* struct _objc_ivar {
2445 char *ivar_name;
2446 char *ivar_type;
2447 int ivar_offset;
2448 };
2449 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002450 Result += "\nstruct _objc_ivar {\n";
2451 Result += "\tchar *ivar_name;\n";
2452 Result += "\tchar *ivar_type;\n";
2453 Result += "\tint ivar_offset;\n";
2454 Result += "};\n";
2455
2456 /* struct _objc_ivar_list {
2457 int ivar_count;
2458 struct _objc_ivar ivar_list[];
2459 };
2460 */
2461 Result += "\nstruct _objc_ivar_list {\n";
2462 Result += "\tint ivar_count;\n";
2463 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002464 objc_ivar = true;
2465 }
2466
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002467 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2468 Result += IDecl->getName();
2469 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2470 "{\n\t";
2471 Result += utostr(NumIvars);
2472 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002473
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002475 if (IDecl->getImplDeclNumIvars() > 0) {
2476 IVI = IDecl->ivar_begin();
2477 IVE = IDecl->ivar_end();
2478 } else {
2479 IVI = CDecl->ivar_begin();
2480 IVE = CDecl->ivar_end();
2481 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002483 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002484 Result += "\", \"";
2485 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002486 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002487 Result += StrEncoding;
2488 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002489 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002490 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002491 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002492 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002493 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002494 Result += "\", \"";
2495 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002497 Result += StrEncoding;
2498 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002499 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002500 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002501 }
2502
2503 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002504 }
2505
2506 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002508 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002509
2510 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002511 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002512 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002514 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002515 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002516 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002517 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002518
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002519
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002520 // Declaration of class/meta-class metadata
2521 /* struct _objc_class {
2522 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002523 const char *super_class_name;
2524 char *name;
2525 long version;
2526 long info;
2527 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002528 struct _objc_ivar_list *ivars;
2529 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002530 struct objc_cache *cache;
2531 struct objc_protocol_list *protocols;
2532 const char *ivar_layout;
2533 struct _objc_class_ext *ext;
2534 };
2535 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002536 static bool objc_class = false;
2537 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002538 Result += "\nstruct _objc_class {\n";
2539 Result += "\tstruct _objc_class *isa;\n";
2540 Result += "\tconst char *super_class_name;\n";
2541 Result += "\tchar *name;\n";
2542 Result += "\tlong version;\n";
2543 Result += "\tlong info;\n";
2544 Result += "\tlong instance_size;\n";
2545 Result += "\tstruct _objc_ivar_list *ivars;\n";
2546 Result += "\tstruct _objc_method_list *methods;\n";
2547 Result += "\tstruct objc_cache *cache;\n";
2548 Result += "\tstruct _objc_protocol_list *protocols;\n";
2549 Result += "\tconst char *ivar_layout;\n";
2550 Result += "\tstruct _objc_class_ext *ext;\n";
2551 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002552 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002553 }
2554
2555 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 ObjCInterfaceDecl *RootClass = 0;
2557 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002558 while (SuperClass) {
2559 RootClass = SuperClass;
2560 SuperClass = SuperClass->getSuperClass();
2561 }
2562 SuperClass = CDecl->getSuperClass();
2563
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002564 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2565 Result += CDecl->getName();
2566 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2567 "{\n\t(struct _objc_class *)\"";
2568 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2569 Result += "\"";
2570
2571 if (SuperClass) {
2572 Result += ", \"";
2573 Result += SuperClass->getName();
2574 Result += "\", \"";
2575 Result += CDecl->getName();
2576 Result += "\"";
2577 }
2578 else {
2579 Result += ", 0, \"";
2580 Result += CDecl->getName();
2581 Result += "\"";
2582 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002583 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002584 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002585 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002586 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002587 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002588 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002589 Result += "\n";
2590 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002591 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002592 Result += ", 0\n";
2593 if (CDecl->getNumIntfRefProtocols() > 0) {
2594 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2595 Result += CDecl->getName();
2596 Result += ",0,0\n";
2597 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002598 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002599 Result += "\t,0,0,0,0\n";
2600 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002601
2602 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002603 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2604 Result += CDecl->getName();
2605 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2606 "{\n\t&_OBJC_METACLASS_";
2607 Result += CDecl->getName();
2608 if (SuperClass) {
2609 Result += ", \"";
2610 Result += SuperClass->getName();
2611 Result += "\", \"";
2612 Result += CDecl->getName();
2613 Result += "\"";
2614 }
2615 else {
2616 Result += ", 0, \"";
2617 Result += CDecl->getName();
2618 Result += "\"";
2619 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002620 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002621 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002623 Result += ",0";
2624 else {
2625 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002626 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002627 Result += CDecl->getName();
2628 Result += ")";
2629 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002630 if (NumIvars > 0) {
2631 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2632 Result += CDecl->getName();
2633 Result += "\n\t";
2634 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002635 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002636 Result += ",0";
2637 if (IDecl->getNumInstanceMethods() > 0) {
2638 Result += ", &_OBJC_INSTANCE_METHODS_";
2639 Result += CDecl->getName();
2640 Result += ", 0\n\t";
2641 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002642 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002643 Result += ",0,0";
2644 if (CDecl->getNumIntfRefProtocols() > 0) {
2645 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2646 Result += CDecl->getName();
2647 Result += ", 0,0\n";
2648 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002649 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002650 Result += ",0,0,0\n";
2651 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002652}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002653
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002654/// RewriteImplementations - This routine rewrites all method implementations
2655/// and emits meta-data.
2656
2657void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002658 int ClsDefCount = ClassImplementation.size();
2659 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002660
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002661 if (ClsDefCount == 0 && CatDefCount == 0)
2662 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002663 // Rewrite implemented methods
2664 for (int i = 0; i < ClsDefCount; i++)
2665 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002666
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002667 for (int i = 0; i < CatDefCount; i++)
2668 RewriteImplementationDecl(CategoryImplementation[i]);
2669
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002670 // This is needed for use of offsetof
2671 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002672
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002673 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002674 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002675 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002676
2677 // For each implemented category, write out all its meta data.
2678 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002679 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002680
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002681 // Write objc_symtab metadata
2682 /*
2683 struct _objc_symtab
2684 {
2685 long sel_ref_cnt;
2686 SEL *refs;
2687 short cls_def_cnt;
2688 short cat_def_cnt;
2689 void *defs[cls_def_cnt + cat_def_cnt];
2690 };
2691 */
2692
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002693 Result += "\nstruct _objc_symtab {\n";
2694 Result += "\tlong sel_ref_cnt;\n";
2695 Result += "\tSEL *refs;\n";
2696 Result += "\tshort cls_def_cnt;\n";
2697 Result += "\tshort cat_def_cnt;\n";
2698 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2699 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002700
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002701 Result += "static struct _objc_symtab "
2702 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2703 Result += "\t0, 0, " + utostr(ClsDefCount)
2704 + ", " + utostr(CatDefCount) + "\n";
2705 for (int i = 0; i < ClsDefCount; i++) {
2706 Result += "\t,&_OBJC_CLASS_";
2707 Result += ClassImplementation[i]->getName();
2708 Result += "\n";
2709 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002710
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002711 for (int i = 0; i < CatDefCount; i++) {
2712 Result += "\t,&_OBJC_CATEGORY_";
2713 Result += CategoryImplementation[i]->getClassInterface()->getName();
2714 Result += "_";
2715 Result += CategoryImplementation[i]->getName();
2716 Result += "\n";
2717 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002718
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002719 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002720
2721 // Write objc_module metadata
2722
2723 /*
2724 struct _objc_module {
2725 long version;
2726 long size;
2727 const char *name;
2728 struct _objc_symtab *symtab;
2729 }
2730 */
2731
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732 Result += "\nstruct _objc_module {\n";
2733 Result += "\tlong version;\n";
2734 Result += "\tlong size;\n";
2735 Result += "\tconst char *name;\n";
2736 Result += "\tstruct _objc_symtab *symtab;\n";
2737 Result += "};\n\n";
2738 Result += "static struct _objc_module "
2739 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002740 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2741 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002743
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002744}
Chris Lattner311ff022007-10-16 22:36:42 +00002745