blob: eca9349fb689e33316c06bee5cca1864db9c9922 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-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 Jahanian13dad332008-01-15 23:58:23 +000043 llvm::SmallVector<Stmt *, 32> Stmts;
44 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000045 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000046
47 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000048 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000049 FunctionDecl *MsgSendStretFunctionDecl;
50 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000051 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000052 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000053 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000054 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000055 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000056 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000057
Steve Naroff0add5d22007-11-03 11:27:19 +000058 // ObjC string constant support.
59 FileVarDecl *ConstantStringClassReference;
60 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000061
Fariborz Jahanian22277422008-01-16 00:09:11 +000062 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000063 int BcLabelCount;
64
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000066 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000067 RecordDecl *SuperStructDecl;
68
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000069 // Needed for header files being rewritten
70 bool IsHeader;
71
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000072 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000073 public:
Ted Kremenek17861c52007-12-19 22:51:13 +000074 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000075 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000076 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000077 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000079 MsgSendStretFunctionDecl = 0;
80 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000081 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000082 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000083 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000084 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000085 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000086 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000087 ConstantStringClassReference = 0;
88 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000089 CurMethodDecl = 0;
90 SuperStructDecl = 0;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000091 BcLabelCount = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000092
Chris Lattnerae43eb72007-12-02 01:13:47 +000093 // Get the ID and start/end of the main file.
Ted Kremenek17861c52007-12-19 22:51:13 +000094 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +000095 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
96 MainFileStart = MainBuf->getBufferStart();
97 MainFileEnd = MainBuf->getBufferEnd();
98
99
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000100 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +0000101 // declaring objc_selector outside the parameter list removes a silly
102 // scope related warning...
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000103 const char *s = "#pragma once\n"
104 "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000105 "#ifndef OBJC_SUPER\n"
106 "struct objc_super { struct objc_object *o; "
107 "struct objc_object *superClass; };\n"
108 "#define OBJC_SUPER\n"
109 "#endif\n"
110 "#ifndef _REWRITER_typedef_Protocol\n"
111 "typedef struct objc_object Protocol;\n"
112 "#define _REWRITER_typedef_Protocol\n"
113 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000114 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000115 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000116 "extern struct objc_object *objc_msgSendSuper"
117 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000118 "extern struct objc_object *objc_msgSend_stret"
119 "(struct objc_object *, struct objc_selector *, ...);\n"
120 "extern struct objc_object *objc_msgSendSuper_stret"
121 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000122 "extern struct objc_object *objc_msgSend_fpret"
123 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000124 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000125 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000126 "extern struct objc_object *objc_getMetaClass"
127 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000128 "extern void objc_exception_throw(struct objc_object *);\n"
129 "extern void objc_exception_try_enter(void *);\n"
130 "extern void objc_exception_try_exit(void *);\n"
131 "extern struct objc_object *objc_exception_extract(void *);\n"
132 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000133 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000134 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000135 "#include <objc/objc.h>\n"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000136 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000137 "struct __objcFastEnumerationState {\n\t"
138 "unsigned long state;\n\t"
139 "id *itemsPtr;\n\t"
140 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000141 "unsigned long extra[5];\n};\n"
142 "#define __FASTENUMERATIONSTATE\n"
143 "#endif\n";
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000144 if (IsHeader) {
145 // insert the whole string when rewriting a header file
146 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
147 s, strlen(s));
148 }
149 else {
150 // Not rewriting header, exclude the #pragma once pragma
151 const char *p = s + strlen("#pragma once\n");
152 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
153 p, strlen(p));
154 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000155 }
Chris Lattner569faa62007-10-11 18:38:32 +0000156
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000157 // Top Level Driver code.
158 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000159 void HandleDeclInMainFile(Decl *D);
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000160 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {IsHeader = isHeader;}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000161 ~RewriteTest();
162
163 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000164 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000165 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000166 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000167 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
168 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000169 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000170 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
171 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
172 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
173 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
174 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
175 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000176 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000177 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000178 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000179 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000180 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000181
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000182 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000183 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000184 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000185 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000186 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000187 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000188 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000189 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000190 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
191 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
192 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
193 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000194 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000195 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
196 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000197 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000198 Stmt *RewriteBreakStmt(BreakStmt *S);
199 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000200 void SynthCountByEnumWithState(std::string &buf);
201
Steve Naroff02a82aa2007-10-30 23:14:51 +0000202 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000203 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000204 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000205 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000206 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000207 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000208 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000209 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000210 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000211 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000212
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000213 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000214 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000215 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000216
Ted Kremenek42730c52008-01-07 19:49:32 +0000217 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000218 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000219
Ted Kremenek42730c52008-01-07 19:49:32 +0000220 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
221 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000222 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000223 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000224 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000225 const char *ClassName,
226 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000227
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000229 int NumProtocols,
230 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000231 const char *ClassName,
232 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000233 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000234 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000235 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
236 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000237 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000238 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000239 };
240}
241
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000242static bool IsHeaderFile(const std::string &Filename) {
243 std::string::size_type DotPos = Filename.rfind('.');
244
245 if (DotPos == std::string::npos) {
246 // no file extension
247 return false;
248 }
249
250 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
251 // C header: .h
252 // C++ header: .hh or .H;
253 return Ext == "h" || Ext == "hh" || Ext == "H";
254}
255
256ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
257 Diagnostic &Diags) {
258 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattner258f26c2007-11-30 22:25:36 +0000259}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000260
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000261//===----------------------------------------------------------------------===//
262// Top Level Driver Code
263//===----------------------------------------------------------------------===//
264
Chris Lattner569faa62007-10-11 18:38:32 +0000265void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000266 // Two cases: either the decl could be in the main file, or it could be in a
267 // #included file. If the former, rewrite it now. If the later, check to see
268 // if we rewrote the #include/#import.
269 SourceLocation Loc = D->getLocation();
270 Loc = SM->getLogicalLoc(Loc);
271
272 // If this is for a builtin, ignore it.
273 if (Loc.isInvalid()) return;
274
Steve Naroffe9780582007-10-23 23:50:29 +0000275 // Look for built-in declarations that we need to refer during the rewrite.
276 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000277 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000278 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
279 // declared in <Foundation/NSString.h>
280 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
281 ConstantStringClassReference = FVD;
282 return;
283 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000284 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000285 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000286 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000287 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000288 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000289 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000290 } else if (ObjCForwardProtocolDecl *FP =
291 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000292 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000293 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000294 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000295 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
296 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000297}
298
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000299/// HandleDeclInMainFile - This is called for each top-level decl defined in the
300/// main file of the input.
301void RewriteTest::HandleDeclInMainFile(Decl *D) {
302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
303 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000304 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000305
Ted Kremenek42730c52008-01-07 19:49:32 +0000306 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000307 if (Stmt *Body = MD->getBody()) {
308 //Body->dump();
309 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000310 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000311 CurMethodDecl = 0;
312 }
Steve Naroff18c83382007-11-13 23:01:27 +0000313 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000314 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000315 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000316 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000317 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000318 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000319 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000320 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000321 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000322 if (VD->getInit())
323 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
324 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000325 // Nothing yet.
326}
327
328RewriteTest::~RewriteTest() {
329 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000330
331 // Rewrite tabs if we care.
332 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000333
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000334 RewriteInclude();
335
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000336 // Rewrite Objective-c meta data*
337 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000338 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000339
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000340 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
341 // we are done.
342 if (const RewriteBuffer *RewriteBuf =
343 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000344 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000345 std::string S(RewriteBuf->begin(), RewriteBuf->end());
346 printf("%s\n", S.c_str());
347 } else {
348 printf("No changes\n");
349 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000350 // Emit metadata.
351 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000352}
353
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000354//===----------------------------------------------------------------------===//
355// Syntactic (non-AST) Rewriting Code
356//===----------------------------------------------------------------------===//
357
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000358void RewriteTest::RewriteInclude() {
359 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
360 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
361 const char *MainBufStart = MainBuf.first;
362 const char *MainBufEnd = MainBuf.second;
363 size_t ImportLen = strlen("import");
364 size_t IncludeLen = strlen("include");
365
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000366 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000367 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
368 if (*BufPtr == '#') {
369 if (++BufPtr == MainBufEnd)
370 return;
371 while (*BufPtr == ' ' || *BufPtr == '\t')
372 if (++BufPtr == MainBufEnd)
373 return;
374 if (!strncmp(BufPtr, "import", ImportLen)) {
375 // replace import with include
376 SourceLocation ImportLoc =
377 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
378 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
379 BufPtr += ImportLen;
380 }
381 }
382 }
Chris Lattner74db1682007-10-16 21:07:07 +0000383}
384
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000385void RewriteTest::RewriteTabs() {
386 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
387 const char *MainBufStart = MainBuf.first;
388 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000389
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000390 // Loop over the whole file, looking for tabs.
391 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
392 if (*BufPtr != '\t')
393 continue;
394
395 // Okay, we found a tab. This tab will turn into at least one character,
396 // but it depends on which 'virtual column' it is in. Compute that now.
397 unsigned VCol = 0;
398 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
399 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
400 ++VCol;
401
402 // Okay, now that we know the virtual column, we know how many spaces to
403 // insert. We assume 8-character tab-stops.
404 unsigned Spaces = 8-(VCol & 7);
405
406 // Get the location of the tab.
407 SourceLocation TabLoc =
408 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
409
410 // Rewrite the single tab character into a sequence of spaces.
411 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
412 }
Chris Lattner569faa62007-10-11 18:38:32 +0000413}
414
415
Ted Kremenek42730c52008-01-07 19:49:32 +0000416void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000417 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000418 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000419
420 // Get the start location and compute the semi location.
421 SourceLocation startLoc = ClassDecl->getLocation();
422 const char *startBuf = SM->getCharacterData(startLoc);
423 const char *semiPtr = strchr(startBuf, ';');
424
425 // Translate to typedef's that forward reference structs with the same name
426 // as the class. As a convenience, we include the original declaration
427 // as a comment.
428 std::string typedefString;
429 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000430 typedefString.append(startBuf, semiPtr-startBuf+1);
431 typedefString += "\n";
432 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000433 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000434 typedefString += "#ifndef _REWRITER_typedef_";
435 typedefString += ForwardDecl->getName();
436 typedefString += "\n";
437 typedefString += "#define _REWRITER_typedef_";
438 typedefString += ForwardDecl->getName();
439 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000440 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000441 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000442 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000443 }
444
445 // Replace the @class with typedefs corresponding to the classes.
446 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
447 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000448}
449
Ted Kremenek42730c52008-01-07 19:49:32 +0000450void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000451 SourceLocation LocStart = Method->getLocStart();
452 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000453
Steve Naroff2ce399a2007-12-14 23:37:57 +0000454 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
455 Rewrite.InsertText(LocStart, "/* ", 3);
456 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
457 } else {
458 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000459 }
460}
461
Ted Kremenek42730c52008-01-07 19:49:32 +0000462void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000463{
464 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000465 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000466 SourceLocation Loc = Property->getLocation();
467
468 Rewrite.ReplaceText(Loc, 0, "// ", 3);
469
470 // FIXME: handle properties that are declared across multiple lines.
471 }
472}
473
Ted Kremenek42730c52008-01-07 19:49:32 +0000474void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000475 SourceLocation LocStart = CatDecl->getLocStart();
476
477 // FIXME: handle category headers that are declared across multiple lines.
478 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
479
Ted Kremenek42730c52008-01-07 19:49:32 +0000480 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000481 E = CatDecl->instmeth_end(); I != E; ++I)
482 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000483 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000484 E = CatDecl->classmeth_end(); I != E; ++I)
485 RewriteMethodDeclaration(*I);
486
Steve Naroff667f1682007-10-30 13:30:57 +0000487 // Lastly, comment out the @end.
488 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
489}
490
Ted Kremenek42730c52008-01-07 19:49:32 +0000491void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000492 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000493
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000494 SourceLocation LocStart = PDecl->getLocStart();
495
496 // FIXME: handle protocol headers that are declared across multiple lines.
497 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
498
Ted Kremenek42730c52008-01-07 19:49:32 +0000499 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000500 E = PDecl->instmeth_end(); I != E; ++I)
501 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000502 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000503 E = PDecl->classmeth_end(); I != E; ++I)
504 RewriteMethodDeclaration(*I);
505
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000506 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000507 SourceLocation LocEnd = PDecl->getAtEndLoc();
508 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000509
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000510 // Must comment out @optional/@required
511 const char *startBuf = SM->getCharacterData(LocStart);
512 const char *endBuf = SM->getCharacterData(LocEnd);
513 for (const char *p = startBuf; p < endBuf; p++) {
514 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
515 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000516 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000517 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
518 CommentedOptional.c_str(), CommentedOptional.size());
519
520 }
521 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
522 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000523 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000524 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
525 CommentedRequired.c_str(), CommentedRequired.size());
526
527 }
528 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000529}
530
Ted Kremenek42730c52008-01-07 19:49:32 +0000531void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000532 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000533 if (LocStart.isInvalid())
534 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000535 // FIXME: handle forward protocol that are declared across multiple lines.
536 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
537}
538
Ted Kremenek42730c52008-01-07 19:49:32 +0000539void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000540 std::string &ResultStr) {
541 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000542 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000543 ResultStr += "id";
544 else
545 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000546 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000547
548 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000549 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000550
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000551 if (OMD->isInstance())
552 NameStr += "_I_";
553 else
554 NameStr += "_C_";
555
556 NameStr += OMD->getClassInterface()->getName();
557 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000558
559 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000560 if (ObjCCategoryImplDecl *CID =
561 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000562 NameStr += CID->getName();
563 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000564 }
565 // Append selector names, replacing ':' with '_'
566 const char *selName = OMD->getSelector().getName().c_str();
567 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000568 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000569 else {
570 std::string selString = OMD->getSelector().getName();
571 int len = selString.size();
572 for (int i = 0; i < len; i++)
573 if (selString[i] == ':')
574 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000575 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000576 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000577 // Remember this name for metadata emission
578 MethodInternalNames[OMD] = NameStr;
579 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000580
581 // Rewrite arguments
582 ResultStr += "(";
583
584 // invisible arguments
585 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000586 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000587 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000588 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000589 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000590 ResultStr += selfTy.getAsString();
591 }
592 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000593 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000594
595 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000596 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000597 ResultStr += " _cmd";
598
599 // Method arguments.
600 for (int i = 0; i < OMD->getNumParams(); i++) {
601 ParmVarDecl *PDecl = OMD->getParamDecl(i);
602 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000603 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000604 ResultStr += "id";
605 else
606 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000607 ResultStr += " ";
608 ResultStr += PDecl->getName();
609 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000610 if (OMD->isVariadic())
611 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000612 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000613
614}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000615void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000616 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
617 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000618
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000619 if (IMD)
620 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
621 else
622 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000623
Ted Kremenek42730c52008-01-07 19:49:32 +0000624 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000625 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
626 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000627 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000628 ObjCMethodDecl *OMD = *I;
629 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000630 SourceLocation LocStart = OMD->getLocStart();
631 SourceLocation LocEnd = OMD->getBody()->getLocStart();
632
633 const char *startBuf = SM->getCharacterData(LocStart);
634 const char *endBuf = SM->getCharacterData(LocEnd);
635 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
636 ResultStr.c_str(), ResultStr.size());
637 }
638
Ted Kremenek42730c52008-01-07 19:49:32 +0000639 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000640 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
641 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000642 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000643 ObjCMethodDecl *OMD = *I;
644 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000645 SourceLocation LocStart = OMD->getLocStart();
646 SourceLocation LocEnd = OMD->getBody()->getLocStart();
647
648 const char *startBuf = SM->getCharacterData(LocStart);
649 const char *endBuf = SM->getCharacterData(LocEnd);
650 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
651 ResultStr.c_str(), ResultStr.size());
652 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000653 if (IMD)
654 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
655 else
656 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000657}
658
Ted Kremenek42730c52008-01-07 19:49:32 +0000659void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000660 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000661 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000662 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000663 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000664 ResultStr += ClassDecl->getName();
665 ResultStr += "\n";
666 ResultStr += "#define _REWRITER_typedef_";
667 ResultStr += ClassDecl->getName();
668 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000669 ResultStr += "typedef struct ";
670 ResultStr += ClassDecl->getName();
671 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000672 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000673 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000674
675 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000676 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000677 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000678 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000679
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000680 RewriteProperties(ClassDecl->getNumPropertyDecl(),
681 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000682 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000683 E = ClassDecl->instmeth_end(); I != E; ++I)
684 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000685 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000686 E = ClassDecl->classmeth_end(); I != E; ++I)
687 RewriteMethodDeclaration(*I);
688
Steve Naroff1ccf4632007-10-30 03:43:13 +0000689 // Lastly, comment out the @end.
690 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000691}
692
Steve Naroff6b759ce2007-11-15 02:58:25 +0000693Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000694 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000695 if (IV->isFreeIvar()) {
696 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
697 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000698 if (Rewrite.ReplaceStmt(IV, Replacement)) {
699 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000700 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
701 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000702 SourceRange Range = IV->getSourceRange();
703 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000704 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000705 delete IV;
706 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000707 } else {
708 if (CurMethodDecl) {
709 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000710 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000711 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
712 IdentifierInfo *II = intT->getDecl()->getIdentifier();
713 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
714 II, 0);
715 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
716
717 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
718 // Don't forget the parens to enforce the proper binding.
719 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000720 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
721 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000722 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
723 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000724 SourceRange Range = IV->getBase()->getSourceRange();
725 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000726 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000727 delete IV->getBase();
728 return PE;
729 }
730 }
731 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000732 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000733 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000734}
735
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000736//===----------------------------------------------------------------------===//
737// Function Body / Expression rewriting
738//===----------------------------------------------------------------------===//
739
Steve Naroff334fbc22007-11-09 15:20:18 +0000740Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000741 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
742 isa<DoStmt>(S) || isa<ForStmt>(S))
743 Stmts.push_back(S);
744 else if (isa<ObjCForCollectionStmt>(S)) {
745 Stmts.push_back(S);
746 ObjCBcLabelNo.push_back(++BcLabelCount);
747 }
748
Chris Lattner6fe8b272007-10-16 22:36:42 +0000749 // Otherwise, just rewrite all children.
750 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
751 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000752 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000753 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000754 if (newStmt)
755 *CI = newStmt;
756 }
Steve Naroffe9780582007-10-23 23:50:29 +0000757
758 // Handle specific things.
759 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
760 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000761
762 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
763 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000764
765 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
766 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000767
768 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
769 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000770
Steve Naroff71226032007-10-24 22:48:43 +0000771 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
772 // Before we rewrite it, put the original message expression in a comment.
773 SourceLocation startLoc = MessExpr->getLocStart();
774 SourceLocation endLoc = MessExpr->getLocEnd();
775
776 const char *startBuf = SM->getCharacterData(startLoc);
777 const char *endBuf = SM->getCharacterData(endLoc);
778
779 std::string messString;
780 messString += "// ";
781 messString.append(startBuf, endBuf-startBuf+1);
782 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000783
Steve Naroff71226032007-10-24 22:48:43 +0000784 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
785 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
786 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000787 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000788 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000789 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000790
Ted Kremenek42730c52008-01-07 19:49:32 +0000791 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
792 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000793
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
795 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000796
797 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
798 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000799
800 if (ObjCForCollectionStmt *StmtForCollection =
801 dyn_cast<ObjCForCollectionStmt>(S))
802 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000803 if (BreakStmt *StmtBreakStmt =
804 dyn_cast<BreakStmt>(S))
805 return RewriteBreakStmt(StmtBreakStmt);
806 if (ContinueStmt *StmtContinueStmt =
807 dyn_cast<ContinueStmt>(S))
808 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000809
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000810 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
811 isa<DoStmt>(S) || isa<ForStmt>(S)) {
812 assert(!Stmts.empty() && "Statement stack is empty");
813 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
814 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
815 && "Statement stack mismatch");
816 Stmts.pop_back();
817 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000818#if 0
819 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
820 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
821 // Get the new text.
822 std::ostringstream Buf;
823 Replacement->printPretty(Buf);
824 const std::string &Str = Buf.str();
825
826 printf("CAST = %s\n", &Str[0]);
827 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
828 delete S;
829 return Replacement;
830 }
831#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000832 // Return this stmt unmodified.
833 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000834}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000835
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000836/// SynthCountByEnumWithState - To print:
837/// ((unsigned int (*)
838/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
839/// (void *)objc_msgSend)((id)l_collection,
840/// sel_registerName(
841/// "countByEnumeratingWithState:objects:count:"),
842/// &enumState,
843/// (id *)items, (unsigned int)16)
844///
845void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
846 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
847 "id *, unsigned int))(void *)objc_msgSend)";
848 buf += "\n\t\t";
849 buf += "((id)l_collection,\n\t\t";
850 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
851 buf += "\n\t\t";
852 buf += "&enumState, "
853 "(id *)items, (unsigned int)16)";
854}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000855
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000856/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
857/// statement to exit to its outer synthesized loop.
858///
859Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
860 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
861 return S;
862 // replace break with goto __break_label
863 std::string buf;
864
865 SourceLocation startLoc = S->getLocStart();
866 buf = "goto __break_label_";
867 buf += utostr(ObjCBcLabelNo.back());
868 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
869
870 return 0;
871}
872
873/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
874/// statement to continue with its inner synthesized loop.
875///
876Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
877 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
878 return S;
879 // replace continue with goto __continue_label
880 std::string buf;
881
882 SourceLocation startLoc = S->getLocStart();
883 buf = "goto __continue_label_";
884 buf += utostr(ObjCBcLabelNo.back());
885 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
886
887 return 0;
888}
889
Fariborz Jahanian72cf3b52008-01-09 01:25:54 +0000890/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000891/// It rewrites:
892/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000893
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000894/// Into:
895/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000896/// type elem;
897/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000898/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000899/// id l_collection = (id)collection;
900/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
901/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000902/// if (limit) {
903/// unsigned long startMutations = *enumState.mutationsPtr;
904/// do {
905/// unsigned long counter = 0;
906/// do {
907/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000908/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000909/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000910/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000911/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000912/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000913/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
914/// objects:items count:16]);
915/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000916/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000917/// }
918/// else
919/// elem = nil;
920/// }
921///
922Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000923 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
924 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
925 "ObjCForCollectionStmt Statement stack mismatch");
926 assert(!ObjCBcLabelNo.empty() &&
927 "ObjCForCollectionStmt - Label No stack empty");
928
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000929 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000930 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000931 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000932 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000933 std::string buf;
934 buf = "\n{\n\t";
935 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
936 // type elem;
937 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000938 elementTypeAsString = ElementType.getAsString();
939 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000940 buf += " ";
941 elementName = DS->getDecl()->getName();
942 buf += elementName;
943 buf += ";\n\t";
944 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000945 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000946 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000947 elementTypeAsString = DR->getDecl()->getType().getAsString();
948 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000949 else
950 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
951
952 // struct __objcFastEnumerationState enumState = { 0 };
953 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
954 // id items[16];
955 buf += "id items[16];\n\t";
956 // id l_collection = (id)
957 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000958 // Find start location of 'collection' the hard way!
959 const char *startCollectionBuf = startBuf;
960 startCollectionBuf += 3; // skip 'for'
961 startCollectionBuf = strchr(startCollectionBuf, '(');
962 startCollectionBuf++; // skip '('
963 // find 'in' and skip it.
964 while (*startCollectionBuf != ' ' ||
965 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
966 (*(startCollectionBuf+3) != ' ' &&
967 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
968 startCollectionBuf++;
969 startCollectionBuf += 3;
970
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000971 // Replace: "for (type element in" with string constructed thus far.
972 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
973 buf.c_str(), buf.size());
974 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000975 SourceLocation rightParenLoc = S->getRParenLoc();
976 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
977 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000978 buf = ";\n\t";
979
980 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
981 // objects:items count:16];
982 // which is synthesized into:
983 // unsigned int limit =
984 // ((unsigned int (*)
985 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
986 // (void *)objc_msgSend)((id)l_collection,
987 // sel_registerName(
988 // "countByEnumeratingWithState:objects:count:"),
989 // (struct __objcFastEnumerationState *)&state,
990 // (id *)items, (unsigned int)16);
991 buf += "unsigned long limit =\n\t\t";
992 SynthCountByEnumWithState(buf);
993 buf += ";\n\t";
994 /// if (limit) {
995 /// unsigned long startMutations = *enumState.mutationsPtr;
996 /// do {
997 /// unsigned long counter = 0;
998 /// do {
999 /// if (startMutations != *enumState.mutationsPtr)
1000 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001001 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001002 buf += "if (limit) {\n\t";
1003 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1004 buf += "do {\n\t\t";
1005 buf += "unsigned long counter = 0;\n\t\t";
1006 buf += "do {\n\t\t\t";
1007 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1008 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1009 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001010 buf += " = (";
1011 buf += elementTypeAsString;
1012 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001013 // Replace ')' in for '(' type elem in collection ')' with all of these.
1014 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1015
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001016 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001017 /// } while (counter < limit);
1018 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1019 /// objects:items count:16]);
1020 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001021 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001022 /// }
1023 /// else
1024 /// elem = nil;
1025 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001026 ///
1027 buf = ";\n\t";
1028 buf += "__continue_label_";
1029 buf += utostr(ObjCBcLabelNo.back());
1030 buf += ": ;";
1031 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001032 buf += "} while (counter < limit);\n\t";
1033 buf += "} while (limit = ";
1034 SynthCountByEnumWithState(buf);
1035 buf += ");\n\t";
1036 buf += elementName;
1037 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001038 buf += "__break_label_";
1039 buf += utostr(ObjCBcLabelNo.back());
1040 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001041 buf += "}\n\t";
1042 buf += "else\n\t\t";
1043 buf += elementName;
1044 buf += " = nil;\n";
1045 buf += "}\n";
1046 // Insert all these *after* the statement body.
1047 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1048 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1049 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1050 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001051 Stmts.pop_back();
1052 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001053
1054 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001055}
1056
Ted Kremenek42730c52008-01-07 19:49:32 +00001057Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001058 // Get the start location and compute the semi location.
1059 SourceLocation startLoc = S->getLocStart();
1060 const char *startBuf = SM->getCharacterData(startLoc);
1061
1062 assert((*startBuf == '@') && "bogus @try location");
1063
1064 std::string buf;
1065 // declare a new scope with two variables, _stack and _rethrow.
1066 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1067 buf += "int buf[18/*32-bit i386*/];\n";
1068 buf += "char *pointers[4];} _stack;\n";
1069 buf += "id volatile _rethrow = 0;\n";
1070 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001071 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001072
1073 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1074
1075 startLoc = S->getTryBody()->getLocEnd();
1076 startBuf = SM->getCharacterData(startLoc);
1077
1078 assert((*startBuf == '}') && "bogus @try block");
1079
1080 SourceLocation lastCurlyLoc = startLoc;
1081
1082 startLoc = startLoc.getFileLocWithOffset(1);
1083 buf = " /* @catch begin */ else {\n";
1084 buf += " id _caught = objc_exception_extract(&_stack);\n";
1085 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001086 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001087 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1088 buf += " else { /* @catch continue */";
1089
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001090 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001091
1092 bool sawIdTypedCatch = false;
1093 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001094 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001095 while (catchList) {
1096 Stmt *catchStmt = catchList->getCatchParamStmt();
1097
1098 if (catchList == S->getCatchStmts())
1099 buf = "if ("; // we are generating code for the first catch clause
1100 else
1101 buf = "else if (";
1102 startLoc = catchList->getLocStart();
1103 startBuf = SM->getCharacterData(startLoc);
1104
1105 assert((*startBuf == '@') && "bogus @catch location");
1106
1107 const char *lParenLoc = strchr(startBuf, '(');
1108
1109 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1110 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001111 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001112 buf += "1) { ";
1113 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1114 buf.c_str(), buf.size());
1115 sawIdTypedCatch = true;
1116 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001117 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001118
Ted Kremenek42730c52008-01-07 19:49:32 +00001119 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001120 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001121 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001122 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001123 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +00001124 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1125 buf.c_str(), buf.size());
1126 }
1127 }
1128 // Now rewrite the body...
1129 lastCatchBody = catchList->getCatchBody();
1130 SourceLocation rParenLoc = catchList->getRParenLoc();
1131 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1132 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1133 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1134 assert((*rParenBuf == ')') && "bogus @catch paren location");
1135 assert((*bodyBuf == '{') && "bogus @catch body location");
1136
1137 buf = " = _caught;";
1138 // Here we replace ") {" with "= _caught;" (which initializes and
1139 // declares the @catch parameter).
1140 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1141 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001142 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001143 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001144 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001145 catchList = catchList->getNextCatchStmt();
1146 }
1147 // Complete the catch list...
1148 if (lastCatchBody) {
1149 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1150 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1151 assert((*bodyBuf == '}') && "bogus @catch body location");
1152 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1153 buf = " } } /* @catch end */\n";
1154
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001155 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001156
1157 // Set lastCurlyLoc
1158 lastCurlyLoc = lastCatchBody->getLocEnd();
1159 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001160 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001161 startLoc = finalStmt->getLocStart();
1162 startBuf = SM->getCharacterData(startLoc);
1163 assert((*startBuf == '@') && "bogus @finally start");
1164
1165 buf = "/* @finally */";
1166 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1167
1168 Stmt *body = finalStmt->getFinallyBody();
1169 SourceLocation startLoc = body->getLocStart();
1170 SourceLocation endLoc = body->getLocEnd();
1171 const char *startBuf = SM->getCharacterData(startLoc);
1172 const char *endBuf = SM->getCharacterData(endLoc);
1173 assert((*startBuf == '{') && "bogus @finally body location");
1174 assert((*endBuf == '}') && "bogus @finally body location");
1175
1176 startLoc = startLoc.getFileLocWithOffset(1);
1177 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001178 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001179 endLoc = endLoc.getFileLocWithOffset(-1);
1180 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001181 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001182
1183 // Set lastCurlyLoc
1184 lastCurlyLoc = body->getLocEnd();
1185 }
1186 // Now emit the final closing curly brace...
1187 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1188 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001189 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001190 return 0;
1191}
1192
Ted Kremenek42730c52008-01-07 19:49:32 +00001193Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001194 return 0;
1195}
1196
Ted Kremenek42730c52008-01-07 19:49:32 +00001197Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001198 return 0;
1199}
1200
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001201// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1202// the throw expression is typically a message expression that's already
1203// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001204Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001205 // Get the start location and compute the semi location.
1206 SourceLocation startLoc = S->getLocStart();
1207 const char *startBuf = SM->getCharacterData(startLoc);
1208
1209 assert((*startBuf == '@') && "bogus @throw location");
1210
1211 std::string buf;
1212 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001213 if (S->getThrowExpr())
1214 buf = "objc_exception_throw(";
1215 else // add an implicit argument
1216 buf = "objc_exception_throw(_caught";
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001217 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1218 const char *semiBuf = strchr(startBuf, ';');
1219 assert((*semiBuf == ';') && "@throw: can't find ';'");
1220 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1221 buf = ");";
1222 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1223 return 0;
1224}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001225
Chris Lattner0021f452007-10-24 16:57:36 +00001226Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001227 // Create a new string expression.
1228 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001229 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001230 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1231 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001232 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1233 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001234 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +00001235 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1236 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001237 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1238 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner217df512007-12-02 01:09:57 +00001239 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001240 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +00001241 }
1242
Chris Lattner4478db92007-11-30 22:53:43 +00001243 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001244 delete Exp;
1245 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001246}
1247
Steve Naroff296b74f2007-11-05 14:50:49 +00001248Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1249 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1250 // Create a call to sel_registerName("selName").
1251 llvm::SmallVector<Expr*, 8> SelExprs;
1252 QualType argType = Context->getPointerType(Context->CharTy);
1253 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1254 Exp->getSelector().getName().size(),
1255 false, argType, SourceLocation(),
1256 SourceLocation()));
1257 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1258 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001259 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1260 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001261 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1262 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001263 SourceRange Range = Exp->getSourceRange();
1264 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001265 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001266 delete Exp;
1267 return SelExp;
1268}
1269
Steve Naroff71226032007-10-24 22:48:43 +00001270CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1271 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001272 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001273 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001274
1275 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001276 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001277
1278 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001279 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001280 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1281
1282 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001283
Steve Naroff71226032007-10-24 22:48:43 +00001284 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1285}
1286
Steve Naroffc8a92d12007-11-01 13:24:47 +00001287static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1288 const char *&startRef, const char *&endRef) {
1289 while (startBuf < endBuf) {
1290 if (*startBuf == '<')
1291 startRef = startBuf; // mark the start.
1292 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001293 if (startRef && *startRef == '<') {
1294 endRef = startBuf; // mark the end.
1295 return true;
1296 }
1297 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001298 }
1299 startBuf++;
1300 }
1301 return false;
1302}
1303
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001304static void scanToNextArgument(const char *&argRef) {
1305 int angle = 0;
1306 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1307 if (*argRef == '<')
1308 angle++;
1309 else if (*argRef == '>')
1310 angle--;
1311 argRef++;
1312 }
1313 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1314}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001315
Steve Naroffc8a92d12007-11-01 13:24:47 +00001316bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001317
Ted Kremenek42730c52008-01-07 19:49:32 +00001318 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001319 return true;
1320
Ted Kremenek42730c52008-01-07 19:49:32 +00001321 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001322 return true;
1323
Steve Naroffc8a92d12007-11-01 13:24:47 +00001324 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001325 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001326 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001327 return true; // we have "Class <Protocol> *".
1328 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001329 return false;
1330}
1331
Ted Kremenek42730c52008-01-07 19:49:32 +00001332void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001333 SourceLocation Loc;
1334 QualType Type;
1335 const FunctionTypeProto *proto = 0;
1336 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1337 Loc = VD->getLocation();
1338 Type = VD->getType();
1339 }
1340 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1341 Loc = FD->getLocation();
1342 // Check for ObjC 'id' and class types that have been adorned with protocol
1343 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1344 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1345 assert(funcType && "missing function type");
1346 proto = dyn_cast<FunctionTypeProto>(funcType);
1347 if (!proto)
1348 return;
1349 Type = proto->getResultType();
1350 }
1351 else
1352 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001353
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001354 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001355 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001356
1357 const char *endBuf = SM->getCharacterData(Loc);
1358 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001359 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001360 startBuf--; // scan backward (from the decl location) for return type.
1361 const char *startRef = 0, *endRef = 0;
1362 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1363 // Get the locations of the startRef, endRef.
1364 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1365 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1366 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001367 Rewrite.InsertText(LessLoc, "/*", 2);
1368 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001369 }
1370 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001371 if (!proto)
1372 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001373 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001374 const char *startBuf = SM->getCharacterData(Loc);
1375 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001376 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1377 if (needToScanForQualifiers(proto->getArgType(i))) {
1378 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001379
Steve Naroffc8a92d12007-11-01 13:24:47 +00001380 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001381 // scan forward (from the decl location) for argument types.
1382 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001383 const char *startRef = 0, *endRef = 0;
1384 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1385 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001386 SourceLocation LessLoc =
1387 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1388 SourceLocation GreaterLoc =
1389 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001390 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001391 Rewrite.InsertText(LessLoc, "/*", 2);
1392 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001393 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001394 startBuf = ++endBuf;
1395 }
1396 else {
1397 while (*startBuf != ')' && *startBuf != ',')
1398 startBuf++; // scan forward (from the decl location) for argument types.
1399 startBuf++;
1400 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001401 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001402}
1403
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001404// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1405void RewriteTest::SynthSelGetUidFunctionDecl() {
1406 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1407 llvm::SmallVector<QualType, 16> ArgTys;
1408 ArgTys.push_back(Context->getPointerType(
1409 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001410 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001411 &ArgTys[0], ArgTys.size(),
1412 false /*isVariadic*/);
1413 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1414 SelGetUidIdent, getFuncType,
1415 FunctionDecl::Extern, false, 0);
1416}
1417
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001418// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1419void RewriteTest::SynthGetProtocolFunctionDecl() {
1420 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1421 llvm::SmallVector<QualType, 16> ArgTys;
1422 ArgTys.push_back(Context->getPointerType(
1423 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001424 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001425 &ArgTys[0], ArgTys.size(),
1426 false /*isVariadic*/);
1427 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1428 SelGetProtoIdent, getFuncType,
1429 FunctionDecl::Extern, false, 0);
1430}
1431
Steve Naroff02a82aa2007-10-30 23:14:51 +00001432void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1433 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001434 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001435 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001436 return;
1437 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001438 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001439}
1440
1441// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1442void RewriteTest::SynthMsgSendFunctionDecl() {
1443 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1444 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001445 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001446 assert(!argT.isNull() && "Can't find 'id' type");
1447 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001448 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001449 assert(!argT.isNull() && "Can't find 'SEL' type");
1450 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001451 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001452 &ArgTys[0], ArgTys.size(),
1453 true /*isVariadic*/);
1454 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1455 msgSendIdent, msgSendType,
1456 FunctionDecl::Extern, false, 0);
1457}
1458
Steve Naroff764c1ae2007-11-15 10:28:18 +00001459// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1460void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1461 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1462 llvm::SmallVector<QualType, 16> ArgTys;
1463 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1464 &Context->Idents.get("objc_super"), 0);
1465 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1466 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1467 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001468 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001469 assert(!argT.isNull() && "Can't find 'SEL' type");
1470 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001471 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001472 &ArgTys[0], ArgTys.size(),
1473 true /*isVariadic*/);
1474 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1475 msgSendIdent, msgSendType,
1476 FunctionDecl::Extern, false, 0);
1477}
1478
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001479// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1480void RewriteTest::SynthMsgSendStretFunctionDecl() {
1481 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1482 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001483 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001484 assert(!argT.isNull() && "Can't find 'id' type");
1485 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001486 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001487 assert(!argT.isNull() && "Can't find 'SEL' type");
1488 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001489 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001490 &ArgTys[0], ArgTys.size(),
1491 true /*isVariadic*/);
1492 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1493 msgSendIdent, msgSendType,
1494 FunctionDecl::Extern, false, 0);
1495}
1496
1497// SynthMsgSendSuperStretFunctionDecl -
1498// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1499void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1500 IdentifierInfo *msgSendIdent =
1501 &Context->Idents.get("objc_msgSendSuper_stret");
1502 llvm::SmallVector<QualType, 16> ArgTys;
1503 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1504 &Context->Idents.get("objc_super"), 0);
1505 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1506 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1507 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001508 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001509 assert(!argT.isNull() && "Can't find 'SEL' type");
1510 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001511 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001512 &ArgTys[0], ArgTys.size(),
1513 true /*isVariadic*/);
1514 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1515 msgSendIdent, msgSendType,
1516 FunctionDecl::Extern, false, 0);
1517}
1518
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001519// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1520void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1521 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1522 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001523 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001524 assert(!argT.isNull() && "Can't find 'id' type");
1525 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001526 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001527 assert(!argT.isNull() && "Can't find 'SEL' type");
1528 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001529 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001530 &ArgTys[0], ArgTys.size(),
1531 true /*isVariadic*/);
1532 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1533 msgSendIdent, msgSendType,
1534 FunctionDecl::Extern, false, 0);
1535}
1536
Steve Naroff02a82aa2007-10-30 23:14:51 +00001537// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1538void RewriteTest::SynthGetClassFunctionDecl() {
1539 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1540 llvm::SmallVector<QualType, 16> ArgTys;
1541 ArgTys.push_back(Context->getPointerType(
1542 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001543 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001544 &ArgTys[0], ArgTys.size(),
1545 false /*isVariadic*/);
1546 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1547 getClassIdent, getClassType,
1548 FunctionDecl::Extern, false, 0);
1549}
1550
Steve Naroff3b1caac2007-12-07 03:50:46 +00001551// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1552void RewriteTest::SynthGetMetaClassFunctionDecl() {
1553 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1554 llvm::SmallVector<QualType, 16> ArgTys;
1555 ArgTys.push_back(Context->getPointerType(
1556 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001557 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001558 &ArgTys[0], ArgTys.size(),
1559 false /*isVariadic*/);
1560 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1561 getClassIdent, getClassType,
1562 FunctionDecl::Extern, false, 0);
1563}
1564
Steve Naroffabb96362007-11-08 14:30:50 +00001565// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1566void RewriteTest::SynthCFStringFunctionDecl() {
1567 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1568 llvm::SmallVector<QualType, 16> ArgTys;
1569 ArgTys.push_back(Context->getPointerType(
1570 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001571 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001572 &ArgTys[0], ArgTys.size(),
1573 false /*isVariadic*/);
1574 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1575 getClassIdent, getClassType,
1576 FunctionDecl::Extern, false, 0);
1577}
1578
Steve Naroff0add5d22007-11-03 11:27:19 +00001579Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001580#if 1
1581 // This rewrite is specific to GCC, which has builtin support for CFString.
1582 if (!CFStringFunctionDecl)
1583 SynthCFStringFunctionDecl();
1584 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1585 llvm::SmallVector<Expr*, 8> StrExpr;
1586 StrExpr.push_back(Exp->getString());
1587 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1588 &StrExpr[0], StrExpr.size());
1589 // cast to NSConstantString *
1590 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001591 if (Rewrite.ReplaceStmt(Exp, cast)) {
1592 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001593 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1594 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001595 SourceRange Range = Exp->getSourceRange();
1596 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001597 }
Steve Naroffabb96362007-11-08 14:30:50 +00001598 delete Exp;
1599 return cast;
1600#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001601 assert(ConstantStringClassReference && "Can't find constant string reference");
1602 llvm::SmallVector<Expr*, 4> InitExprs;
1603
1604 // Synthesize "(Class)&_NSConstantStringClassReference"
1605 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1606 ConstantStringClassReference->getType(),
1607 SourceLocation());
1608 QualType expType = Context->getPointerType(ClsRef->getType());
1609 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1610 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001611 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001612 SourceLocation());
1613 InitExprs.push_back(cast); // set the 'isa'.
1614 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1615 unsigned IntSize = static_cast<unsigned>(
1616 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1617 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1618 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1619 Exp->getLocStart());
1620 InitExprs.push_back(len); // set "int numBytes".
1621
1622 // struct NSConstantString
1623 QualType CFConstantStrType = Context->getCFConstantStringType();
1624 // (struct NSConstantString) { <exprs from above> }
1625 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1626 &InitExprs[0], InitExprs.size(),
1627 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001628 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001629 // struct NSConstantString *
1630 expType = Context->getPointerType(StrRep->getType());
1631 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1632 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001633 // cast to NSConstantString *
1634 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001635 Rewrite.ReplaceStmt(Exp, cast);
1636 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001637 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001638#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001639}
1640
Ted Kremenek42730c52008-01-07 19:49:32 +00001641ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001642 // check if we are sending a message to 'super'
1643 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001644 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1645 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1646 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1647 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001648 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001649 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001650 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001651 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001652 if (ObjCInterfaceType *IT =
1653 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001654 if (IT->getDecl() ==
1655 CurMethodDecl->getClassInterface()->getSuperClass())
1656 return IT->getDecl();
1657 }
1658 }
1659 }
1660 }
1661 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001662 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001663 }
1664 return 0;
1665}
1666
1667// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1668QualType RewriteTest::getSuperStructType() {
1669 if (!SuperStructDecl) {
1670 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1671 &Context->Idents.get("objc_super"), 0);
1672 QualType FieldTypes[2];
1673
1674 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001675 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001676 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001677 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001678 // Create fields
1679 FieldDecl *FieldDecls[2];
1680
1681 for (unsigned i = 0; i < 2; ++i)
1682 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1683
1684 SuperStructDecl->defineBody(FieldDecls, 4);
1685 }
1686 return Context->getTagDeclType(SuperStructDecl);
1687}
1688
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001689Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001690 if (!SelGetUidFunctionDecl)
1691 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001692 if (!MsgSendFunctionDecl)
1693 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001694 if (!MsgSendSuperFunctionDecl)
1695 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001696 if (!MsgSendStretFunctionDecl)
1697 SynthMsgSendStretFunctionDecl();
1698 if (!MsgSendSuperStretFunctionDecl)
1699 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001700 if (!MsgSendFpretFunctionDecl)
1701 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001702 if (!GetClassFunctionDecl)
1703 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001704 if (!GetMetaClassFunctionDecl)
1705 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001706
Steve Naroff764c1ae2007-11-15 10:28:18 +00001707 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001708 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1709 // May need to use objc_msgSend_stret() as well.
1710 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001711 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001712 QualType resultType = mDecl->getResultType();
1713 if (resultType.getCanonicalType()->isStructureType()
1714 || resultType.getCanonicalType()->isUnionType())
1715 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001716 else if (resultType.getCanonicalType()->isRealFloatingType())
1717 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001718 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001719
Steve Naroff71226032007-10-24 22:48:43 +00001720 // Synthesize a call to objc_msgSend().
1721 llvm::SmallVector<Expr*, 8> MsgExprs;
1722 IdentifierInfo *clsName = Exp->getClassName();
1723
1724 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1725 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001726 if (!strcmp(clsName->getName(), "super")) {
1727 MsgSendFlavor = MsgSendSuperFunctionDecl;
1728 if (MsgSendStretFlavor)
1729 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1730 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1731
Ted Kremenek42730c52008-01-07 19:49:32 +00001732 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001733 CurMethodDecl->getClassInterface()->getSuperClass();
1734
1735 llvm::SmallVector<Expr*, 4> InitExprs;
1736
1737 // set the receiver to self, the first argument to all methods.
1738 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001739 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001740 SourceLocation()));
1741 llvm::SmallVector<Expr*, 8> ClsExprs;
1742 QualType argType = Context->getPointerType(Context->CharTy);
1743 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1744 SuperDecl->getIdentifier()->getLength(),
1745 false, argType, SourceLocation(),
1746 SourceLocation()));
1747 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1748 &ClsExprs[0],
1749 ClsExprs.size());
1750 // To turn off a warning, type-cast to 'id'
1751 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001752 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001753 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1754 // struct objc_super
1755 QualType superType = getSuperStructType();
1756 // (struct objc_super) { <exprs from above> }
1757 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1758 &InitExprs[0], InitExprs.size(),
1759 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001760 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001761 superType, ILE, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001762 // struct objc_super *
1763 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1764 Context->getPointerType(SuperRep->getType()),
1765 SourceLocation());
1766 MsgExprs.push_back(Unop);
1767 } else {
1768 llvm::SmallVector<Expr*, 8> ClsExprs;
1769 QualType argType = Context->getPointerType(Context->CharTy);
1770 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1771 clsName->getLength(),
1772 false, argType, SourceLocation(),
1773 SourceLocation()));
1774 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1775 &ClsExprs[0],
1776 ClsExprs.size());
1777 MsgExprs.push_back(Cls);
1778 }
Steve Naroff885e2122007-11-14 23:54:14 +00001779 } else { // instance message.
1780 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001781
Ted Kremenek42730c52008-01-07 19:49:32 +00001782 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001783 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001784 if (MsgSendStretFlavor)
1785 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001786 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1787
1788 llvm::SmallVector<Expr*, 4> InitExprs;
1789
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001790 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001791 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001792 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001793
1794 llvm::SmallVector<Expr*, 8> ClsExprs;
1795 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001796 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1797 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001798 false, argType, SourceLocation(),
1799 SourceLocation()));
1800 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001801 &ClsExprs[0],
1802 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001803 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001804 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001805 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001806 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001807 // struct objc_super
1808 QualType superType = getSuperStructType();
1809 // (struct objc_super) { <exprs from above> }
1810 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1811 &InitExprs[0], InitExprs.size(),
1812 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001813 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001814 superType, ILE, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001815 // struct objc_super *
1816 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1817 Context->getPointerType(SuperRep->getType()),
1818 SourceLocation());
1819 MsgExprs.push_back(Unop);
1820 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001821 // Remove all type-casts because it may contain objc-style types; e.g.
1822 // Foo<Proto> *.
1823 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1824 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001825 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001826 MsgExprs.push_back(recExpr);
1827 }
Steve Naroff885e2122007-11-14 23:54:14 +00001828 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001829 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001830 llvm::SmallVector<Expr*, 8> SelExprs;
1831 QualType argType = Context->getPointerType(Context->CharTy);
1832 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1833 Exp->getSelector().getName().size(),
1834 false, argType, SourceLocation(),
1835 SourceLocation()));
1836 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1837 &SelExprs[0], SelExprs.size());
1838 MsgExprs.push_back(SelExp);
1839
1840 // Now push any user supplied arguments.
1841 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001842 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001843 // Make all implicit casts explicit...ICE comes in handy:-)
1844 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1845 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001846 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1847 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001848 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001849 }
1850 // Make id<P...> cast into an 'id' cast.
1851 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001852 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001853 while ((CE = dyn_cast<CastExpr>(userExpr)))
1854 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001855 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001856 userExpr, SourceLocation());
1857 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001858 }
Steve Naroff885e2122007-11-14 23:54:14 +00001859 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001860 // We've transferred the ownership to MsgExprs. Null out the argument in
1861 // the original expression, since we will delete it below.
1862 Exp->setArg(i, 0);
1863 }
Steve Naroff0744c472007-11-04 22:37:50 +00001864 // Generate the funky cast.
1865 CastExpr *cast;
1866 llvm::SmallVector<QualType, 8> ArgTypes;
1867 QualType returnType;
1868
1869 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001870 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1871 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1872 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001873 ArgTypes.push_back(Context->getObjCIdType());
1874 ArgTypes.push_back(Context->getObjCSelType());
1875 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001876 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001877 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001878 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1879 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001880 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001881 ArgTypes.push_back(t);
1882 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001883 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1884 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001885 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001886 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001887 }
1888 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001889 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001890
1891 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001892 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1893 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001894
1895 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1896 // If we don't do this cast, we get the following bizarre warning/note:
1897 // xx.m:13: warning: function called through a non-compatible type
1898 // xx.m:13: note: if this code is reached, the program will abort
1899 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1900 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001901
Steve Naroff0744c472007-11-04 22:37:50 +00001902 // Now do the "normal" pointer to function cast.
1903 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001904 &ArgTypes[0], ArgTypes.size(),
1905 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001906 castType = Context->getPointerType(castType);
1907 cast = new CastExpr(castType, cast, SourceLocation());
1908
1909 // Don't forget the parens to enforce the proper binding.
1910 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1911
1912 const FunctionType *FT = msgSendType->getAsFunctionType();
1913 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1914 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001915 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001916 if (MsgSendStretFlavor) {
1917 // We have the method which returns a struct/union. Must also generate
1918 // call to objc_msgSend_stret and hang both varieties on a conditional
1919 // expression which dictate which one to envoke depending on size of
1920 // method's return type.
1921
1922 // Create a reference to the objc_msgSend_stret() declaration.
1923 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1924 SourceLocation());
1925 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1926 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1927 SourceLocation());
1928 // Now do the "normal" pointer to function cast.
1929 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001930 &ArgTypes[0], ArgTypes.size(),
1931 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001932 castType = Context->getPointerType(castType);
1933 cast = new CastExpr(castType, cast, SourceLocation());
1934
1935 // Don't forget the parens to enforce the proper binding.
1936 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1937
1938 FT = msgSendType->getAsFunctionType();
1939 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1940 FT->getResultType(), SourceLocation());
1941
1942 // Build sizeof(returnType)
1943 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1944 returnType, Context->getSizeType(),
1945 SourceLocation(), SourceLocation());
1946 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1947 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1948 // For X86 it is more complicated and some kind of target specific routine
1949 // is needed to decide what to do.
1950 unsigned IntSize = static_cast<unsigned>(
1951 Context->getTypeSize(Context->IntTy, SourceLocation()));
1952
1953 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1954 Context->IntTy,
1955 SourceLocation());
1956 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1957 BinaryOperator::LE,
1958 Context->IntTy,
1959 SourceLocation());
1960 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1961 ConditionalOperator *CondExpr =
1962 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001963 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001964 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001965 return ReplacingStmt;
1966}
1967
1968Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1969 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00001970 // Now do the actual rewrite.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001971 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroffe4e5e262007-12-19 14:32:56 +00001972 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001973 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1974 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001975 SourceRange Range = Exp->getSourceRange();
1976 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001977 }
Steve Naroff71226032007-10-24 22:48:43 +00001978
Chris Lattner0021f452007-10-24 16:57:36 +00001979 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001980 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00001981}
1982
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001983/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1984/// call to objc_getProtocol("proto-name").
1985Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1986 if (!GetProtocolFunctionDecl)
1987 SynthGetProtocolFunctionDecl();
1988 // Create a call to objc_getProtocol("ProtocolName").
1989 llvm::SmallVector<Expr*, 8> ProtoExprs;
1990 QualType argType = Context->getPointerType(Context->CharTy);
1991 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1992 strlen(Exp->getProtocol()->getName()),
1993 false, argType, SourceLocation(),
1994 SourceLocation()));
1995 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1996 &ProtoExprs[0],
1997 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001998 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1999 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00002000 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
2001 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00002002 SourceRange Range = Exp->getSourceRange();
2003 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002004 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002005 delete Exp;
2006 return ProtoExp;
2007
2008}
2009
Ted Kremenek42730c52008-01-07 19:49:32 +00002010/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002011/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002012void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002013 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2015 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002016 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002017 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002018 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002019 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002020 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002021 SourceLocation LocStart = CDecl->getLocStart();
2022 SourceLocation LocEnd = CDecl->getLocEnd();
2023
2024 const char *startBuf = SM->getCharacterData(LocStart);
2025 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002026 // If no ivars and no root or if its root, directly or indirectly,
2027 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002028 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002029 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2030 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2031 Result.c_str(), Result.size());
2032 return;
2033 }
2034
2035 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002036 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002037 Result += "\nstruct ";
2038 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002039
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002040 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002041 const char *cursor = strchr(startBuf, '{');
2042 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002043 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002044
2045 // rewrite the original header *without* disturbing the '{'
2046 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2047 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002048 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002049 Result = "\n struct ";
2050 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00002051 // Note: We don't name the field decl. This simplifies the "codegen" for
2052 // accessing a superclasses instance variables (and is similar to what gcc
2053 // does internally). The unnamed struct field feature is enabled with
2054 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2055 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002056 Result += ";\n";
2057
2058 // insert the super class structure definition.
2059 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2060 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2061 }
2062 cursor++; // past '{'
2063
2064 // Now comment out any visibility specifiers.
2065 while (cursor < endBuf) {
2066 if (*cursor == '@') {
2067 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002068 // Skip whitespace.
2069 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2070 /*scan*/;
2071
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002072 // FIXME: presence of @public, etc. inside comment results in
2073 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002074 if (!strncmp(cursor, "public", strlen("public")) ||
2075 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002076 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00002077 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002078 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002079 // FIXME: If there are cases where '<' is used in ivar declaration part
2080 // of user code, then scan the ivar list and use needToScanForQualifiers
2081 // for type checking.
2082 else if (*cursor == '<') {
2083 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2084 Rewrite.InsertText(atLoc, "/* ", 3);
2085 cursor = strchr(cursor, '>');
2086 cursor++;
2087 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2088 Rewrite.InsertText(atLoc, " */", 3);
2089 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002090 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002091 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002092 // Don't forget to add a ';'!!
2093 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2094 } else { // we don't have any instance variables - insert super struct.
2095 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2096 Result += " {\n struct ";
2097 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00002098 // Note: We don't name the field decl. This simplifies the "codegen" for
2099 // accessing a superclasses instance variables (and is similar to what gcc
2100 // does internally). The unnamed struct field feature is enabled with
2101 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2102 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002103 Result += ";\n};\n";
2104 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2105 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002106 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002107 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002108 if (!ObjCSynthesizedStructs.insert(CDecl))
2109 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002110}
2111
Ted Kremenek42730c52008-01-07 19:49:32 +00002112// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002113/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002114void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002115 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002116 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002117 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002118 const char *ClassName,
2119 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002120 if (MethodBegin == MethodEnd) return;
2121
Fariborz Jahanian04455192007-10-22 21:41:37 +00002122 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002123 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002124 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002125 SEL _cmd;
2126 char *method_types;
2127 void *_imp;
2128 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002129 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002130 Result += "\nstruct _objc_method {\n";
2131 Result += "\tSEL _cmd;\n";
2132 Result += "\tchar *method_types;\n";
2133 Result += "\tvoid *_imp;\n";
2134 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002135
2136 /* struct _objc_method_list {
2137 struct _objc_method_list *next_method;
2138 int method_count;
2139 struct _objc_method method_list[];
2140 }
2141 */
2142 Result += "\nstruct _objc_method_list {\n";
2143 Result += "\tstruct _objc_method_list *next_method;\n";
2144 Result += "\tint method_count;\n";
2145 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002146 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002147 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002148
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002149 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002150 Result += "\nstatic struct _objc_method_list _OBJC_";
2151 Result += prefix;
2152 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2153 Result += "_METHODS_";
2154 Result += ClassName;
2155 Result += " __attribute__ ((section (\"__OBJC, __";
2156 Result += IsInstanceMethod ? "inst" : "cls";
2157 Result += "_meth\")))= ";
2158 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002159
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002160 Result += "\t,{{(SEL)\"";
2161 Result += (*MethodBegin)->getSelector().getName().c_str();
2162 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002163 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002164 Result += "\", \"";
2165 Result += MethodTypeString;
2166 Result += "\", ";
2167 Result += MethodInternalNames[*MethodBegin];
2168 Result += "}\n";
2169 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2170 Result += "\t ,{(SEL)\"";
2171 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002172 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002173 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002174 Result += "\", \"";
2175 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002176 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002177 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002178 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002179 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002180 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002181}
2182
Ted Kremenek42730c52008-01-07 19:49:32 +00002183/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2184void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002185 int NumProtocols,
2186 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002187 const char *ClassName,
2188 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002189 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002190 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002191 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002192 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002193 // Output struct protocol_methods holder of method selector and type.
2194 if (!objc_protocol_methods &&
2195 (PDecl->getNumInstanceMethods() > 0
2196 || PDecl->getNumClassMethods() > 0)) {
2197 /* struct protocol_methods {
2198 SEL _cmd;
2199 char *method_types;
2200 }
2201 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002202 Result += "\nstruct protocol_methods {\n";
2203 Result += "\tSEL _cmd;\n";
2204 Result += "\tchar *method_types;\n";
2205 Result += "};\n";
2206
2207 /* struct _objc_protocol_method_list {
2208 int protocol_method_count;
2209 struct protocol_methods protocols[];
2210 }
2211 */
2212 Result += "\nstruct _objc_protocol_method_list {\n";
2213 Result += "\tint protocol_method_count;\n";
2214 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002215 objc_protocol_methods = true;
2216 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002217
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002218 int NumMethods = PDecl->getNumInstanceMethods();
2219 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002220 Result += "\nstatic struct _objc_protocol_method_list "
2221 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2222 Result += PDecl->getName();
2223 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2224 "{\n\t" + utostr(NumMethods) + "\n";
2225
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002226 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002227 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002228 E = PDecl->instmeth_end(); I != E; ++I) {
2229 if (I == PDecl->instmeth_begin())
2230 Result += "\t ,{{(SEL)\"";
2231 else
2232 Result += "\t ,{(SEL)\"";
2233 Result += (*I)->getSelector().getName().c_str();
2234 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002235 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002236 Result += "\", \"";
2237 Result += MethodTypeString;
2238 Result += "\"}\n";
2239 }
2240 Result += "\t }\n};\n";
2241 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002242
2243 // Output class methods declared in this protocol.
2244 NumMethods = PDecl->getNumClassMethods();
2245 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002246 Result += "\nstatic struct _objc_protocol_method_list "
2247 "_OBJC_PROTOCOL_CLASS_METHODS_";
2248 Result += PDecl->getName();
2249 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2250 "{\n\t";
2251 Result += utostr(NumMethods);
2252 Result += "\n";
2253
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002254 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002255 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002256 E = PDecl->classmeth_end(); I != E; ++I) {
2257 if (I == PDecl->classmeth_begin())
2258 Result += "\t ,{{(SEL)\"";
2259 else
2260 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002261 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002262 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002263 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002264 Result += "\", \"";
2265 Result += MethodTypeString;
2266 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002267 }
2268 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002269 }
2270 // Output:
2271 /* struct _objc_protocol {
2272 // Objective-C 1.0 extensions
2273 struct _objc_protocol_extension *isa;
2274 char *protocol_name;
2275 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002276 struct _objc_protocol_method_list *instance_methods;
2277 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002278 };
2279 */
2280 static bool objc_protocol = false;
2281 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002282 Result += "\nstruct _objc_protocol {\n";
2283 Result += "\tstruct _objc_protocol_extension *isa;\n";
2284 Result += "\tchar *protocol_name;\n";
2285 Result += "\tstruct _objc_protocol **protocol_list;\n";
2286 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2287 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2288 Result += "};\n";
2289
2290 /* struct _objc_protocol_list {
2291 struct _objc_protocol_list *next;
2292 int protocol_count;
2293 struct _objc_protocol *class_protocols[];
2294 }
2295 */
2296 Result += "\nstruct _objc_protocol_list {\n";
2297 Result += "\tstruct _objc_protocol_list *next;\n";
2298 Result += "\tint protocol_count;\n";
2299 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2300 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002301 objc_protocol = true;
2302 }
2303
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002304 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2305 Result += PDecl->getName();
2306 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2307 "{\n\t0, \"";
2308 Result += PDecl->getName();
2309 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002310 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002311 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2312 Result += PDecl->getName();
2313 Result += ", ";
2314 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002315 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002316 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002317 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002318 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2319 Result += PDecl->getName();
2320 Result += "\n";
2321 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002322 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002323 Result += "0\n";
2324 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002325 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002326 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002327 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2328 Result += prefix;
2329 Result += "_PROTOCOLS_";
2330 Result += ClassName;
2331 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2332 "{\n\t0, ";
2333 Result += utostr(NumProtocols);
2334 Result += "\n";
2335
2336 Result += "\t,{&_OBJC_PROTOCOL_";
2337 Result += Protocols[0]->getName();
2338 Result += " \n";
2339
2340 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002341 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002342 Result += "\t ,&_OBJC_PROTOCOL_";
2343 Result += PDecl->getName();
2344 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002345 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002346 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002347 }
2348}
2349
Ted Kremenek42730c52008-01-07 19:49:32 +00002350/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002351/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002352void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002353 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002354 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002355 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002356 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002357 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2358 CDecl = CDecl->getNextClassCategory())
2359 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2360 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002361
Chris Lattnera661a4d2007-12-23 01:40:15 +00002362 std::string FullCategoryName = ClassDecl->getName();
2363 FullCategoryName += '_';
2364 FullCategoryName += IDecl->getName();
2365
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002366 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002367 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002368 true, "CATEGORY_", FullCategoryName.c_str(),
2369 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002370
2371 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002372 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002373 false, "CATEGORY_", FullCategoryName.c_str(),
2374 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002375
2376 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002377 // Null CDecl is case of a category implementation with no category interface
2378 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002379 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002380 CDecl->getNumReferencedProtocols(),
2381 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002382 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002383
2384 /* struct _objc_category {
2385 char *category_name;
2386 char *class_name;
2387 struct _objc_method_list *instance_methods;
2388 struct _objc_method_list *class_methods;
2389 struct _objc_protocol_list *protocols;
2390 // Objective-C 1.0 extensions
2391 uint32_t size; // sizeof (struct _objc_category)
2392 struct _objc_property_list *instance_properties; // category's own
2393 // @property decl.
2394 };
2395 */
2396
2397 static bool objc_category = false;
2398 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002399 Result += "\nstruct _objc_category {\n";
2400 Result += "\tchar *category_name;\n";
2401 Result += "\tchar *class_name;\n";
2402 Result += "\tstruct _objc_method_list *instance_methods;\n";
2403 Result += "\tstruct _objc_method_list *class_methods;\n";
2404 Result += "\tstruct _objc_protocol_list *protocols;\n";
2405 Result += "\tunsigned int size;\n";
2406 Result += "\tstruct _objc_property_list *instance_properties;\n";
2407 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002408 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002409 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002410 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2411 Result += FullCategoryName;
2412 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2413 Result += IDecl->getName();
2414 Result += "\"\n\t, \"";
2415 Result += ClassDecl->getName();
2416 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002417
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002418 if (IDecl->getNumInstanceMethods() > 0) {
2419 Result += "\t, (struct _objc_method_list *)"
2420 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2421 Result += FullCategoryName;
2422 Result += "\n";
2423 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002424 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002425 Result += "\t, 0\n";
2426 if (IDecl->getNumClassMethods() > 0) {
2427 Result += "\t, (struct _objc_method_list *)"
2428 "&_OBJC_CATEGORY_CLASS_METHODS_";
2429 Result += FullCategoryName;
2430 Result += "\n";
2431 }
2432 else
2433 Result += "\t, 0\n";
2434
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002435 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002436 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2437 Result += FullCategoryName;
2438 Result += "\n";
2439 }
2440 else
2441 Result += "\t, 0\n";
2442 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002443}
2444
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002445/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2446/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002447void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2448 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002449 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002450 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002451 Result += IDecl->getName();
2452 Result += ", ";
2453 Result += ivar->getName();
2454 Result += ")";
2455}
2456
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002457//===----------------------------------------------------------------------===//
2458// Meta Data Emission
2459//===----------------------------------------------------------------------===//
2460
Ted Kremenek42730c52008-01-07 19:49:32 +00002461void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002462 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002463 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002464
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002465 // Explictly declared @interface's are already synthesized.
2466 if (CDecl->ImplicitInterfaceDecl()) {
2467 // FIXME: Implementation of a class with no @interface (legacy) doese not
2468 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002469 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002470 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002471
Chris Lattnerc7b06752007-12-12 07:56:42 +00002472 // Build _objc_ivar_list metadata for classes ivars if needed
2473 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2474 ? IDecl->getImplDeclNumIvars()
2475 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002476 if (NumIvars > 0) {
2477 static bool objc_ivar = false;
2478 if (!objc_ivar) {
2479 /* struct _objc_ivar {
2480 char *ivar_name;
2481 char *ivar_type;
2482 int ivar_offset;
2483 };
2484 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002485 Result += "\nstruct _objc_ivar {\n";
2486 Result += "\tchar *ivar_name;\n";
2487 Result += "\tchar *ivar_type;\n";
2488 Result += "\tint ivar_offset;\n";
2489 Result += "};\n";
2490
2491 /* struct _objc_ivar_list {
2492 int ivar_count;
2493 struct _objc_ivar ivar_list[];
2494 };
2495 */
2496 Result += "\nstruct _objc_ivar_list {\n";
2497 Result += "\tint ivar_count;\n";
2498 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002499 objc_ivar = true;
2500 }
2501
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002502 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2503 Result += IDecl->getName();
2504 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2505 "{\n\t";
2506 Result += utostr(NumIvars);
2507 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002508
Ted Kremenek42730c52008-01-07 19:49:32 +00002509 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002510 if (IDecl->getImplDeclNumIvars() > 0) {
2511 IVI = IDecl->ivar_begin();
2512 IVE = IDecl->ivar_end();
2513 } else {
2514 IVI = CDecl->ivar_begin();
2515 IVE = CDecl->ivar_end();
2516 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002517 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002518 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002519 Result += "\", \"";
2520 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002521 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2522 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002523 Result += StrEncoding;
2524 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002525 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002526 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002527 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002528 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002529 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002530 Result += "\", \"";
2531 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002532 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2533 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002534 Result += StrEncoding;
2535 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002536 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002537 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002538 }
2539
2540 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002541 }
2542
2543 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002544 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002545 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002546
2547 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002548 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002549 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002550
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002551 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002552 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002553 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002554 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002555
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002556
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002557 // Declaration of class/meta-class metadata
2558 /* struct _objc_class {
2559 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002560 const char *super_class_name;
2561 char *name;
2562 long version;
2563 long info;
2564 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002565 struct _objc_ivar_list *ivars;
2566 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002567 struct objc_cache *cache;
2568 struct objc_protocol_list *protocols;
2569 const char *ivar_layout;
2570 struct _objc_class_ext *ext;
2571 };
2572 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002573 static bool objc_class = false;
2574 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002575 Result += "\nstruct _objc_class {\n";
2576 Result += "\tstruct _objc_class *isa;\n";
2577 Result += "\tconst char *super_class_name;\n";
2578 Result += "\tchar *name;\n";
2579 Result += "\tlong version;\n";
2580 Result += "\tlong info;\n";
2581 Result += "\tlong instance_size;\n";
2582 Result += "\tstruct _objc_ivar_list *ivars;\n";
2583 Result += "\tstruct _objc_method_list *methods;\n";
2584 Result += "\tstruct objc_cache *cache;\n";
2585 Result += "\tstruct _objc_protocol_list *protocols;\n";
2586 Result += "\tconst char *ivar_layout;\n";
2587 Result += "\tstruct _objc_class_ext *ext;\n";
2588 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002589 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002590 }
2591
2592 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002593 ObjCInterfaceDecl *RootClass = 0;
2594 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002595 while (SuperClass) {
2596 RootClass = SuperClass;
2597 SuperClass = SuperClass->getSuperClass();
2598 }
2599 SuperClass = CDecl->getSuperClass();
2600
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002601 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2602 Result += CDecl->getName();
2603 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2604 "{\n\t(struct _objc_class *)\"";
2605 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2606 Result += "\"";
2607
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 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002620 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002621 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002622 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002623 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002624 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002625 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002626 Result += "\n";
2627 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002628 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002629 Result += ", 0\n";
2630 if (CDecl->getNumIntfRefProtocols() > 0) {
2631 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2632 Result += CDecl->getName();
2633 Result += ",0,0\n";
2634 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002635 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002636 Result += "\t,0,0,0,0\n";
2637 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002638
2639 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002640 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2641 Result += CDecl->getName();
2642 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2643 "{\n\t&_OBJC_METACLASS_";
2644 Result += CDecl->getName();
2645 if (SuperClass) {
2646 Result += ", \"";
2647 Result += SuperClass->getName();
2648 Result += "\", \"";
2649 Result += CDecl->getName();
2650 Result += "\"";
2651 }
2652 else {
2653 Result += ", 0, \"";
2654 Result += CDecl->getName();
2655 Result += "\"";
2656 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002657 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002658 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002659 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002660 Result += ",0";
2661 else {
2662 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002663 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002664 Result += CDecl->getName();
2665 Result += ")";
2666 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002667 if (NumIvars > 0) {
2668 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2669 Result += CDecl->getName();
2670 Result += "\n\t";
2671 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002672 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002673 Result += ",0";
2674 if (IDecl->getNumInstanceMethods() > 0) {
2675 Result += ", &_OBJC_INSTANCE_METHODS_";
2676 Result += CDecl->getName();
2677 Result += ", 0\n\t";
2678 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002679 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002680 Result += ",0,0";
2681 if (CDecl->getNumIntfRefProtocols() > 0) {
2682 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2683 Result += CDecl->getName();
2684 Result += ", 0,0\n";
2685 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002686 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002687 Result += ",0,0,0\n";
2688 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002689}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002690
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002691/// RewriteImplementations - This routine rewrites all method implementations
2692/// and emits meta-data.
2693
2694void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002695 int ClsDefCount = ClassImplementation.size();
2696 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002697
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002698 if (ClsDefCount == 0 && CatDefCount == 0)
2699 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002700 // Rewrite implemented methods
2701 for (int i = 0; i < ClsDefCount; i++)
2702 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002703
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002704 for (int i = 0; i < CatDefCount; i++)
2705 RewriteImplementationDecl(CategoryImplementation[i]);
2706
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002707 // This is needed for use of offsetof
2708 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002709
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002710 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002711 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002712 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002713
2714 // For each implemented category, write out all its meta data.
2715 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002716 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002717
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002718 // Write objc_symtab metadata
2719 /*
2720 struct _objc_symtab
2721 {
2722 long sel_ref_cnt;
2723 SEL *refs;
2724 short cls_def_cnt;
2725 short cat_def_cnt;
2726 void *defs[cls_def_cnt + cat_def_cnt];
2727 };
2728 */
2729
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002730 Result += "\nstruct _objc_symtab {\n";
2731 Result += "\tlong sel_ref_cnt;\n";
2732 Result += "\tSEL *refs;\n";
2733 Result += "\tshort cls_def_cnt;\n";
2734 Result += "\tshort cat_def_cnt;\n";
2735 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2736 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002737
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002738 Result += "static struct _objc_symtab "
2739 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2740 Result += "\t0, 0, " + utostr(ClsDefCount)
2741 + ", " + utostr(CatDefCount) + "\n";
2742 for (int i = 0; i < ClsDefCount; i++) {
2743 Result += "\t,&_OBJC_CLASS_";
2744 Result += ClassImplementation[i]->getName();
2745 Result += "\n";
2746 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002747
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002748 for (int i = 0; i < CatDefCount; i++) {
2749 Result += "\t,&_OBJC_CATEGORY_";
2750 Result += CategoryImplementation[i]->getClassInterface()->getName();
2751 Result += "_";
2752 Result += CategoryImplementation[i]->getName();
2753 Result += "\n";
2754 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002755
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002756 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002757
2758 // Write objc_module metadata
2759
2760 /*
2761 struct _objc_module {
2762 long version;
2763 long size;
2764 const char *name;
2765 struct _objc_symtab *symtab;
2766 }
2767 */
2768
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002769 Result += "\nstruct _objc_module {\n";
2770 Result += "\tlong version;\n";
2771 Result += "\tlong size;\n";
2772 Result += "\tconst char *name;\n";
2773 Result += "\tstruct _objc_symtab *symtab;\n";
2774 Result += "};\n\n";
2775 Result += "static struct _objc_module "
2776 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002777 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2778 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002779 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002780
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002781}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002782