blob: 0bcef9547689c018e267263737177ccc167ba785 [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 Naroff1c46cf12008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000026#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000027using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000029
Steve Naroff1c46cf12008-01-28 21:34:52 +000030static llvm::cl::opt<bool>
31SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
32 llvm::cl::desc("Silence ObjC rewriting warnings"));
33
Chris Lattnerb429ae42007-10-11 00:43:27 +000034namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff1c46cf12008-01-28 21:34:52 +000038 unsigned RewriteFailedDiag;
39
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000041 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000042 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000045 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
46 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
47 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
49 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000050 llvm::SmallVector<Stmt *, 32> Stmts;
51 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000052 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000053
54 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000055 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000056 FunctionDecl *MsgSendStretFunctionDecl;
57 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000058 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000059 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000060 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000061 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000062 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000063 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000064
Steve Naroff0add5d22007-11-03 11:27:19 +000065 // ObjC string constant support.
66 FileVarDecl *ConstantStringClassReference;
67 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000068
Fariborz Jahanian22277422008-01-16 00:09:11 +000069 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000070 int BcLabelCount;
71
Steve Naroff764c1ae2007-11-15 10:28:18 +000072 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000073 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000074 RecordDecl *SuperStructDecl;
75
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000076 // Needed for header files being rewritten
77 bool IsHeader;
78
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000079 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000080 public:
Ted Kremenek17861c52007-12-19 22:51:13 +000081 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000082 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000083 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000084 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000086 MsgSendStretFunctionDecl = 0;
87 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000088 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000089 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000090 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000091 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000092 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000093 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000094 ConstantStringClassReference = 0;
95 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000096 CurMethodDecl = 0;
97 SuperStructDecl = 0;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000098 BcLabelCount = 0;
Steve Naroff1c46cf12008-01-28 21:34:52 +000099
Chris Lattnerae43eb72007-12-02 01:13:47 +0000100 // Get the ID and start/end of the main file.
Ted Kremenek17861c52007-12-19 22:51:13 +0000101 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +0000102 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
103 MainFileStart = MainBuf->getBufferStart();
104 MainFileEnd = MainBuf->getBufferEnd();
105
106
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000107 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +0000108 // declaring objc_selector outside the parameter list removes a silly
109 // scope related warning...
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000110 const char *s = "#pragma once\n"
111 "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000112 "#ifndef OBJC_SUPER\n"
113 "struct objc_super { struct objc_object *o; "
114 "struct objc_object *superClass; };\n"
115 "#define OBJC_SUPER\n"
116 "#endif\n"
117 "#ifndef _REWRITER_typedef_Protocol\n"
118 "typedef struct objc_object Protocol;\n"
119 "#define _REWRITER_typedef_Protocol\n"
120 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000121 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000122 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000123 "extern struct objc_object *objc_msgSendSuper"
124 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000125 "extern struct objc_object *objc_msgSend_stret"
126 "(struct objc_object *, struct objc_selector *, ...);\n"
127 "extern struct objc_object *objc_msgSendSuper_stret"
128 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000129 "extern struct objc_object *objc_msgSend_fpret"
130 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000131 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000132 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000133 "extern struct objc_object *objc_getMetaClass"
134 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000135 "extern void objc_exception_throw(struct objc_object *);\n"
136 "extern void objc_exception_try_enter(void *);\n"
137 "extern void objc_exception_try_exit(void *);\n"
138 "extern struct objc_object *objc_exception_extract(void *);\n"
139 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000140 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000141 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000142 "#include <objc/objc.h>\n"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000143 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000144 "struct __objcFastEnumerationState {\n\t"
145 "unsigned long state;\n\t"
146 "id *itemsPtr;\n\t"
147 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000148 "unsigned long extra[5];\n};\n"
149 "#define __FASTENUMERATIONSTATE\n"
150 "#endif\n";
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000151 if (IsHeader) {
152 // insert the whole string when rewriting a header file
153 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
154 s, strlen(s));
155 }
156 else {
157 // Not rewriting header, exclude the #pragma once pragma
158 const char *p = s + strlen("#pragma once\n");
159 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
160 p, strlen(p));
161 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000162 }
Chris Lattner569faa62007-10-11 18:38:32 +0000163
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000164 // Top Level Driver code.
165 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000166 void HandleDeclInMainFile(Decl *D);
Steve Naroff1c46cf12008-01-28 21:34:52 +0000167 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {
168 IsHeader = isHeader;
169 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
170 "rewriting sub-expression within a macro (may not be correct)");
171 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000172 ~RewriteTest();
173
174 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000175 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000176 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000177 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000178 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
179 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000180 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000181 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
182 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
183 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
184 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
185 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
186 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000187 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000188 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000189 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000190 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000191 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000192
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000193 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000194 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000195 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000196 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000197 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000198 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000199 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000200 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000201 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
202 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
203 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
204 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000205 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000206 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
207 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000208 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000209 Stmt *RewriteBreakStmt(BreakStmt *S);
210 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000211 void SynthCountByEnumWithState(std::string &buf);
212
Steve Naroff02a82aa2007-10-30 23:14:51 +0000213 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000214 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000215 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000216 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000217 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000218 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000219 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000220 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000221 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000222 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000223
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000224 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000226 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000227
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000229 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000230
Ted Kremenek42730c52008-01-07 19:49:32 +0000231 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
232 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000233 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000234 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000235 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000236 const char *ClassName,
237 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000238
Ted Kremenek42730c52008-01-07 19:49:32 +0000239 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000240 int NumProtocols,
241 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000242 const char *ClassName,
243 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000244 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000245 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000246 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
247 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000248 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000249 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000250 };
251}
252
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000253static bool IsHeaderFile(const std::string &Filename) {
254 std::string::size_type DotPos = Filename.rfind('.');
255
256 if (DotPos == std::string::npos) {
257 // no file extension
258 return false;
259 }
260
261 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
262 // C header: .h
263 // C++ header: .hh or .H;
264 return Ext == "h" || Ext == "hh" || Ext == "H";
265}
266
267ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
268 Diagnostic &Diags) {
269 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattner258f26c2007-11-30 22:25:36 +0000270}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000271
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000272//===----------------------------------------------------------------------===//
273// Top Level Driver Code
274//===----------------------------------------------------------------------===//
275
Chris Lattner569faa62007-10-11 18:38:32 +0000276void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000277 // Two cases: either the decl could be in the main file, or it could be in a
278 // #included file. If the former, rewrite it now. If the later, check to see
279 // if we rewrote the #include/#import.
280 SourceLocation Loc = D->getLocation();
281 Loc = SM->getLogicalLoc(Loc);
282
283 // If this is for a builtin, ignore it.
284 if (Loc.isInvalid()) return;
285
Steve Naroffe9780582007-10-23 23:50:29 +0000286 // Look for built-in declarations that we need to refer during the rewrite.
287 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000288 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000289 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
290 // declared in <Foundation/NSString.h>
291 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
292 ConstantStringClassReference = FVD;
293 return;
294 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000295 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000296 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000297 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000298 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000299 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000300 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000301 } else if (ObjCForwardProtocolDecl *FP =
302 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000303 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000304 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000305 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000306 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
307 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000308}
309
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000310/// HandleDeclInMainFile - This is called for each top-level decl defined in the
311/// main file of the input.
312void RewriteTest::HandleDeclInMainFile(Decl *D) {
313 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
314 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000315 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000316
Ted Kremenek42730c52008-01-07 19:49:32 +0000317 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000318 if (Stmt *Body = MD->getBody()) {
319 //Body->dump();
320 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000321 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000322 CurMethodDecl = 0;
323 }
Steve Naroff18c83382007-11-13 23:01:27 +0000324 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000325 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000326 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000327 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000328 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000329 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000330 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000331 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000332 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000333 if (VD->getInit())
334 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
335 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000336 // Nothing yet.
337}
338
339RewriteTest::~RewriteTest() {
340 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000341
342 // Rewrite tabs if we care.
343 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000344
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000345 RewriteInclude();
346
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000347 // Rewrite Objective-c meta data*
348 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000349 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000350
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000351 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
352 // we are done.
353 if (const RewriteBuffer *RewriteBuf =
354 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000355 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000356 std::string S(RewriteBuf->begin(), RewriteBuf->end());
357 printf("%s\n", S.c_str());
358 } else {
359 printf("No changes\n");
360 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000361 // Emit metadata.
362 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000363}
364
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000365//===----------------------------------------------------------------------===//
366// Syntactic (non-AST) Rewriting Code
367//===----------------------------------------------------------------------===//
368
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000369void RewriteTest::RewriteInclude() {
370 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
371 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
372 const char *MainBufStart = MainBuf.first;
373 const char *MainBufEnd = MainBuf.second;
374 size_t ImportLen = strlen("import");
375 size_t IncludeLen = strlen("include");
376
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000377 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000378 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
379 if (*BufPtr == '#') {
380 if (++BufPtr == MainBufEnd)
381 return;
382 while (*BufPtr == ' ' || *BufPtr == '\t')
383 if (++BufPtr == MainBufEnd)
384 return;
385 if (!strncmp(BufPtr, "import", ImportLen)) {
386 // replace import with include
387 SourceLocation ImportLoc =
388 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
389 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
390 BufPtr += ImportLen;
391 }
392 }
393 }
Chris Lattner74db1682007-10-16 21:07:07 +0000394}
395
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000396void RewriteTest::RewriteTabs() {
397 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
398 const char *MainBufStart = MainBuf.first;
399 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000400
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000401 // Loop over the whole file, looking for tabs.
402 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
403 if (*BufPtr != '\t')
404 continue;
405
406 // Okay, we found a tab. This tab will turn into at least one character,
407 // but it depends on which 'virtual column' it is in. Compute that now.
408 unsigned VCol = 0;
409 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
410 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
411 ++VCol;
412
413 // Okay, now that we know the virtual column, we know how many spaces to
414 // insert. We assume 8-character tab-stops.
415 unsigned Spaces = 8-(VCol & 7);
416
417 // Get the location of the tab.
418 SourceLocation TabLoc =
419 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
420
421 // Rewrite the single tab character into a sequence of spaces.
422 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
423 }
Chris Lattner569faa62007-10-11 18:38:32 +0000424}
425
426
Ted Kremenek42730c52008-01-07 19:49:32 +0000427void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000428 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000429 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430
431 // Get the start location and compute the semi location.
432 SourceLocation startLoc = ClassDecl->getLocation();
433 const char *startBuf = SM->getCharacterData(startLoc);
434 const char *semiPtr = strchr(startBuf, ';');
435
436 // Translate to typedef's that forward reference structs with the same name
437 // as the class. As a convenience, we include the original declaration
438 // as a comment.
439 std::string typedefString;
440 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000441 typedefString.append(startBuf, semiPtr-startBuf+1);
442 typedefString += "\n";
443 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000444 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000445 typedefString += "#ifndef _REWRITER_typedef_";
446 typedefString += ForwardDecl->getName();
447 typedefString += "\n";
448 typedefString += "#define _REWRITER_typedef_";
449 typedefString += ForwardDecl->getName();
450 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000451 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000452 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000453 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000454 }
455
456 // Replace the @class with typedefs corresponding to the classes.
457 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
458 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000459}
460
Ted Kremenek42730c52008-01-07 19:49:32 +0000461void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000462 SourceLocation LocStart = Method->getLocStart();
463 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000464
Steve Naroff2ce399a2007-12-14 23:37:57 +0000465 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
466 Rewrite.InsertText(LocStart, "/* ", 3);
467 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
468 } else {
469 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000470 }
471}
472
Ted Kremenek42730c52008-01-07 19:49:32 +0000473void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000474{
475 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000476 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000477 SourceLocation Loc = Property->getLocation();
478
479 Rewrite.ReplaceText(Loc, 0, "// ", 3);
480
481 // FIXME: handle properties that are declared across multiple lines.
482 }
483}
484
Ted Kremenek42730c52008-01-07 19:49:32 +0000485void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000486 SourceLocation LocStart = CatDecl->getLocStart();
487
488 // FIXME: handle category headers that are declared across multiple lines.
489 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
490
Ted Kremenek42730c52008-01-07 19:49:32 +0000491 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000492 E = CatDecl->instmeth_end(); I != E; ++I)
493 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000494 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000495 E = CatDecl->classmeth_end(); I != E; ++I)
496 RewriteMethodDeclaration(*I);
497
Steve Naroff667f1682007-10-30 13:30:57 +0000498 // Lastly, comment out the @end.
499 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
500}
501
Ted Kremenek42730c52008-01-07 19:49:32 +0000502void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000503 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000504
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000505 SourceLocation LocStart = PDecl->getLocStart();
506
507 // FIXME: handle protocol headers that are declared across multiple lines.
508 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
509
Ted Kremenek42730c52008-01-07 19:49:32 +0000510 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000511 E = PDecl->instmeth_end(); I != E; ++I)
512 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000513 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000514 E = PDecl->classmeth_end(); I != E; ++I)
515 RewriteMethodDeclaration(*I);
516
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000517 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000518 SourceLocation LocEnd = PDecl->getAtEndLoc();
519 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000520
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000521 // Must comment out @optional/@required
522 const char *startBuf = SM->getCharacterData(LocStart);
523 const char *endBuf = SM->getCharacterData(LocEnd);
524 for (const char *p = startBuf; p < endBuf; p++) {
525 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
526 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000527 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000528 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
529 CommentedOptional.c_str(), CommentedOptional.size());
530
531 }
532 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
533 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000534 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000535 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
536 CommentedRequired.c_str(), CommentedRequired.size());
537
538 }
539 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000540}
541
Ted Kremenek42730c52008-01-07 19:49:32 +0000542void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000543 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000544 if (LocStart.isInvalid())
545 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000546 // FIXME: handle forward protocol that are declared across multiple lines.
547 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
548}
549
Ted Kremenek42730c52008-01-07 19:49:32 +0000550void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000551 std::string &ResultStr) {
552 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000553 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000554 ResultStr += "id";
555 else
556 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000557 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000558
559 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000560 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000561
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000562 if (OMD->isInstance())
563 NameStr += "_I_";
564 else
565 NameStr += "_C_";
566
567 NameStr += OMD->getClassInterface()->getName();
568 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000569
570 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000571 if (ObjCCategoryImplDecl *CID =
572 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000573 NameStr += CID->getName();
574 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000575 }
576 // Append selector names, replacing ':' with '_'
577 const char *selName = OMD->getSelector().getName().c_str();
578 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000579 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000580 else {
581 std::string selString = OMD->getSelector().getName();
582 int len = selString.size();
583 for (int i = 0; i < len; i++)
584 if (selString[i] == ':')
585 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000586 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000587 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000588 // Remember this name for metadata emission
589 MethodInternalNames[OMD] = NameStr;
590 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000591
592 // Rewrite arguments
593 ResultStr += "(";
594
595 // invisible arguments
596 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000597 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000598 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000599 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000600 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000601 ResultStr += selfTy.getAsString();
602 }
603 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000604 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000605
606 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000607 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000608 ResultStr += " _cmd";
609
610 // Method arguments.
611 for (int i = 0; i < OMD->getNumParams(); i++) {
612 ParmVarDecl *PDecl = OMD->getParamDecl(i);
613 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000614 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000615 ResultStr += "id";
616 else
617 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000618 ResultStr += " ";
619 ResultStr += PDecl->getName();
620 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000621 if (OMD->isVariadic())
622 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000623 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000624
625}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000626void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000627 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
628 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000629
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000630 if (IMD)
631 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
632 else
633 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000634
Ted Kremenek42730c52008-01-07 19:49:32 +0000635 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000636 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
637 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000638 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000639 ObjCMethodDecl *OMD = *I;
640 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000641 SourceLocation LocStart = OMD->getLocStart();
642 SourceLocation LocEnd = OMD->getBody()->getLocStart();
643
644 const char *startBuf = SM->getCharacterData(LocStart);
645 const char *endBuf = SM->getCharacterData(LocEnd);
646 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
647 ResultStr.c_str(), ResultStr.size());
648 }
649
Ted Kremenek42730c52008-01-07 19:49:32 +0000650 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000651 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
652 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000653 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000654 ObjCMethodDecl *OMD = *I;
655 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000656 SourceLocation LocStart = OMD->getLocStart();
657 SourceLocation LocEnd = OMD->getBody()->getLocStart();
658
659 const char *startBuf = SM->getCharacterData(LocStart);
660 const char *endBuf = SM->getCharacterData(LocEnd);
661 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
662 ResultStr.c_str(), ResultStr.size());
663 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000664 if (IMD)
665 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
666 else
667 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000668}
669
Ted Kremenek42730c52008-01-07 19:49:32 +0000670void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000671 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000672 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000673 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000674 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000675 ResultStr += ClassDecl->getName();
676 ResultStr += "\n";
677 ResultStr += "#define _REWRITER_typedef_";
678 ResultStr += ClassDecl->getName();
679 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000680 ResultStr += "typedef struct ";
681 ResultStr += ClassDecl->getName();
682 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000683 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000684 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000685
686 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000687 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000688 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000689 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000690
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000691 RewriteProperties(ClassDecl->getNumPropertyDecl(),
692 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000693 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000694 E = ClassDecl->instmeth_end(); I != E; ++I)
695 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000696 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000697 E = ClassDecl->classmeth_end(); I != E; ++I)
698 RewriteMethodDeclaration(*I);
699
Steve Naroff1ccf4632007-10-30 03:43:13 +0000700 // Lastly, comment out the @end.
701 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000702}
703
Steve Naroff6b759ce2007-11-15 02:58:25 +0000704Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000706 if (IV->isFreeIvar()) {
707 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
708 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000709 if (Rewrite.ReplaceStmt(IV, Replacement)) {
710 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000711 SourceRange Range = IV->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +0000712 if (!SilenceRewriteMacroWarning)
713 Diags.Report(Context->getFullLoc(IV->getLocation()), RewriteFailedDiag,
714 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000715 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000716 delete IV;
717 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000718 } else {
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000719#if 0
720 /// This code is not right. It seems unnecessary. It breaks use of
721 /// ivar reference used as 'receiver' of an expression; as in:
722 /// [newInv->_container addObject:0];
Steve Naroff292b7b92007-11-15 11:33:00 +0000723 if (CurMethodDecl) {
724 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000725 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000726 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
727 IdentifierInfo *II = intT->getDecl()->getIdentifier();
728 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
729 II, 0);
730 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
731
732 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
733 // Don't forget the parens to enforce the proper binding.
734 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000735 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
736 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000737 SourceRange Range = IV->getBase()->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +0000738 if (!SilenceRewriteMacroWarning)
739 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()),
740 RewriteFailedDiag, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000741 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000742 delete IV->getBase();
743 return PE;
744 }
745 }
746 }
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000747#endif
Steve Naroff6b759ce2007-11-15 02:58:25 +0000748 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000749 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000750}
751
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000752//===----------------------------------------------------------------------===//
753// Function Body / Expression rewriting
754//===----------------------------------------------------------------------===//
755
Steve Naroff334fbc22007-11-09 15:20:18 +0000756Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000757 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
758 isa<DoStmt>(S) || isa<ForStmt>(S))
759 Stmts.push_back(S);
760 else if (isa<ObjCForCollectionStmt>(S)) {
761 Stmts.push_back(S);
762 ObjCBcLabelNo.push_back(++BcLabelCount);
763 }
764
Chris Lattner6fe8b272007-10-16 22:36:42 +0000765 // Otherwise, just rewrite all children.
766 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
767 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000768 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000769 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000770 if (newStmt)
771 *CI = newStmt;
772 }
Steve Naroffe9780582007-10-23 23:50:29 +0000773
774 // Handle specific things.
775 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
776 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000777
778 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
779 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000780
781 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
782 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000783
784 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
785 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000786
Steve Naroff71226032007-10-24 22:48:43 +0000787 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
788 // Before we rewrite it, put the original message expression in a comment.
789 SourceLocation startLoc = MessExpr->getLocStart();
790 SourceLocation endLoc = MessExpr->getLocEnd();
791
792 const char *startBuf = SM->getCharacterData(startLoc);
793 const char *endBuf = SM->getCharacterData(endLoc);
794
795 std::string messString;
796 messString += "// ";
797 messString.append(startBuf, endBuf-startBuf+1);
798 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000799
Steve Naroff71226032007-10-24 22:48:43 +0000800 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
801 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
802 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000803 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000804 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000805 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000806
Ted Kremenek42730c52008-01-07 19:49:32 +0000807 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
808 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000809
Ted Kremenek42730c52008-01-07 19:49:32 +0000810 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
811 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000812
813 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
814 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000815
816 if (ObjCForCollectionStmt *StmtForCollection =
817 dyn_cast<ObjCForCollectionStmt>(S))
818 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000819 if (BreakStmt *StmtBreakStmt =
820 dyn_cast<BreakStmt>(S))
821 return RewriteBreakStmt(StmtBreakStmt);
822 if (ContinueStmt *StmtContinueStmt =
823 dyn_cast<ContinueStmt>(S))
824 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000825
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000826 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
827 isa<DoStmt>(S) || isa<ForStmt>(S)) {
828 assert(!Stmts.empty() && "Statement stack is empty");
829 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
830 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
831 && "Statement stack mismatch");
832 Stmts.pop_back();
833 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000834#if 0
835 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
836 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
837 // Get the new text.
838 std::ostringstream Buf;
839 Replacement->printPretty(Buf);
840 const std::string &Str = Buf.str();
841
842 printf("CAST = %s\n", &Str[0]);
843 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
844 delete S;
845 return Replacement;
846 }
847#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000848 // Return this stmt unmodified.
849 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000850}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000851
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000852/// SynthCountByEnumWithState - To print:
853/// ((unsigned int (*)
854/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
855/// (void *)objc_msgSend)((id)l_collection,
856/// sel_registerName(
857/// "countByEnumeratingWithState:objects:count:"),
858/// &enumState,
859/// (id *)items, (unsigned int)16)
860///
861void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
862 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
863 "id *, unsigned int))(void *)objc_msgSend)";
864 buf += "\n\t\t";
865 buf += "((id)l_collection,\n\t\t";
866 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
867 buf += "\n\t\t";
868 buf += "&enumState, "
869 "(id *)items, (unsigned int)16)";
870}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000871
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000872/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
873/// statement to exit to its outer synthesized loop.
874///
875Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
876 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
877 return S;
878 // replace break with goto __break_label
879 std::string buf;
880
881 SourceLocation startLoc = S->getLocStart();
882 buf = "goto __break_label_";
883 buf += utostr(ObjCBcLabelNo.back());
884 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
885
886 return 0;
887}
888
889/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
890/// statement to continue with its inner synthesized loop.
891///
892Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
893 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
894 return S;
895 // replace continue with goto __continue_label
896 std::string buf;
897
898 SourceLocation startLoc = S->getLocStart();
899 buf = "goto __continue_label_";
900 buf += utostr(ObjCBcLabelNo.back());
901 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
902
903 return 0;
904}
905
Fariborz Jahanian72cf3b52008-01-09 01:25:54 +0000906/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000907/// It rewrites:
908/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000909
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000910/// Into:
911/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000912/// type elem;
913/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000914/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000915/// id l_collection = (id)collection;
916/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
917/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000918/// if (limit) {
919/// unsigned long startMutations = *enumState.mutationsPtr;
920/// do {
921/// unsigned long counter = 0;
922/// do {
923/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000924/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000925/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000926/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000927/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000928/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000929/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
930/// objects:items count:16]);
931/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000932/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000933/// }
934/// else
935/// elem = nil;
936/// }
937///
938Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000939 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
940 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
941 "ObjCForCollectionStmt Statement stack mismatch");
942 assert(!ObjCBcLabelNo.empty() &&
943 "ObjCForCollectionStmt - Label No stack empty");
944
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000945 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000946 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000947 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000948 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000949 std::string buf;
950 buf = "\n{\n\t";
951 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
952 // type elem;
953 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000954 elementTypeAsString = ElementType.getAsString();
955 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000956 buf += " ";
957 elementName = DS->getDecl()->getName();
958 buf += elementName;
959 buf += ";\n\t";
960 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000961 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000962 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000963 elementTypeAsString = DR->getDecl()->getType().getAsString();
964 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000965 else
966 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
967
968 // struct __objcFastEnumerationState enumState = { 0 };
969 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
970 // id items[16];
971 buf += "id items[16];\n\t";
972 // id l_collection = (id)
973 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000974 // Find start location of 'collection' the hard way!
975 const char *startCollectionBuf = startBuf;
976 startCollectionBuf += 3; // skip 'for'
977 startCollectionBuf = strchr(startCollectionBuf, '(');
978 startCollectionBuf++; // skip '('
979 // find 'in' and skip it.
980 while (*startCollectionBuf != ' ' ||
981 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
982 (*(startCollectionBuf+3) != ' ' &&
983 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
984 startCollectionBuf++;
985 startCollectionBuf += 3;
986
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000987 // Replace: "for (type element in" with string constructed thus far.
988 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
989 buf.c_str(), buf.size());
990 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000991 SourceLocation rightParenLoc = S->getRParenLoc();
992 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
993 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000994 buf = ";\n\t";
995
996 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
997 // objects:items count:16];
998 // which is synthesized into:
999 // unsigned int limit =
1000 // ((unsigned int (*)
1001 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1002 // (void *)objc_msgSend)((id)l_collection,
1003 // sel_registerName(
1004 // "countByEnumeratingWithState:objects:count:"),
1005 // (struct __objcFastEnumerationState *)&state,
1006 // (id *)items, (unsigned int)16);
1007 buf += "unsigned long limit =\n\t\t";
1008 SynthCountByEnumWithState(buf);
1009 buf += ";\n\t";
1010 /// if (limit) {
1011 /// unsigned long startMutations = *enumState.mutationsPtr;
1012 /// do {
1013 /// unsigned long counter = 0;
1014 /// do {
1015 /// if (startMutations != *enumState.mutationsPtr)
1016 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001017 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001018 buf += "if (limit) {\n\t";
1019 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1020 buf += "do {\n\t\t";
1021 buf += "unsigned long counter = 0;\n\t\t";
1022 buf += "do {\n\t\t\t";
1023 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1024 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1025 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001026 buf += " = (";
1027 buf += elementTypeAsString;
1028 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001029 // Replace ')' in for '(' type elem in collection ')' with all of these.
1030 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1031
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001032 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001033 /// } while (counter < limit);
1034 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1035 /// objects:items count:16]);
1036 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001037 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001038 /// }
1039 /// else
1040 /// elem = nil;
1041 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001042 ///
1043 buf = ";\n\t";
1044 buf += "__continue_label_";
1045 buf += utostr(ObjCBcLabelNo.back());
1046 buf += ": ;";
1047 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001048 buf += "} while (counter < limit);\n\t";
1049 buf += "} while (limit = ";
1050 SynthCountByEnumWithState(buf);
1051 buf += ");\n\t";
1052 buf += elementName;
1053 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001054 buf += "__break_label_";
1055 buf += utostr(ObjCBcLabelNo.back());
1056 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001057 buf += "}\n\t";
1058 buf += "else\n\t\t";
1059 buf += elementName;
1060 buf += " = nil;\n";
1061 buf += "}\n";
1062 // Insert all these *after* the statement body.
1063 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1064 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1065 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1066 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001067 Stmts.pop_back();
1068 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001069
1070 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001071}
1072
Ted Kremenek42730c52008-01-07 19:49:32 +00001073Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001074 // Get the start location and compute the semi location.
1075 SourceLocation startLoc = S->getLocStart();
1076 const char *startBuf = SM->getCharacterData(startLoc);
1077
1078 assert((*startBuf == '@') && "bogus @try location");
1079
1080 std::string buf;
1081 // declare a new scope with two variables, _stack and _rethrow.
1082 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1083 buf += "int buf[18/*32-bit i386*/];\n";
1084 buf += "char *pointers[4];} _stack;\n";
1085 buf += "id volatile _rethrow = 0;\n";
1086 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001087 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001088
1089 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1090
1091 startLoc = S->getTryBody()->getLocEnd();
1092 startBuf = SM->getCharacterData(startLoc);
1093
1094 assert((*startBuf == '}') && "bogus @try block");
1095
1096 SourceLocation lastCurlyLoc = startLoc;
1097
1098 startLoc = startLoc.getFileLocWithOffset(1);
1099 buf = " /* @catch begin */ else {\n";
1100 buf += " id _caught = objc_exception_extract(&_stack);\n";
1101 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001102 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001103 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1104 buf += " else { /* @catch continue */";
1105
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001106 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001107
1108 bool sawIdTypedCatch = false;
1109 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001110 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001111 while (catchList) {
1112 Stmt *catchStmt = catchList->getCatchParamStmt();
1113
1114 if (catchList == S->getCatchStmts())
1115 buf = "if ("; // we are generating code for the first catch clause
1116 else
1117 buf = "else if (";
1118 startLoc = catchList->getLocStart();
1119 startBuf = SM->getCharacterData(startLoc);
1120
1121 assert((*startBuf == '@') && "bogus @catch location");
1122
1123 const char *lParenLoc = strchr(startBuf, '(');
1124
1125 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1126 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001127 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001128 buf += "1) { ";
1129 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1130 buf.c_str(), buf.size());
1131 sawIdTypedCatch = true;
1132 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001133 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001134
Ted Kremenek42730c52008-01-07 19:49:32 +00001135 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001136 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001137 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001138 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001139 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +00001140 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1141 buf.c_str(), buf.size());
1142 }
1143 }
1144 // Now rewrite the body...
1145 lastCatchBody = catchList->getCatchBody();
1146 SourceLocation rParenLoc = catchList->getRParenLoc();
1147 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1148 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1149 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1150 assert((*rParenBuf == ')') && "bogus @catch paren location");
1151 assert((*bodyBuf == '{') && "bogus @catch body location");
1152
1153 buf = " = _caught;";
1154 // Here we replace ") {" with "= _caught;" (which initializes and
1155 // declares the @catch parameter).
1156 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1157 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001158 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001159 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001160 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001161 catchList = catchList->getNextCatchStmt();
1162 }
1163 // Complete the catch list...
1164 if (lastCatchBody) {
1165 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1166 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1167 assert((*bodyBuf == '}') && "bogus @catch body location");
1168 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1169 buf = " } } /* @catch end */\n";
1170
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001171 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001172
1173 // Set lastCurlyLoc
1174 lastCurlyLoc = lastCatchBody->getLocEnd();
1175 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001176 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001177 startLoc = finalStmt->getLocStart();
1178 startBuf = SM->getCharacterData(startLoc);
1179 assert((*startBuf == '@') && "bogus @finally start");
1180
1181 buf = "/* @finally */";
1182 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1183
1184 Stmt *body = finalStmt->getFinallyBody();
1185 SourceLocation startLoc = body->getLocStart();
1186 SourceLocation endLoc = body->getLocEnd();
1187 const char *startBuf = SM->getCharacterData(startLoc);
1188 const char *endBuf = SM->getCharacterData(endLoc);
1189 assert((*startBuf == '{') && "bogus @finally body location");
1190 assert((*endBuf == '}') && "bogus @finally body location");
1191
1192 startLoc = startLoc.getFileLocWithOffset(1);
1193 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001194 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001195 endLoc = endLoc.getFileLocWithOffset(-1);
1196 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001197 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001198
1199 // Set lastCurlyLoc
1200 lastCurlyLoc = body->getLocEnd();
1201 }
1202 // Now emit the final closing curly brace...
1203 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1204 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001205 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001206 return 0;
1207}
1208
Ted Kremenek42730c52008-01-07 19:49:32 +00001209Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001210 return 0;
1211}
1212
Ted Kremenek42730c52008-01-07 19:49:32 +00001213Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001214 return 0;
1215}
1216
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001217// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1218// the throw expression is typically a message expression that's already
1219// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001220Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001221 // Get the start location and compute the semi location.
1222 SourceLocation startLoc = S->getLocStart();
1223 const char *startBuf = SM->getCharacterData(startLoc);
1224
1225 assert((*startBuf == '@') && "bogus @throw location");
1226
1227 std::string buf;
1228 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001229 if (S->getThrowExpr())
1230 buf = "objc_exception_throw(";
1231 else // add an implicit argument
1232 buf = "objc_exception_throw(_caught";
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001233 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1234 const char *semiBuf = strchr(startBuf, ';');
1235 assert((*semiBuf == ';') && "@throw: can't find ';'");
1236 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1237 buf = ");";
1238 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1239 return 0;
1240}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001241
Chris Lattner0021f452007-10-24 16:57:36 +00001242Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001243 // Create a new string expression.
1244 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001245 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001246 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1247 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001248 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1249 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001250 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +00001251 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1252 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +00001253 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001254 if (!SilenceRewriteMacroWarning)
1255 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
1256 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +00001257 }
1258
Chris Lattner4478db92007-11-30 22:53:43 +00001259 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001260 delete Exp;
1261 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001262}
1263
Steve Naroff296b74f2007-11-05 14:50:49 +00001264Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1265 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1266 // Create a call to sel_registerName("selName").
1267 llvm::SmallVector<Expr*, 8> SelExprs;
1268 QualType argType = Context->getPointerType(Context->CharTy);
1269 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1270 Exp->getSelector().getName().size(),
1271 false, argType, SourceLocation(),
1272 SourceLocation()));
1273 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1274 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001275 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1276 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001277 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001278 if (!SilenceRewriteMacroWarning)
1279 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
1280 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001281 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001282 delete Exp;
1283 return SelExp;
1284}
1285
Steve Naroff71226032007-10-24 22:48:43 +00001286CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1287 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001288 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001289 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001290
1291 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001292 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001293
1294 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001295 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001296 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1297
1298 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001299
Steve Naroff71226032007-10-24 22:48:43 +00001300 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1301}
1302
Steve Naroffc8a92d12007-11-01 13:24:47 +00001303static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1304 const char *&startRef, const char *&endRef) {
1305 while (startBuf < endBuf) {
1306 if (*startBuf == '<')
1307 startRef = startBuf; // mark the start.
1308 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001309 if (startRef && *startRef == '<') {
1310 endRef = startBuf; // mark the end.
1311 return true;
1312 }
1313 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001314 }
1315 startBuf++;
1316 }
1317 return false;
1318}
1319
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001320static void scanToNextArgument(const char *&argRef) {
1321 int angle = 0;
1322 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1323 if (*argRef == '<')
1324 angle++;
1325 else if (*argRef == '>')
1326 angle--;
1327 argRef++;
1328 }
1329 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1330}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001331
Steve Naroffc8a92d12007-11-01 13:24:47 +00001332bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001333
Ted Kremenek42730c52008-01-07 19:49:32 +00001334 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001335 return true;
1336
Ted Kremenek42730c52008-01-07 19:49:32 +00001337 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001338 return true;
1339
Steve Naroffc8a92d12007-11-01 13:24:47 +00001340 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001341 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001342 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001343 return true; // we have "Class <Protocol> *".
1344 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001345 return false;
1346}
1347
Ted Kremenek42730c52008-01-07 19:49:32 +00001348void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001349 SourceLocation Loc;
1350 QualType Type;
1351 const FunctionTypeProto *proto = 0;
1352 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1353 Loc = VD->getLocation();
1354 Type = VD->getType();
1355 }
1356 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1357 Loc = FD->getLocation();
1358 // Check for ObjC 'id' and class types that have been adorned with protocol
1359 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1360 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1361 assert(funcType && "missing function type");
1362 proto = dyn_cast<FunctionTypeProto>(funcType);
1363 if (!proto)
1364 return;
1365 Type = proto->getResultType();
1366 }
1367 else
1368 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001369
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001370 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001371 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001372
1373 const char *endBuf = SM->getCharacterData(Loc);
1374 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001375 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001376 startBuf--; // scan backward (from the decl location) for return type.
1377 const char *startRef = 0, *endRef = 0;
1378 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1379 // Get the locations of the startRef, endRef.
1380 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1381 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1382 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001383 Rewrite.InsertText(LessLoc, "/*", 2);
1384 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001385 }
1386 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001387 if (!proto)
1388 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001389 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001390 const char *startBuf = SM->getCharacterData(Loc);
1391 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001392 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1393 if (needToScanForQualifiers(proto->getArgType(i))) {
1394 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001395
Steve Naroffc8a92d12007-11-01 13:24:47 +00001396 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001397 // scan forward (from the decl location) for argument types.
1398 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001399 const char *startRef = 0, *endRef = 0;
1400 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1401 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001402 SourceLocation LessLoc =
1403 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1404 SourceLocation GreaterLoc =
1405 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001406 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001407 Rewrite.InsertText(LessLoc, "/*", 2);
1408 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001409 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001410 startBuf = ++endBuf;
1411 }
1412 else {
1413 while (*startBuf != ')' && *startBuf != ',')
1414 startBuf++; // scan forward (from the decl location) for argument types.
1415 startBuf++;
1416 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001417 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001418}
1419
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001420// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1421void RewriteTest::SynthSelGetUidFunctionDecl() {
1422 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1423 llvm::SmallVector<QualType, 16> ArgTys;
1424 ArgTys.push_back(Context->getPointerType(
1425 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001426 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001427 &ArgTys[0], ArgTys.size(),
1428 false /*isVariadic*/);
1429 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1430 SelGetUidIdent, getFuncType,
1431 FunctionDecl::Extern, false, 0);
1432}
1433
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001434// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1435void RewriteTest::SynthGetProtocolFunctionDecl() {
1436 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1437 llvm::SmallVector<QualType, 16> ArgTys;
1438 ArgTys.push_back(Context->getPointerType(
1439 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001440 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001441 &ArgTys[0], ArgTys.size(),
1442 false /*isVariadic*/);
1443 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1444 SelGetProtoIdent, getFuncType,
1445 FunctionDecl::Extern, false, 0);
1446}
1447
Steve Naroff02a82aa2007-10-30 23:14:51 +00001448void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1449 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001450 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001451 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001452 return;
1453 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001454 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001455}
1456
1457// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1458void RewriteTest::SynthMsgSendFunctionDecl() {
1459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1460 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001461 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001462 assert(!argT.isNull() && "Can't find 'id' type");
1463 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001464 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001465 assert(!argT.isNull() && "Can't find 'SEL' type");
1466 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001467 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001468 &ArgTys[0], ArgTys.size(),
1469 true /*isVariadic*/);
1470 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1471 msgSendIdent, msgSendType,
1472 FunctionDecl::Extern, false, 0);
1473}
1474
Steve Naroff764c1ae2007-11-15 10:28:18 +00001475// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1476void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1477 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1478 llvm::SmallVector<QualType, 16> ArgTys;
1479 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1480 &Context->Idents.get("objc_super"), 0);
1481 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1482 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1483 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001484 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001485 assert(!argT.isNull() && "Can't find 'SEL' type");
1486 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001487 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001488 &ArgTys[0], ArgTys.size(),
1489 true /*isVariadic*/);
1490 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1491 msgSendIdent, msgSendType,
1492 FunctionDecl::Extern, false, 0);
1493}
1494
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001495// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1496void RewriteTest::SynthMsgSendStretFunctionDecl() {
1497 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1498 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001499 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001500 assert(!argT.isNull() && "Can't find 'id' type");
1501 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001502 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001503 assert(!argT.isNull() && "Can't find 'SEL' type");
1504 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001505 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001506 &ArgTys[0], ArgTys.size(),
1507 true /*isVariadic*/);
1508 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1509 msgSendIdent, msgSendType,
1510 FunctionDecl::Extern, false, 0);
1511}
1512
1513// SynthMsgSendSuperStretFunctionDecl -
1514// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1515void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1516 IdentifierInfo *msgSendIdent =
1517 &Context->Idents.get("objc_msgSendSuper_stret");
1518 llvm::SmallVector<QualType, 16> ArgTys;
1519 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1520 &Context->Idents.get("objc_super"), 0);
1521 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1522 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1523 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001524 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001525 assert(!argT.isNull() && "Can't find 'SEL' type");
1526 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001527 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001528 &ArgTys[0], ArgTys.size(),
1529 true /*isVariadic*/);
1530 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1531 msgSendIdent, msgSendType,
1532 FunctionDecl::Extern, false, 0);
1533}
1534
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001535// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1536void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1537 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1538 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001539 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001540 assert(!argT.isNull() && "Can't find 'id' type");
1541 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001542 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001543 assert(!argT.isNull() && "Can't find 'SEL' type");
1544 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001545 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001546 &ArgTys[0], ArgTys.size(),
1547 true /*isVariadic*/);
1548 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1549 msgSendIdent, msgSendType,
1550 FunctionDecl::Extern, false, 0);
1551}
1552
Steve Naroff02a82aa2007-10-30 23:14:51 +00001553// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1554void RewriteTest::SynthGetClassFunctionDecl() {
1555 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1556 llvm::SmallVector<QualType, 16> ArgTys;
1557 ArgTys.push_back(Context->getPointerType(
1558 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001559 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001560 &ArgTys[0], ArgTys.size(),
1561 false /*isVariadic*/);
1562 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1563 getClassIdent, getClassType,
1564 FunctionDecl::Extern, false, 0);
1565}
1566
Steve Naroff3b1caac2007-12-07 03:50:46 +00001567// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1568void RewriteTest::SynthGetMetaClassFunctionDecl() {
1569 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1570 llvm::SmallVector<QualType, 16> ArgTys;
1571 ArgTys.push_back(Context->getPointerType(
1572 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001573 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001574 &ArgTys[0], ArgTys.size(),
1575 false /*isVariadic*/);
1576 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1577 getClassIdent, getClassType,
1578 FunctionDecl::Extern, false, 0);
1579}
1580
Steve Naroffabb96362007-11-08 14:30:50 +00001581// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1582void RewriteTest::SynthCFStringFunctionDecl() {
1583 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1584 llvm::SmallVector<QualType, 16> ArgTys;
1585 ArgTys.push_back(Context->getPointerType(
1586 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001587 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001588 &ArgTys[0], ArgTys.size(),
1589 false /*isVariadic*/);
1590 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1591 getClassIdent, getClassType,
1592 FunctionDecl::Extern, false, 0);
1593}
1594
Steve Naroff0add5d22007-11-03 11:27:19 +00001595Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001596#if 1
1597 // This rewrite is specific to GCC, which has builtin support for CFString.
1598 if (!CFStringFunctionDecl)
1599 SynthCFStringFunctionDecl();
1600 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1601 llvm::SmallVector<Expr*, 8> StrExpr;
1602 StrExpr.push_back(Exp->getString());
1603 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1604 &StrExpr[0], StrExpr.size());
1605 // cast to NSConstantString *
1606 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001607 if (Rewrite.ReplaceStmt(Exp, cast)) {
1608 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001609 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001610 if (!SilenceRewriteMacroWarning)
1611 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
1612 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001613 }
Steve Naroffabb96362007-11-08 14:30:50 +00001614 delete Exp;
1615 return cast;
1616#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001617 assert(ConstantStringClassReference && "Can't find constant string reference");
1618 llvm::SmallVector<Expr*, 4> InitExprs;
1619
1620 // Synthesize "(Class)&_NSConstantStringClassReference"
1621 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1622 ConstantStringClassReference->getType(),
1623 SourceLocation());
1624 QualType expType = Context->getPointerType(ClsRef->getType());
1625 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1626 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001627 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001628 SourceLocation());
1629 InitExprs.push_back(cast); // set the 'isa'.
1630 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1631 unsigned IntSize = static_cast<unsigned>(
1632 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1633 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1634 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1635 Exp->getLocStart());
1636 InitExprs.push_back(len); // set "int numBytes".
1637
1638 // struct NSConstantString
1639 QualType CFConstantStrType = Context->getCFConstantStringType();
1640 // (struct NSConstantString) { <exprs from above> }
1641 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1642 &InitExprs[0], InitExprs.size(),
1643 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001644 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001645 // struct NSConstantString *
1646 expType = Context->getPointerType(StrRep->getType());
1647 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1648 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001649 // cast to NSConstantString *
1650 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001651 Rewrite.ReplaceStmt(Exp, cast);
1652 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001653 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001654#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001655}
1656
Ted Kremenek42730c52008-01-07 19:49:32 +00001657ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001658 // check if we are sending a message to 'super'
1659 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001660 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1661 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1662 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1663 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001664 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001665 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001666 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001667 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001668 if (ObjCInterfaceType *IT =
1669 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001670 if (IT->getDecl() ==
1671 CurMethodDecl->getClassInterface()->getSuperClass())
1672 return IT->getDecl();
1673 }
1674 }
1675 }
1676 }
1677 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001678 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001679 }
1680 return 0;
1681}
1682
1683// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1684QualType RewriteTest::getSuperStructType() {
1685 if (!SuperStructDecl) {
1686 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1687 &Context->Idents.get("objc_super"), 0);
1688 QualType FieldTypes[2];
1689
1690 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001691 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001692 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001693 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001694 // Create fields
1695 FieldDecl *FieldDecls[2];
1696
1697 for (unsigned i = 0; i < 2; ++i)
1698 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1699
1700 SuperStructDecl->defineBody(FieldDecls, 4);
1701 }
1702 return Context->getTagDeclType(SuperStructDecl);
1703}
1704
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001705Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001706 if (!SelGetUidFunctionDecl)
1707 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001708 if (!MsgSendFunctionDecl)
1709 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001710 if (!MsgSendSuperFunctionDecl)
1711 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001712 if (!MsgSendStretFunctionDecl)
1713 SynthMsgSendStretFunctionDecl();
1714 if (!MsgSendSuperStretFunctionDecl)
1715 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001716 if (!MsgSendFpretFunctionDecl)
1717 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001718 if (!GetClassFunctionDecl)
1719 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001720 if (!GetMetaClassFunctionDecl)
1721 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001722
Steve Naroff764c1ae2007-11-15 10:28:18 +00001723 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001724 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1725 // May need to use objc_msgSend_stret() as well.
1726 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001727 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001728 QualType resultType = mDecl->getResultType();
1729 if (resultType.getCanonicalType()->isStructureType()
1730 || resultType.getCanonicalType()->isUnionType())
1731 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001732 else if (resultType.getCanonicalType()->isRealFloatingType())
1733 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001734 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001735
Steve Naroff71226032007-10-24 22:48:43 +00001736 // Synthesize a call to objc_msgSend().
1737 llvm::SmallVector<Expr*, 8> MsgExprs;
1738 IdentifierInfo *clsName = Exp->getClassName();
1739
1740 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1741 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001742 if (!strcmp(clsName->getName(), "super")) {
1743 MsgSendFlavor = MsgSendSuperFunctionDecl;
1744 if (MsgSendStretFlavor)
1745 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1746 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1747
Ted Kremenek42730c52008-01-07 19:49:32 +00001748 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001749 CurMethodDecl->getClassInterface()->getSuperClass();
1750
1751 llvm::SmallVector<Expr*, 4> InitExprs;
1752
1753 // set the receiver to self, the first argument to all methods.
1754 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001755 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001756 SourceLocation()));
1757 llvm::SmallVector<Expr*, 8> ClsExprs;
1758 QualType argType = Context->getPointerType(Context->CharTy);
1759 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1760 SuperDecl->getIdentifier()->getLength(),
1761 false, argType, SourceLocation(),
1762 SourceLocation()));
1763 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1764 &ClsExprs[0],
1765 ClsExprs.size());
1766 // To turn off a warning, type-cast to 'id'
1767 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001768 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001769 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1770 // struct objc_super
1771 QualType superType = getSuperStructType();
1772 // (struct objc_super) { <exprs from above> }
1773 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1774 &InitExprs[0], InitExprs.size(),
1775 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001776 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001777 superType, ILE, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001778 // struct objc_super *
1779 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1780 Context->getPointerType(SuperRep->getType()),
1781 SourceLocation());
1782 MsgExprs.push_back(Unop);
1783 } else {
1784 llvm::SmallVector<Expr*, 8> ClsExprs;
1785 QualType argType = Context->getPointerType(Context->CharTy);
1786 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1787 clsName->getLength(),
1788 false, argType, SourceLocation(),
1789 SourceLocation()));
1790 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1791 &ClsExprs[0],
1792 ClsExprs.size());
1793 MsgExprs.push_back(Cls);
1794 }
Steve Naroff885e2122007-11-14 23:54:14 +00001795 } else { // instance message.
1796 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001797
Ted Kremenek42730c52008-01-07 19:49:32 +00001798 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001799 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001800 if (MsgSendStretFlavor)
1801 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001802 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1803
1804 llvm::SmallVector<Expr*, 4> InitExprs;
1805
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001806 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001808 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001809
1810 llvm::SmallVector<Expr*, 8> ClsExprs;
1811 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001812 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1813 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001814 false, argType, SourceLocation(),
1815 SourceLocation()));
1816 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001817 &ClsExprs[0],
1818 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001819 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001820 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001821 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001822 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001823 // struct objc_super
1824 QualType superType = getSuperStructType();
1825 // (struct objc_super) { <exprs from above> }
1826 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1827 &InitExprs[0], InitExprs.size(),
1828 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001829 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001830 superType, ILE, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001831 // struct objc_super *
1832 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1833 Context->getPointerType(SuperRep->getType()),
1834 SourceLocation());
1835 MsgExprs.push_back(Unop);
1836 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001837 // Remove all type-casts because it may contain objc-style types; e.g.
1838 // Foo<Proto> *.
1839 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1840 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001841 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001842 MsgExprs.push_back(recExpr);
1843 }
Steve Naroff885e2122007-11-14 23:54:14 +00001844 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001845 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001846 llvm::SmallVector<Expr*, 8> SelExprs;
1847 QualType argType = Context->getPointerType(Context->CharTy);
1848 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1849 Exp->getSelector().getName().size(),
1850 false, argType, SourceLocation(),
1851 SourceLocation()));
1852 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1853 &SelExprs[0], SelExprs.size());
1854 MsgExprs.push_back(SelExp);
1855
1856 // Now push any user supplied arguments.
1857 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001858 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001859 // Make all implicit casts explicit...ICE comes in handy:-)
1860 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1861 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001862 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1863 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001864 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001865 }
1866 // Make id<P...> cast into an 'id' cast.
1867 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001868 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001869 while ((CE = dyn_cast<CastExpr>(userExpr)))
1870 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001871 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001872 userExpr, SourceLocation());
1873 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001874 }
Steve Naroff885e2122007-11-14 23:54:14 +00001875 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001876 // We've transferred the ownership to MsgExprs. Null out the argument in
1877 // the original expression, since we will delete it below.
1878 Exp->setArg(i, 0);
1879 }
Steve Naroff0744c472007-11-04 22:37:50 +00001880 // Generate the funky cast.
1881 CastExpr *cast;
1882 llvm::SmallVector<QualType, 8> ArgTypes;
1883 QualType returnType;
1884
1885 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001886 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1887 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1888 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001889 ArgTypes.push_back(Context->getObjCIdType());
1890 ArgTypes.push_back(Context->getObjCSelType());
1891 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001892 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001893 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001894 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1895 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001896 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001897 ArgTypes.push_back(t);
1898 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001899 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1900 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001901 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001902 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001903 }
1904 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001905 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001906
1907 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001908 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1909 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001910
1911 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1912 // If we don't do this cast, we get the following bizarre warning/note:
1913 // xx.m:13: warning: function called through a non-compatible type
1914 // xx.m:13: note: if this code is reached, the program will abort
1915 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1916 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001917
Steve Naroff0744c472007-11-04 22:37:50 +00001918 // Now do the "normal" pointer to function cast.
1919 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001920 &ArgTypes[0], ArgTypes.size(),
1921 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001922 castType = Context->getPointerType(castType);
1923 cast = new CastExpr(castType, cast, SourceLocation());
1924
1925 // Don't forget the parens to enforce the proper binding.
1926 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1927
1928 const FunctionType *FT = msgSendType->getAsFunctionType();
1929 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1930 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001931 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001932 if (MsgSendStretFlavor) {
1933 // We have the method which returns a struct/union. Must also generate
1934 // call to objc_msgSend_stret and hang both varieties on a conditional
1935 // expression which dictate which one to envoke depending on size of
1936 // method's return type.
1937
1938 // Create a reference to the objc_msgSend_stret() declaration.
1939 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1940 SourceLocation());
1941 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1942 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1943 SourceLocation());
1944 // Now do the "normal" pointer to function cast.
1945 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001946 &ArgTypes[0], ArgTypes.size(),
1947 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001948 castType = Context->getPointerType(castType);
1949 cast = new CastExpr(castType, cast, SourceLocation());
1950
1951 // Don't forget the parens to enforce the proper binding.
1952 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1953
1954 FT = msgSendType->getAsFunctionType();
1955 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1956 FT->getResultType(), SourceLocation());
1957
1958 // Build sizeof(returnType)
1959 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1960 returnType, Context->getSizeType(),
1961 SourceLocation(), SourceLocation());
1962 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1963 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1964 // For X86 it is more complicated and some kind of target specific routine
1965 // is needed to decide what to do.
1966 unsigned IntSize = static_cast<unsigned>(
1967 Context->getTypeSize(Context->IntTy, SourceLocation()));
1968
1969 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1970 Context->IntTy,
1971 SourceLocation());
1972 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1973 BinaryOperator::LE,
1974 Context->IntTy,
1975 SourceLocation());
1976 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1977 ConditionalOperator *CondExpr =
1978 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001979 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001980 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001981 return ReplacingStmt;
1982}
1983
1984Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1985 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00001986 // Now do the actual rewrite.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001987 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroffe4e5e262007-12-19 14:32:56 +00001988 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001989 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001990 if (!SilenceRewriteMacroWarning)
1991 Diags.Report(Context->getFullLoc(Exp->getLocStart()), RewriteFailedDiag,
1992 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001993 }
Steve Naroff71226032007-10-24 22:48:43 +00001994
Chris Lattner0021f452007-10-24 16:57:36 +00001995 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001996 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00001997}
1998
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001999/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2000/// call to objc_getProtocol("proto-name").
2001Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2002 if (!GetProtocolFunctionDecl)
2003 SynthGetProtocolFunctionDecl();
2004 // Create a call to objc_getProtocol("ProtocolName").
2005 llvm::SmallVector<Expr*, 8> ProtoExprs;
2006 QualType argType = Context->getPointerType(Context->CharTy);
2007 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2008 strlen(Exp->getProtocol()->getName()),
2009 false, argType, SourceLocation(),
2010 SourceLocation()));
2011 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2012 &ProtoExprs[0],
2013 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00002014 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
2015 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00002016 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00002017 if (!SilenceRewriteMacroWarning)
2018 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
2019 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002020 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002021 delete Exp;
2022 return ProtoExp;
2023
2024}
2025
Ted Kremenek42730c52008-01-07 19:49:32 +00002026/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002027/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002028void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002029 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002030 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2031 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002032 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002033 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002034 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002035 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002036 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002037 SourceLocation LocStart = CDecl->getLocStart();
2038 SourceLocation LocEnd = CDecl->getLocEnd();
2039
2040 const char *startBuf = SM->getCharacterData(LocStart);
2041 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002042 // If no ivars and no root or if its root, directly or indirectly,
2043 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002044 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002045 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2046 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2047 Result.c_str(), Result.size());
2048 return;
2049 }
2050
2051 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002052 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002053 Result += "\nstruct ";
2054 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002055
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002056 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002057 const char *cursor = strchr(startBuf, '{');
2058 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002059 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002060
2061 // rewrite the original header *without* disturbing the '{'
2062 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2063 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002064 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002065 Result = "\n struct ";
2066 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00002067 // Note: We don't name the field decl. This simplifies the "codegen" for
2068 // accessing a superclasses instance variables (and is similar to what gcc
2069 // does internally). The unnamed struct field feature is enabled with
2070 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2071 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002072 Result += ";\n";
2073
2074 // insert the super class structure definition.
2075 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2076 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2077 }
2078 cursor++; // past '{'
2079
2080 // Now comment out any visibility specifiers.
2081 while (cursor < endBuf) {
2082 if (*cursor == '@') {
2083 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002084 // Skip whitespace.
2085 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2086 /*scan*/;
2087
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002088 // FIXME: presence of @public, etc. inside comment results in
2089 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002090 if (!strncmp(cursor, "public", strlen("public")) ||
2091 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002092 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00002093 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002094 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002095 // FIXME: If there are cases where '<' is used in ivar declaration part
2096 // of user code, then scan the ivar list and use needToScanForQualifiers
2097 // for type checking.
2098 else if (*cursor == '<') {
2099 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2100 Rewrite.InsertText(atLoc, "/* ", 3);
2101 cursor = strchr(cursor, '>');
2102 cursor++;
2103 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2104 Rewrite.InsertText(atLoc, " */", 3);
2105 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002106 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002107 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002108 // Don't forget to add a ';'!!
2109 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2110 } else { // we don't have any instance variables - insert super struct.
2111 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2112 Result += " {\n struct ";
2113 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00002114 // Note: We don't name the field decl. This simplifies the "codegen" for
2115 // accessing a superclasses instance variables (and is similar to what gcc
2116 // does internally). The unnamed struct field feature is enabled with
2117 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2118 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002119 Result += ";\n};\n";
2120 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2121 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002122 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002123 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002124 if (!ObjCSynthesizedStructs.insert(CDecl))
2125 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002126}
2127
Ted Kremenek42730c52008-01-07 19:49:32 +00002128// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002129/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002130void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002131 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002132 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002133 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002134 const char *ClassName,
2135 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002136 if (MethodBegin == MethodEnd) return;
2137
Fariborz Jahanian04455192007-10-22 21:41:37 +00002138 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002139 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002140 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002141 SEL _cmd;
2142 char *method_types;
2143 void *_imp;
2144 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002145 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002146 Result += "\nstruct _objc_method {\n";
2147 Result += "\tSEL _cmd;\n";
2148 Result += "\tchar *method_types;\n";
2149 Result += "\tvoid *_imp;\n";
2150 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002151
2152 /* struct _objc_method_list {
2153 struct _objc_method_list *next_method;
2154 int method_count;
2155 struct _objc_method method_list[];
2156 }
2157 */
2158 Result += "\nstruct _objc_method_list {\n";
2159 Result += "\tstruct _objc_method_list *next_method;\n";
2160 Result += "\tint method_count;\n";
2161 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002162 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002163 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002164
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002165 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002166 Result += "\nstatic struct _objc_method_list _OBJC_";
2167 Result += prefix;
2168 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2169 Result += "_METHODS_";
2170 Result += ClassName;
2171 Result += " __attribute__ ((section (\"__OBJC, __";
2172 Result += IsInstanceMethod ? "inst" : "cls";
2173 Result += "_meth\")))= ";
2174 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002175
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002176 Result += "\t,{{(SEL)\"";
2177 Result += (*MethodBegin)->getSelector().getName().c_str();
2178 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002179 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002180 Result += "\", \"";
2181 Result += MethodTypeString;
2182 Result += "\", ";
2183 Result += MethodInternalNames[*MethodBegin];
2184 Result += "}\n";
2185 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2186 Result += "\t ,{(SEL)\"";
2187 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002188 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002189 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002190 Result += "\", \"";
2191 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002192 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002193 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002194 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002195 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002196 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002197}
2198
Ted Kremenek42730c52008-01-07 19:49:32 +00002199/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2200void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002201 int NumProtocols,
2202 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002203 const char *ClassName,
2204 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002205 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002206 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002207 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002208 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002209 // Output struct protocol_methods holder of method selector and type.
2210 if (!objc_protocol_methods &&
2211 (PDecl->getNumInstanceMethods() > 0
2212 || PDecl->getNumClassMethods() > 0)) {
2213 /* struct protocol_methods {
2214 SEL _cmd;
2215 char *method_types;
2216 }
2217 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002218 Result += "\nstruct protocol_methods {\n";
2219 Result += "\tSEL _cmd;\n";
2220 Result += "\tchar *method_types;\n";
2221 Result += "};\n";
2222
2223 /* struct _objc_protocol_method_list {
2224 int protocol_method_count;
2225 struct protocol_methods protocols[];
2226 }
2227 */
2228 Result += "\nstruct _objc_protocol_method_list {\n";
2229 Result += "\tint protocol_method_count;\n";
2230 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002231 objc_protocol_methods = true;
2232 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002233
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002234 int NumMethods = PDecl->getNumInstanceMethods();
2235 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002236 Result += "\nstatic struct _objc_protocol_method_list "
2237 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2238 Result += PDecl->getName();
2239 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2240 "{\n\t" + utostr(NumMethods) + "\n";
2241
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002242 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002243 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002244 E = PDecl->instmeth_end(); I != E; ++I) {
2245 if (I == PDecl->instmeth_begin())
2246 Result += "\t ,{{(SEL)\"";
2247 else
2248 Result += "\t ,{(SEL)\"";
2249 Result += (*I)->getSelector().getName().c_str();
2250 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002251 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002252 Result += "\", \"";
2253 Result += MethodTypeString;
2254 Result += "\"}\n";
2255 }
2256 Result += "\t }\n};\n";
2257 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002258
2259 // Output class methods declared in this protocol.
2260 NumMethods = PDecl->getNumClassMethods();
2261 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002262 Result += "\nstatic struct _objc_protocol_method_list "
2263 "_OBJC_PROTOCOL_CLASS_METHODS_";
2264 Result += PDecl->getName();
2265 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2266 "{\n\t";
2267 Result += utostr(NumMethods);
2268 Result += "\n";
2269
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002270 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002271 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002272 E = PDecl->classmeth_end(); I != E; ++I) {
2273 if (I == PDecl->classmeth_begin())
2274 Result += "\t ,{{(SEL)\"";
2275 else
2276 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002277 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002278 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002279 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002280 Result += "\", \"";
2281 Result += MethodTypeString;
2282 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002283 }
2284 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002285 }
2286 // Output:
2287 /* struct _objc_protocol {
2288 // Objective-C 1.0 extensions
2289 struct _objc_protocol_extension *isa;
2290 char *protocol_name;
2291 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002292 struct _objc_protocol_method_list *instance_methods;
2293 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002294 };
2295 */
2296 static bool objc_protocol = false;
2297 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002298 Result += "\nstruct _objc_protocol {\n";
2299 Result += "\tstruct _objc_protocol_extension *isa;\n";
2300 Result += "\tchar *protocol_name;\n";
2301 Result += "\tstruct _objc_protocol **protocol_list;\n";
2302 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2303 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2304 Result += "};\n";
2305
2306 /* struct _objc_protocol_list {
2307 struct _objc_protocol_list *next;
2308 int protocol_count;
2309 struct _objc_protocol *class_protocols[];
2310 }
2311 */
2312 Result += "\nstruct _objc_protocol_list {\n";
2313 Result += "\tstruct _objc_protocol_list *next;\n";
2314 Result += "\tint protocol_count;\n";
2315 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2316 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002317 objc_protocol = true;
2318 }
2319
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002320 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2321 Result += PDecl->getName();
2322 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2323 "{\n\t0, \"";
2324 Result += PDecl->getName();
2325 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002326 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002327 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2328 Result += PDecl->getName();
2329 Result += ", ";
2330 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002331 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002332 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002333 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002334 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2335 Result += PDecl->getName();
2336 Result += "\n";
2337 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002338 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002339 Result += "0\n";
2340 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002341 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002342 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002343 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2344 Result += prefix;
2345 Result += "_PROTOCOLS_";
2346 Result += ClassName;
2347 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2348 "{\n\t0, ";
2349 Result += utostr(NumProtocols);
2350 Result += "\n";
2351
2352 Result += "\t,{&_OBJC_PROTOCOL_";
2353 Result += Protocols[0]->getName();
2354 Result += " \n";
2355
2356 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002357 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002358 Result += "\t ,&_OBJC_PROTOCOL_";
2359 Result += PDecl->getName();
2360 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002361 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002362 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002363 }
2364}
2365
Ted Kremenek42730c52008-01-07 19:49:32 +00002366/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002367/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002368void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002369 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002370 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002371 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002372 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002373 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2374 CDecl = CDecl->getNextClassCategory())
2375 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2376 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002377
Chris Lattnera661a4d2007-12-23 01:40:15 +00002378 std::string FullCategoryName = ClassDecl->getName();
2379 FullCategoryName += '_';
2380 FullCategoryName += IDecl->getName();
2381
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002382 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002383 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002384 true, "CATEGORY_", FullCategoryName.c_str(),
2385 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002386
2387 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002388 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002389 false, "CATEGORY_", FullCategoryName.c_str(),
2390 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002391
2392 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002393 // Null CDecl is case of a category implementation with no category interface
2394 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002395 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002396 CDecl->getNumReferencedProtocols(),
2397 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002398 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002399
2400 /* struct _objc_category {
2401 char *category_name;
2402 char *class_name;
2403 struct _objc_method_list *instance_methods;
2404 struct _objc_method_list *class_methods;
2405 struct _objc_protocol_list *protocols;
2406 // Objective-C 1.0 extensions
2407 uint32_t size; // sizeof (struct _objc_category)
2408 struct _objc_property_list *instance_properties; // category's own
2409 // @property decl.
2410 };
2411 */
2412
2413 static bool objc_category = false;
2414 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002415 Result += "\nstruct _objc_category {\n";
2416 Result += "\tchar *category_name;\n";
2417 Result += "\tchar *class_name;\n";
2418 Result += "\tstruct _objc_method_list *instance_methods;\n";
2419 Result += "\tstruct _objc_method_list *class_methods;\n";
2420 Result += "\tstruct _objc_protocol_list *protocols;\n";
2421 Result += "\tunsigned int size;\n";
2422 Result += "\tstruct _objc_property_list *instance_properties;\n";
2423 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002424 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002425 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002426 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2427 Result += FullCategoryName;
2428 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2429 Result += IDecl->getName();
2430 Result += "\"\n\t, \"";
2431 Result += ClassDecl->getName();
2432 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002433
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002434 if (IDecl->getNumInstanceMethods() > 0) {
2435 Result += "\t, (struct _objc_method_list *)"
2436 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2437 Result += FullCategoryName;
2438 Result += "\n";
2439 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002440 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002441 Result += "\t, 0\n";
2442 if (IDecl->getNumClassMethods() > 0) {
2443 Result += "\t, (struct _objc_method_list *)"
2444 "&_OBJC_CATEGORY_CLASS_METHODS_";
2445 Result += FullCategoryName;
2446 Result += "\n";
2447 }
2448 else
2449 Result += "\t, 0\n";
2450
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002451 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002452 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2453 Result += FullCategoryName;
2454 Result += "\n";
2455 }
2456 else
2457 Result += "\t, 0\n";
2458 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002459}
2460
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002461/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2462/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002463void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2464 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002465 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002466 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002467 Result += IDecl->getName();
2468 Result += ", ";
2469 Result += ivar->getName();
2470 Result += ")";
2471}
2472
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002473//===----------------------------------------------------------------------===//
2474// Meta Data Emission
2475//===----------------------------------------------------------------------===//
2476
Ted Kremenek42730c52008-01-07 19:49:32 +00002477void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002478 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002479 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002480
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002481 // Explictly declared @interface's are already synthesized.
2482 if (CDecl->ImplicitInterfaceDecl()) {
2483 // FIXME: Implementation of a class with no @interface (legacy) doese not
2484 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002485 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002486 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002487
Chris Lattnerc7b06752007-12-12 07:56:42 +00002488 // Build _objc_ivar_list metadata for classes ivars if needed
2489 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2490 ? IDecl->getImplDeclNumIvars()
2491 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002492 if (NumIvars > 0) {
2493 static bool objc_ivar = false;
2494 if (!objc_ivar) {
2495 /* struct _objc_ivar {
2496 char *ivar_name;
2497 char *ivar_type;
2498 int ivar_offset;
2499 };
2500 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002501 Result += "\nstruct _objc_ivar {\n";
2502 Result += "\tchar *ivar_name;\n";
2503 Result += "\tchar *ivar_type;\n";
2504 Result += "\tint ivar_offset;\n";
2505 Result += "};\n";
2506
2507 /* struct _objc_ivar_list {
2508 int ivar_count;
2509 struct _objc_ivar ivar_list[];
2510 };
2511 */
2512 Result += "\nstruct _objc_ivar_list {\n";
2513 Result += "\tint ivar_count;\n";
2514 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002515 objc_ivar = true;
2516 }
2517
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002518 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2519 Result += IDecl->getName();
2520 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2521 "{\n\t";
2522 Result += utostr(NumIvars);
2523 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002524
Ted Kremenek42730c52008-01-07 19:49:32 +00002525 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002526 if (IDecl->getImplDeclNumIvars() > 0) {
2527 IVI = IDecl->ivar_begin();
2528 IVE = IDecl->ivar_end();
2529 } else {
2530 IVI = CDecl->ivar_begin();
2531 IVE = CDecl->ivar_end();
2532 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002533 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002534 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002535 Result += "\", \"";
2536 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002537 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2538 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002539 Result += StrEncoding;
2540 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002541 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002542 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002543 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002544 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002545 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002546 Result += "\", \"";
2547 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002548 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2549 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002550 Result += StrEncoding;
2551 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002552 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002553 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002554 }
2555
2556 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002557 }
2558
2559 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002560 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002561 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002562
2563 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002564 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002565 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002566
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002567 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002568 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002569 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002570 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002571
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002572
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002573 // Declaration of class/meta-class metadata
2574 /* struct _objc_class {
2575 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002576 const char *super_class_name;
2577 char *name;
2578 long version;
2579 long info;
2580 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002581 struct _objc_ivar_list *ivars;
2582 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002583 struct objc_cache *cache;
2584 struct objc_protocol_list *protocols;
2585 const char *ivar_layout;
2586 struct _objc_class_ext *ext;
2587 };
2588 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002589 static bool objc_class = false;
2590 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002591 Result += "\nstruct _objc_class {\n";
2592 Result += "\tstruct _objc_class *isa;\n";
2593 Result += "\tconst char *super_class_name;\n";
2594 Result += "\tchar *name;\n";
2595 Result += "\tlong version;\n";
2596 Result += "\tlong info;\n";
2597 Result += "\tlong instance_size;\n";
2598 Result += "\tstruct _objc_ivar_list *ivars;\n";
2599 Result += "\tstruct _objc_method_list *methods;\n";
2600 Result += "\tstruct objc_cache *cache;\n";
2601 Result += "\tstruct _objc_protocol_list *protocols;\n";
2602 Result += "\tconst char *ivar_layout;\n";
2603 Result += "\tstruct _objc_class_ext *ext;\n";
2604 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002605 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002606 }
2607
2608 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002609 ObjCInterfaceDecl *RootClass = 0;
2610 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002611 while (SuperClass) {
2612 RootClass = SuperClass;
2613 SuperClass = SuperClass->getSuperClass();
2614 }
2615 SuperClass = CDecl->getSuperClass();
2616
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002617 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2618 Result += CDecl->getName();
2619 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2620 "{\n\t(struct _objc_class *)\"";
2621 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2622 Result += "\"";
2623
2624 if (SuperClass) {
2625 Result += ", \"";
2626 Result += SuperClass->getName();
2627 Result += "\", \"";
2628 Result += CDecl->getName();
2629 Result += "\"";
2630 }
2631 else {
2632 Result += ", 0, \"";
2633 Result += CDecl->getName();
2634 Result += "\"";
2635 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002636 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002637 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002638 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002639 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002640 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002641 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002642 Result += "\n";
2643 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002644 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002645 Result += ", 0\n";
2646 if (CDecl->getNumIntfRefProtocols() > 0) {
2647 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2648 Result += CDecl->getName();
2649 Result += ",0,0\n";
2650 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002651 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002652 Result += "\t,0,0,0,0\n";
2653 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002654
2655 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002656 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2657 Result += CDecl->getName();
2658 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2659 "{\n\t&_OBJC_METACLASS_";
2660 Result += CDecl->getName();
2661 if (SuperClass) {
2662 Result += ", \"";
2663 Result += SuperClass->getName();
2664 Result += "\", \"";
2665 Result += CDecl->getName();
2666 Result += "\"";
2667 }
2668 else {
2669 Result += ", 0, \"";
2670 Result += CDecl->getName();
2671 Result += "\"";
2672 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002673 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002674 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002675 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002676 Result += ",0";
2677 else {
2678 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002679 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002680 Result += CDecl->getName();
2681 Result += ")";
2682 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002683 if (NumIvars > 0) {
2684 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2685 Result += CDecl->getName();
2686 Result += "\n\t";
2687 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002688 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002689 Result += ",0";
2690 if (IDecl->getNumInstanceMethods() > 0) {
2691 Result += ", &_OBJC_INSTANCE_METHODS_";
2692 Result += CDecl->getName();
2693 Result += ", 0\n\t";
2694 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002695 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002696 Result += ",0,0";
2697 if (CDecl->getNumIntfRefProtocols() > 0) {
2698 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2699 Result += CDecl->getName();
2700 Result += ", 0,0\n";
2701 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002702 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002703 Result += ",0,0,0\n";
2704 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002705}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002706
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002707/// RewriteImplementations - This routine rewrites all method implementations
2708/// and emits meta-data.
2709
2710void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002711 int ClsDefCount = ClassImplementation.size();
2712 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002713
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002714 if (ClsDefCount == 0 && CatDefCount == 0)
2715 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002716 // Rewrite implemented methods
2717 for (int i = 0; i < ClsDefCount; i++)
2718 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002719
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002720 for (int i = 0; i < CatDefCount; i++)
2721 RewriteImplementationDecl(CategoryImplementation[i]);
2722
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002723 // This is needed for use of offsetof
2724 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002725
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002726 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002727 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002728 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002729
2730 // For each implemented category, write out all its meta data.
2731 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002732 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002733
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002734 // Write objc_symtab metadata
2735 /*
2736 struct _objc_symtab
2737 {
2738 long sel_ref_cnt;
2739 SEL *refs;
2740 short cls_def_cnt;
2741 short cat_def_cnt;
2742 void *defs[cls_def_cnt + cat_def_cnt];
2743 };
2744 */
2745
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002746 Result += "\nstruct _objc_symtab {\n";
2747 Result += "\tlong sel_ref_cnt;\n";
2748 Result += "\tSEL *refs;\n";
2749 Result += "\tshort cls_def_cnt;\n";
2750 Result += "\tshort cat_def_cnt;\n";
2751 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2752 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002753
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002754 Result += "static struct _objc_symtab "
2755 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2756 Result += "\t0, 0, " + utostr(ClsDefCount)
2757 + ", " + utostr(CatDefCount) + "\n";
2758 for (int i = 0; i < ClsDefCount; i++) {
2759 Result += "\t,&_OBJC_CLASS_";
2760 Result += ClassImplementation[i]->getName();
2761 Result += "\n";
2762 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002763
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002764 for (int i = 0; i < CatDefCount; i++) {
2765 Result += "\t,&_OBJC_CATEGORY_";
2766 Result += CategoryImplementation[i]->getClassInterface()->getName();
2767 Result += "_";
2768 Result += CategoryImplementation[i]->getName();
2769 Result += "\n";
2770 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002771
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002772 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002773
2774 // Write objc_module metadata
2775
2776 /*
2777 struct _objc_module {
2778 long version;
2779 long size;
2780 const char *name;
2781 struct _objc_symtab *symtab;
2782 }
2783 */
2784
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002785 Result += "\nstruct _objc_module {\n";
2786 Result += "\tlong version;\n";
2787 Result += "\tlong size;\n";
2788 Result += "\tconst char *name;\n";
2789 Result += "\tstruct _objc_symtab *symtab;\n";
2790 Result += "};\n\n";
2791 Result += "static struct _objc_module "
2792 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002793 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2794 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002795 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002796
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002797}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002798