blob: 2b6c08c49a7677bd62a9c1c0b3c3281a06193674 [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 Naroff7fd0aff2008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
40
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000041 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000042 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000043 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
50 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000051 llvm::SmallVector<Stmt *, 32> Stmts;
52 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000053 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000054
55 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000056 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000057 FunctionDecl *MsgSendStretFunctionDecl;
58 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000059 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000060 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000061 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000062 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000063 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000064 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000065 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066
Steve Naroff0add5d22007-11-03 11:27:19 +000067 // ObjC string constant support.
68 FileVarDecl *ConstantStringClassReference;
69 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000070
Fariborz Jahanian22277422008-01-16 00:09:11 +000071 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000072 int BcLabelCount;
73
Steve Naroff764c1ae2007-11-15 10:28:18 +000074 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000075 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000076 RecordDecl *SuperStructDecl;
77
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000078 // Needed for header files being rewritten
79 bool IsHeader;
80
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000081 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000082 public:
Chris Lattner12499682008-01-31 19:38:44 +000083 void Initialize(ASTContext &context);
84
Chris Lattner569faa62007-10-11 18:38:32 +000085
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000086 // Top Level Driver code.
87 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000088 void HandleDeclInMainFile(Decl *D);
Steve Naroff7fd0aff2008-03-10 20:43:59 +000089 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
90 Diags(D), LangOpts(LOpts) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +000091 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +000092 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
93 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +000094 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000095 ~RewriteTest();
Chris Lattnerb1548372008-01-31 19:37:57 +000096
97 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +000098 // If replacement succeeded or warning disabled return with no warning.
99 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000100 return;
101
Chris Lattnerb1548372008-01-31 19:37:57 +0000102 SourceRange Range = Old->getSourceRange();
103 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
104 0, 0, &Range, 1);
105 }
106
Chris Lattner6216f292008-01-31 19:42:41 +0000107 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000108 // If insertion succeeded or warning disabled return with no warning.
Chris Lattner6216f292008-01-31 19:42:41 +0000109 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
110 SilenceRewriteMacroWarning)
111 return;
112
113 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
114 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000115
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000116 void RemoveText(SourceLocation Loc, unsigned StrLen) {
117 // If removal succeeded or warning disabled return with no warning.
118 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000123
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000124 void ReplaceText(SourceLocation Start, unsigned OrigLength,
125 const char *NewStr, unsigned NewLength) {
126 // If removal succeeded or warning disabled return with no warning.
127 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
128 SilenceRewriteMacroWarning)
129 return;
130
131 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
132 }
133
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000135 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000136 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000137 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000138 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
139 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000140 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000141 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
142 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
144 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
145 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
146 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000147 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000148 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000149 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000150 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000151 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000152
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000153 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000154 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000155 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000156 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000157 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000158 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000159 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000160 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000161 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000162 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000163 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
164 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
165 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000166 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
167 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000170 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000171 Stmt *RewriteBreakStmt(BreakStmt *S);
172 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000173 void SynthCountByEnumWithState(std::string &buf);
174
Steve Naroff02a82aa2007-10-30 23:14:51 +0000175 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000176 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000177 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000178 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000179 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000180 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000181 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000182 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000183 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000184 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000185 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000186
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000187 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000188 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000189 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000190
Ted Kremenek42730c52008-01-07 19:49:32 +0000191 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000192 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000193
Ted Kremenek42730c52008-01-07 19:49:32 +0000194 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
195 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000196 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000197 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000198 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000199 const char *ClassName,
200 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000201
Ted Kremenek42730c52008-01-07 19:49:32 +0000202 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000203 int NumProtocols,
204 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000205 const char *ClassName,
206 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000207 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000208 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000209 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
210 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000211 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000212 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000213 };
214}
215
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000216static bool IsHeaderFile(const std::string &Filename) {
217 std::string::size_type DotPos = Filename.rfind('.');
218
219 if (DotPos == std::string::npos) {
220 // no file extension
221 return false;
222 }
223
224 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
225 // C header: .h
226 // C++ header: .hh or .H;
227 return Ext == "h" || Ext == "hh" || Ext == "H";
228}
229
230ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000231 Diagnostic &Diags,
232 const LangOptions &LOpts) {
233 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000234}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000235
Chris Lattner12499682008-01-31 19:38:44 +0000236void RewriteTest::Initialize(ASTContext &context) {
237 Context = &context;
238 SM = &Context->getSourceManager();
239 MsgSendFunctionDecl = 0;
240 MsgSendSuperFunctionDecl = 0;
241 MsgSendStretFunctionDecl = 0;
242 MsgSendSuperStretFunctionDecl = 0;
243 MsgSendFpretFunctionDecl = 0;
244 GetClassFunctionDecl = 0;
245 GetMetaClassFunctionDecl = 0;
246 SelGetUidFunctionDecl = 0;
247 CFStringFunctionDecl = 0;
248 GetProtocolFunctionDecl = 0;
249 ConstantStringClassReference = 0;
250 NSStringRecord = 0;
251 CurMethodDecl = 0;
252 SuperStructDecl = 0;
253 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000254 SuperContructorFunctionDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000255
256 // Get the ID and start/end of the main file.
257 MainFileID = SM->getMainFileID();
258 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
259 MainFileStart = MainBuf->getBufferStart();
260 MainFileEnd = MainBuf->getBufferEnd();
261
262
263 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000264
Chris Lattner12499682008-01-31 19:38:44 +0000265 // declaring objc_selector outside the parameter list removes a silly
266 // scope related warning...
Steve Naroffde0da102008-03-10 23:16:54 +0000267 std::string S = "#pragma once\n";
268 S += "struct objc_selector; struct objc_class;\n";
269 S += "#ifndef OBJC_SUPER\n";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000270 S += "struct objc_super { struct objc_object *object; ";
271 S += "struct objc_object *superClass; ";
272 if (LangOpts.Microsoft) {
273 // Add a constructor for creating temporary objects.
274 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
275 S += "object(o), superClass(s) {} ";
276 }
277 S += "};\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000278 S += "#define OBJC_SUPER\n";
279 S += "#endif\n";
280 S += "#ifndef _REWRITER_typedef_Protocol\n";
281 S += "typedef struct objc_object Protocol;\n";
282 S += "#define _REWRITER_typedef_Protocol\n";
283 S += "#endif\n";
284 S += "extern struct objc_object *objc_msgSend";
285 S += "(struct objc_object *, struct objc_selector *, ...);\n";
286 S += "extern struct objc_object *objc_msgSendSuper";
287 S += "(struct objc_super *, struct objc_selector *, ...);\n";
288 S += "extern struct objc_object *objc_msgSend_stret";
289 S += "(struct objc_object *, struct objc_selector *, ...);\n";
290 S += "extern struct objc_object *objc_msgSendSuper_stret";
291 S += "(struct objc_super *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSend_fpret";
293 S += "(struct objc_object *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_getClass";
295 S += "(const char *);\n";
296 S += "extern struct objc_object *objc_getMetaClass";
297 S += "(const char *);\n";
298 S += "extern void objc_exception_throw(struct objc_object *);\n";
299 S += "extern void objc_exception_try_enter(void *);\n";
300 S += "extern void objc_exception_try_exit(void *);\n";
301 S += "extern struct objc_object *objc_exception_extract(void *);\n";
302 S += "extern int objc_exception_match";
303 S += "(struct objc_class *, struct objc_object *, ...);\n";
304 S += "extern Protocol *objc_getProtocol(const char *);\n";
305 S += "#include <objc/objc.h>\n";
306 S += "#ifndef __FASTENUMERATIONSTATE\n";
307 S += "struct __objcFastEnumerationState {\n\t";
308 S += "unsigned long state;\n\t";
309 S += "id *itemsPtr;\n\t";
310 S += "unsigned long *mutationsPtr;\n\t";
311 S += "unsigned long extra[5];\n};\n";
312 S += "#define __FASTENUMERATIONSTATE\n";
313 S += "#endif\n";
314#if 0
315 if (LangOpts.Microsoft)
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000316 S += "#define __attribute__(X)\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000317#endif
Chris Lattner12499682008-01-31 19:38:44 +0000318 if (IsHeader) {
319 // insert the whole string when rewriting a header file
Steve Naroffde0da102008-03-10 23:16:54 +0000320 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner12499682008-01-31 19:38:44 +0000321 }
322 else {
323 // Not rewriting header, exclude the #pragma once pragma
Steve Naroffde0da102008-03-10 23:16:54 +0000324 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattner6216f292008-01-31 19:42:41 +0000325 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner12499682008-01-31 19:38:44 +0000326 }
327}
328
329
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000330//===----------------------------------------------------------------------===//
331// Top Level Driver Code
332//===----------------------------------------------------------------------===//
333
Chris Lattner569faa62007-10-11 18:38:32 +0000334void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000335 // Two cases: either the decl could be in the main file, or it could be in a
336 // #included file. If the former, rewrite it now. If the later, check to see
337 // if we rewrote the #include/#import.
338 SourceLocation Loc = D->getLocation();
339 Loc = SM->getLogicalLoc(Loc);
340
341 // If this is for a builtin, ignore it.
342 if (Loc.isInvalid()) return;
343
Steve Naroffe9780582007-10-23 23:50:29 +0000344 // Look for built-in declarations that we need to refer during the rewrite.
345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000346 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000347 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
348 // declared in <Foundation/NSString.h>
349 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
350 ConstantStringClassReference = FVD;
351 return;
352 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000353 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000354 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000355 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000356 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000357 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000358 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000359 } else if (ObjCForwardProtocolDecl *FP =
360 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000361 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000362 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000363 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000364 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
365 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000366}
367
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000368/// HandleDeclInMainFile - This is called for each top-level decl defined in the
369/// main file of the input.
370void RewriteTest::HandleDeclInMainFile(Decl *D) {
371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
372 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000373 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000374
Ted Kremenek42730c52008-01-07 19:49:32 +0000375 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000376 if (Stmt *Body = MD->getBody()) {
377 //Body->dump();
378 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000379 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000380 CurMethodDecl = 0;
381 }
Steve Naroff18c83382007-11-13 23:01:27 +0000382 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000383 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000384 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000385 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000386 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000387 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000388 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000389 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000390 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000391 if (VD->getInit())
392 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
393 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000394 // Nothing yet.
395}
396
397RewriteTest::~RewriteTest() {
398 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000399
400 // Rewrite tabs if we care.
401 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000402
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000403 RewriteInclude();
404
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000405 // Rewrite Objective-c meta data*
406 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000407 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000408
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000409 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
410 // we are done.
411 if (const RewriteBuffer *RewriteBuf =
412 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000413 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000414 std::string S(RewriteBuf->begin(), RewriteBuf->end());
415 printf("%s\n", S.c_str());
416 } else {
417 printf("No changes\n");
418 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000419 // Emit metadata.
420 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000421}
422
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000423//===----------------------------------------------------------------------===//
424// Syntactic (non-AST) Rewriting Code
425//===----------------------------------------------------------------------===//
426
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000427void RewriteTest::RewriteInclude() {
428 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
429 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
430 const char *MainBufStart = MainBuf.first;
431 const char *MainBufEnd = MainBuf.second;
432 size_t ImportLen = strlen("import");
433 size_t IncludeLen = strlen("include");
434
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000435 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000436 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
437 if (*BufPtr == '#') {
438 if (++BufPtr == MainBufEnd)
439 return;
440 while (*BufPtr == ' ' || *BufPtr == '\t')
441 if (++BufPtr == MainBufEnd)
442 return;
443 if (!strncmp(BufPtr, "import", ImportLen)) {
444 // replace import with include
445 SourceLocation ImportLoc =
446 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000447 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000448 BufPtr += ImportLen;
449 }
450 }
451 }
Chris Lattner74db1682007-10-16 21:07:07 +0000452}
453
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000454void RewriteTest::RewriteTabs() {
455 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
456 const char *MainBufStart = MainBuf.first;
457 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000458
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000459 // Loop over the whole file, looking for tabs.
460 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
461 if (*BufPtr != '\t')
462 continue;
463
464 // Okay, we found a tab. This tab will turn into at least one character,
465 // but it depends on which 'virtual column' it is in. Compute that now.
466 unsigned VCol = 0;
467 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
468 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
469 ++VCol;
470
471 // Okay, now that we know the virtual column, we know how many spaces to
472 // insert. We assume 8-character tab-stops.
473 unsigned Spaces = 8-(VCol & 7);
474
475 // Get the location of the tab.
476 SourceLocation TabLoc =
477 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
478
479 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000480 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000481 }
Chris Lattner569faa62007-10-11 18:38:32 +0000482}
483
484
Ted Kremenek42730c52008-01-07 19:49:32 +0000485void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000486 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000487 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000488
489 // Get the start location and compute the semi location.
490 SourceLocation startLoc = ClassDecl->getLocation();
491 const char *startBuf = SM->getCharacterData(startLoc);
492 const char *semiPtr = strchr(startBuf, ';');
493
494 // Translate to typedef's that forward reference structs with the same name
495 // as the class. As a convenience, we include the original declaration
496 // as a comment.
497 std::string typedefString;
498 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000499 typedefString.append(startBuf, semiPtr-startBuf+1);
500 typedefString += "\n";
501 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000502 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000503 typedefString += "#ifndef _REWRITER_typedef_";
504 typedefString += ForwardDecl->getName();
505 typedefString += "\n";
506 typedefString += "#define _REWRITER_typedef_";
507 typedefString += ForwardDecl->getName();
508 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000509 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000510 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000511 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000512 }
513
514 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000515 ReplaceText(startLoc, semiPtr-startBuf+1,
516 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000517}
518
Ted Kremenek42730c52008-01-07 19:49:32 +0000519void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000520 SourceLocation LocStart = Method->getLocStart();
521 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000522
Steve Naroff2ce399a2007-12-14 23:37:57 +0000523 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000524 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000525 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000526 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000527 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000528 }
529}
530
Ted Kremenek42730c52008-01-07 19:49:32 +0000531void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000532{
533 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000534 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000535 SourceLocation Loc = Property->getLocation();
536
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000537 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000538
539 // FIXME: handle properties that are declared across multiple lines.
540 }
541}
542
Ted Kremenek42730c52008-01-07 19:49:32 +0000543void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000544 SourceLocation LocStart = CatDecl->getLocStart();
545
546 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000547 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000548
Ted Kremenek42730c52008-01-07 19:49:32 +0000549 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000550 E = CatDecl->instmeth_end(); I != E; ++I)
551 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000552 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000553 E = CatDecl->classmeth_end(); I != E; ++I)
554 RewriteMethodDeclaration(*I);
555
Steve Naroff667f1682007-10-30 13:30:57 +0000556 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000557 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000558}
559
Ted Kremenek42730c52008-01-07 19:49:32 +0000560void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000561 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000562
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000563 SourceLocation LocStart = PDecl->getLocStart();
564
565 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000566 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000567
Ted Kremenek42730c52008-01-07 19:49:32 +0000568 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000569 E = PDecl->instmeth_end(); I != E; ++I)
570 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000571 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000572 E = PDecl->classmeth_end(); I != E; ++I)
573 RewriteMethodDeclaration(*I);
574
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000575 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000576 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000577 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000578
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000579 // Must comment out @optional/@required
580 const char *startBuf = SM->getCharacterData(LocStart);
581 const char *endBuf = SM->getCharacterData(LocEnd);
582 for (const char *p = startBuf; p < endBuf; p++) {
583 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
584 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000585 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000586 ReplaceText(OptionalLoc, strlen("@optional"),
587 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000588
589 }
590 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
591 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000592 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000593 ReplaceText(OptionalLoc, strlen("@required"),
594 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000595
596 }
597 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000598}
599
Ted Kremenek42730c52008-01-07 19:49:32 +0000600void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000601 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000602 if (LocStart.isInvalid())
603 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000604 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000605 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000606}
607
Ted Kremenek42730c52008-01-07 19:49:32 +0000608void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000609 std::string &ResultStr) {
610 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000611 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000612 ResultStr += "id";
613 else
614 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000615 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000616
617 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000618 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000619
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000620 if (OMD->isInstance())
621 NameStr += "_I_";
622 else
623 NameStr += "_C_";
624
625 NameStr += OMD->getClassInterface()->getName();
626 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000627
628 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000629 if (ObjCCategoryImplDecl *CID =
630 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000631 NameStr += CID->getName();
632 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000633 }
634 // Append selector names, replacing ':' with '_'
635 const char *selName = OMD->getSelector().getName().c_str();
636 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000637 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000638 else {
639 std::string selString = OMD->getSelector().getName();
640 int len = selString.size();
641 for (int i = 0; i < len; i++)
642 if (selString[i] == ':')
643 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000644 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000645 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000646 // Remember this name for metadata emission
647 MethodInternalNames[OMD] = NameStr;
648 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000649
650 // Rewrite arguments
651 ResultStr += "(";
652
653 // invisible arguments
654 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000655 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000656 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000657 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000658 ResultStr += "struct ";
Steve Naroffde0da102008-03-10 23:16:54 +0000659 ResultStr += OMD->getClassInterface()->getName();
660 if (LangOpts.Microsoft)
661 ResultStr += "_IMPL";
662 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000663 }
664 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000665 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000666
667 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000668 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000669 ResultStr += " _cmd";
670
671 // Method arguments.
672 for (int i = 0; i < OMD->getNumParams(); i++) {
673 ParmVarDecl *PDecl = OMD->getParamDecl(i);
674 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000675 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000676 ResultStr += "id";
677 else
678 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000679 ResultStr += " ";
680 ResultStr += PDecl->getName();
681 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000682 if (OMD->isVariadic())
683 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000684 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000685
686}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000687void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000688 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
689 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000690
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000691 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000692 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000693 else
Chris Lattner6216f292008-01-31 19:42:41 +0000694 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000695
Ted Kremenek42730c52008-01-07 19:49:32 +0000696 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000697 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
698 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000699 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000700 ObjCMethodDecl *OMD = *I;
701 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000702 SourceLocation LocStart = OMD->getLocStart();
703 SourceLocation LocEnd = OMD->getBody()->getLocStart();
704
705 const char *startBuf = SM->getCharacterData(LocStart);
706 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000707 ReplaceText(LocStart, endBuf-startBuf,
708 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000709 }
710
Ted Kremenek42730c52008-01-07 19:49:32 +0000711 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000712 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
713 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000714 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000715 ObjCMethodDecl *OMD = *I;
716 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000717 SourceLocation LocStart = OMD->getLocStart();
718 SourceLocation LocEnd = OMD->getBody()->getLocStart();
719
720 const char *startBuf = SM->getCharacterData(LocStart);
721 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000722 ReplaceText(LocStart, endBuf-startBuf,
723 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000725 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000726 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000727 else
Chris Lattner6216f292008-01-31 19:42:41 +0000728 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000729}
730
Ted Kremenek42730c52008-01-07 19:49:32 +0000731void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000732 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000733 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000734 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000735 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000736 ResultStr += ClassDecl->getName();
737 ResultStr += "\n";
738 ResultStr += "#define _REWRITER_typedef_";
739 ResultStr += ClassDecl->getName();
740 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000741 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000742 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000743 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000744 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000745 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000746 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000747 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000748
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000749 RewriteProperties(ClassDecl->getNumPropertyDecl(),
750 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000751 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000752 E = ClassDecl->instmeth_end(); I != E; ++I)
753 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000754 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000755 E = ClassDecl->classmeth_end(); I != E; ++I)
756 RewriteMethodDeclaration(*I);
757
Steve Naroff1ccf4632007-10-30 03:43:13 +0000758 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000759 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000760}
761
Steve Naroff6b759ce2007-11-15 02:58:25 +0000762Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000763 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000764 if (IV->isFreeIvar()) {
765 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
Eli Friedman76b49832008-02-06 22:48:16 +0000766 IV->getLocation(), D->getType());
Chris Lattnerb1548372008-01-31 19:37:57 +0000767 ReplaceStmt(IV, Replacement);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000768 delete IV;
769 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000770 } else {
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000771#if 0
772 /// This code is not right. It seems unnecessary. It breaks use of
773 /// ivar reference used as 'receiver' of an expression; as in:
774 /// [newInv->_container addObject:0];
Steve Naroff292b7b92007-11-15 11:33:00 +0000775 if (CurMethodDecl) {
776 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000777 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000778 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
779 IdentifierInfo *II = intT->getDecl()->getIdentifier();
780 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
781 II, 0);
782 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
783
784 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
785 // Don't forget the parens to enforce the proper binding.
786 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerb1548372008-01-31 19:37:57 +0000787 ReplaceStmt(IV->getBase(), PE);
Steve Naroff292b7b92007-11-15 11:33:00 +0000788 delete IV->getBase();
789 return PE;
790 }
791 }
792 }
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000793#endif
Steve Naroff6b759ce2007-11-15 02:58:25 +0000794 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000795 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000796}
797
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000798//===----------------------------------------------------------------------===//
799// Function Body / Expression rewriting
800//===----------------------------------------------------------------------===//
801
Steve Naroff334fbc22007-11-09 15:20:18 +0000802Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000803 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
804 isa<DoStmt>(S) || isa<ForStmt>(S))
805 Stmts.push_back(S);
806 else if (isa<ObjCForCollectionStmt>(S)) {
807 Stmts.push_back(S);
808 ObjCBcLabelNo.push_back(++BcLabelCount);
809 }
810
Chris Lattner2c022162008-01-31 05:10:40 +0000811 SourceLocation OrigStmtEnd = S->getLocEnd();
812
813 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000814 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
815 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000816 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000817 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000818 if (newStmt)
819 *CI = newStmt;
820 }
Steve Naroffe9780582007-10-23 23:50:29 +0000821
822 // Handle specific things.
823 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
824 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000825
826 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
827 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000828
829 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
830 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000831
Steve Naroff0add5d22007-11-03 11:27:19 +0000832 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
833 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000834
Steve Naroff71226032007-10-24 22:48:43 +0000835 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
836 // Before we rewrite it, put the original message expression in a comment.
837 SourceLocation startLoc = MessExpr->getLocStart();
838 SourceLocation endLoc = MessExpr->getLocEnd();
839
840 const char *startBuf = SM->getCharacterData(startLoc);
841 const char *endBuf = SM->getCharacterData(endLoc);
842
843 std::string messString;
844 messString += "// ";
845 messString.append(startBuf, endBuf-startBuf+1);
846 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000847
Chris Lattner6216f292008-01-31 19:42:41 +0000848 // FIXME: Missing definition of
849 // InsertText(clang::SourceLocation, char const*, unsigned int).
850 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000851 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000852 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000853 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000854 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000855
Ted Kremenek42730c52008-01-07 19:49:32 +0000856 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
857 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000858
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000859 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
860 return RewriteObjCSynchronizedStmt(StmtTry);
861
Ted Kremenek42730c52008-01-07 19:49:32 +0000862 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
863 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000864
865 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
866 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000867
868 if (ObjCForCollectionStmt *StmtForCollection =
869 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000870 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000871 if (BreakStmt *StmtBreakStmt =
872 dyn_cast<BreakStmt>(S))
873 return RewriteBreakStmt(StmtBreakStmt);
874 if (ContinueStmt *StmtContinueStmt =
875 dyn_cast<ContinueStmt>(S))
876 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000877
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000878 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
879 isa<DoStmt>(S) || isa<ForStmt>(S)) {
880 assert(!Stmts.empty() && "Statement stack is empty");
881 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
882 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
883 && "Statement stack mismatch");
884 Stmts.pop_back();
885 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000886#if 0
887 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
888 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
889 // Get the new text.
890 std::ostringstream Buf;
891 Replacement->printPretty(Buf);
892 const std::string &Str = Buf.str();
893
894 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000895 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000896 delete S;
897 return Replacement;
898 }
899#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000900 // Return this stmt unmodified.
901 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000902}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000903
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000904/// SynthCountByEnumWithState - To print:
905/// ((unsigned int (*)
906/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
907/// (void *)objc_msgSend)((id)l_collection,
908/// sel_registerName(
909/// "countByEnumeratingWithState:objects:count:"),
910/// &enumState,
911/// (id *)items, (unsigned int)16)
912///
913void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
914 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
915 "id *, unsigned int))(void *)objc_msgSend)";
916 buf += "\n\t\t";
917 buf += "((id)l_collection,\n\t\t";
918 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
919 buf += "\n\t\t";
920 buf += "&enumState, "
921 "(id *)items, (unsigned int)16)";
922}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000923
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000924/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
925/// statement to exit to its outer synthesized loop.
926///
927Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
928 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
929 return S;
930 // replace break with goto __break_label
931 std::string buf;
932
933 SourceLocation startLoc = S->getLocStart();
934 buf = "goto __break_label_";
935 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000936 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000937
938 return 0;
939}
940
941/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
942/// statement to continue with its inner synthesized loop.
943///
944Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
945 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
946 return S;
947 // replace continue with goto __continue_label
948 std::string buf;
949
950 SourceLocation startLoc = S->getLocStart();
951 buf = "goto __continue_label_";
952 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000953 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000954
955 return 0;
956}
957
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000958/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000959/// It rewrites:
960/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000961
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000962/// Into:
963/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000964/// type elem;
965/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000966/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000967/// id l_collection = (id)collection;
968/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
969/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000970/// if (limit) {
971/// unsigned long startMutations = *enumState.mutationsPtr;
972/// do {
973/// unsigned long counter = 0;
974/// do {
975/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000976/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000977/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000978/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000979/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000980/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000981/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
982/// objects:items count:16]);
983/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000984/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000985/// }
986/// else
987/// elem = nil;
988/// }
989///
Chris Lattner2c022162008-01-31 05:10:40 +0000990Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
991 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000992 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
993 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
994 "ObjCForCollectionStmt Statement stack mismatch");
995 assert(!ObjCBcLabelNo.empty() &&
996 "ObjCForCollectionStmt - Label No stack empty");
997
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000998 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000999 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001000 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001001 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001002 std::string buf;
1003 buf = "\n{\n\t";
1004 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1005 // type elem;
1006 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001007 elementTypeAsString = ElementType.getAsString();
1008 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001009 buf += " ";
1010 elementName = DS->getDecl()->getName();
1011 buf += elementName;
1012 buf += ";\n\t";
1013 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001014 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001015 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001016 elementTypeAsString = DR->getDecl()->getType().getAsString();
1017 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001018 else
1019 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1020
1021 // struct __objcFastEnumerationState enumState = { 0 };
1022 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1023 // id items[16];
1024 buf += "id items[16];\n\t";
1025 // id l_collection = (id)
1026 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001027 // Find start location of 'collection' the hard way!
1028 const char *startCollectionBuf = startBuf;
1029 startCollectionBuf += 3; // skip 'for'
1030 startCollectionBuf = strchr(startCollectionBuf, '(');
1031 startCollectionBuf++; // skip '('
1032 // find 'in' and skip it.
1033 while (*startCollectionBuf != ' ' ||
1034 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1035 (*(startCollectionBuf+3) != ' ' &&
1036 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1037 startCollectionBuf++;
1038 startCollectionBuf += 3;
1039
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001040 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001041 ReplaceText(startLoc, startCollectionBuf - startBuf,
1042 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001043 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001044 SourceLocation rightParenLoc = S->getRParenLoc();
1045 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1046 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001047 buf = ";\n\t";
1048
1049 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1050 // objects:items count:16];
1051 // which is synthesized into:
1052 // unsigned int limit =
1053 // ((unsigned int (*)
1054 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1055 // (void *)objc_msgSend)((id)l_collection,
1056 // sel_registerName(
1057 // "countByEnumeratingWithState:objects:count:"),
1058 // (struct __objcFastEnumerationState *)&state,
1059 // (id *)items, (unsigned int)16);
1060 buf += "unsigned long limit =\n\t\t";
1061 SynthCountByEnumWithState(buf);
1062 buf += ";\n\t";
1063 /// if (limit) {
1064 /// unsigned long startMutations = *enumState.mutationsPtr;
1065 /// do {
1066 /// unsigned long counter = 0;
1067 /// do {
1068 /// if (startMutations != *enumState.mutationsPtr)
1069 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001070 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001071 buf += "if (limit) {\n\t";
1072 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1073 buf += "do {\n\t\t";
1074 buf += "unsigned long counter = 0;\n\t\t";
1075 buf += "do {\n\t\t\t";
1076 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1077 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1078 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001079 buf += " = (";
1080 buf += elementTypeAsString;
1081 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001082 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001083 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001084
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001085 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001086 /// } while (counter < limit);
1087 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1088 /// objects:items count:16]);
1089 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001090 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001091 /// }
1092 /// else
1093 /// elem = nil;
1094 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001095 ///
1096 buf = ";\n\t";
1097 buf += "__continue_label_";
1098 buf += utostr(ObjCBcLabelNo.back());
1099 buf += ": ;";
1100 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001101 buf += "} while (counter < limit);\n\t";
1102 buf += "} while (limit = ";
1103 SynthCountByEnumWithState(buf);
1104 buf += ");\n\t";
1105 buf += elementName;
1106 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001107 buf += "__break_label_";
1108 buf += utostr(ObjCBcLabelNo.back());
1109 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001110 buf += "}\n\t";
1111 buf += "else\n\t\t";
1112 buf += elementName;
1113 buf += " = nil;\n";
1114 buf += "}\n";
1115 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001116 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001117 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001118 Stmts.pop_back();
1119 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001121}
1122
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001123/// RewriteObjCSynchronizedStmt -
1124/// This routine rewrites @synchronized(expr) stmt;
1125/// into:
1126/// objc_sync_enter(expr);
1127/// @try stmt @finally { objc_sync_exit(expr); }
1128///
1129Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1130 // Get the start location and compute the semi location.
1131 SourceLocation startLoc = S->getLocStart();
1132 const char *startBuf = SM->getCharacterData(startLoc);
1133
1134 assert((*startBuf == '@') && "bogus @synchronized location");
1135
1136 std::string buf;
1137 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001138 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001139 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1140 const char *endBuf = SM->getCharacterData(endLoc);
1141 endBuf++;
1142 const char *rparenBuf = strchr(endBuf, ')');
1143 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1144 buf = ");\n";
1145 // declare a new scope with two variables, _stack and _rethrow.
1146 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1147 buf += "int buf[18/*32-bit i386*/];\n";
1148 buf += "char *pointers[4];} _stack;\n";
1149 buf += "id volatile _rethrow = 0;\n";
1150 buf += "objc_exception_try_enter(&_stack);\n";
1151 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001152 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001153 startLoc = S->getSynchBody()->getLocEnd();
1154 startBuf = SM->getCharacterData(startLoc);
1155
1156 assert((*startBuf == '}') && "bogus @try block");
1157 SourceLocation lastCurlyLoc = startLoc;
1158 buf = "}\nelse {\n";
1159 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1160 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1161 // FIXME: This must be objc_sync_exit(syncExpr);
1162 buf += " objc_sync_exit();\n";
1163 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1164 buf += "}\n";
1165 buf += "}";
1166
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001167 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001168 return 0;
1169}
1170
Ted Kremenek42730c52008-01-07 19:49:32 +00001171Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001172 // Get the start location and compute the semi location.
1173 SourceLocation startLoc = S->getLocStart();
1174 const char *startBuf = SM->getCharacterData(startLoc);
1175
1176 assert((*startBuf == '@') && "bogus @try location");
1177
1178 std::string buf;
1179 // declare a new scope with two variables, _stack and _rethrow.
1180 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1181 buf += "int buf[18/*32-bit i386*/];\n";
1182 buf += "char *pointers[4];} _stack;\n";
1183 buf += "id volatile _rethrow = 0;\n";
1184 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001185 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001186
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001187 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001188
1189 startLoc = S->getTryBody()->getLocEnd();
1190 startBuf = SM->getCharacterData(startLoc);
1191
1192 assert((*startBuf == '}') && "bogus @try block");
1193
1194 SourceLocation lastCurlyLoc = startLoc;
1195
1196 startLoc = startLoc.getFileLocWithOffset(1);
1197 buf = " /* @catch begin */ else {\n";
1198 buf += " id _caught = objc_exception_extract(&_stack);\n";
1199 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001200 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001201 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1202 buf += " else { /* @catch continue */";
1203
Chris Lattner6216f292008-01-31 19:42:41 +00001204 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001205
1206 bool sawIdTypedCatch = false;
1207 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001208 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001209 while (catchList) {
1210 Stmt *catchStmt = catchList->getCatchParamStmt();
1211
1212 if (catchList == S->getCatchStmts())
1213 buf = "if ("; // we are generating code for the first catch clause
1214 else
1215 buf = "else if (";
1216 startLoc = catchList->getLocStart();
1217 startBuf = SM->getCharacterData(startLoc);
1218
1219 assert((*startBuf == '@') && "bogus @catch location");
1220
1221 const char *lParenLoc = strchr(startBuf, '(');
1222
Steve Naroff397c4ce2008-02-01 22:08:12 +00001223 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001224 // Now rewrite the body...
1225 lastCatchBody = catchList->getCatchBody();
1226 SourceLocation rParenLoc = catchList->getRParenLoc();
1227 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1228 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1229 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1230 assert((*rParenBuf == ')') && "bogus @catch paren location");
1231 assert((*bodyBuf == '{') && "bogus @catch body location");
1232
1233 buf += "1) { id _tmp = _caught;";
1234 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1235 buf.c_str(), buf.size());
1236 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001237 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001238 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001239 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001240 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001241 sawIdTypedCatch = true;
1242 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001243 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001244
Ted Kremenek42730c52008-01-07 19:49:32 +00001245 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001246 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001247 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001248 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001249 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001250 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001251 }
1252 }
1253 // Now rewrite the body...
1254 lastCatchBody = catchList->getCatchBody();
1255 SourceLocation rParenLoc = catchList->getRParenLoc();
1256 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1257 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1258 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1259 assert((*rParenBuf == ')') && "bogus @catch paren location");
1260 assert((*bodyBuf == '{') && "bogus @catch body location");
1261
1262 buf = " = _caught;";
1263 // Here we replace ") {" with "= _caught;" (which initializes and
1264 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001265 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001266 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001267 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001268 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001269 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001270 catchList = catchList->getNextCatchStmt();
1271 }
1272 // Complete the catch list...
1273 if (lastCatchBody) {
1274 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1275 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1276 assert((*bodyBuf == '}') && "bogus @catch body location");
1277 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1278 buf = " } } /* @catch end */\n";
1279
Chris Lattner6216f292008-01-31 19:42:41 +00001280 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001281
1282 // Set lastCurlyLoc
1283 lastCurlyLoc = lastCatchBody->getLocEnd();
1284 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001285 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001286 startLoc = finalStmt->getLocStart();
1287 startBuf = SM->getCharacterData(startLoc);
1288 assert((*startBuf == '@') && "bogus @finally start");
1289
1290 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001291 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001292
1293 Stmt *body = finalStmt->getFinallyBody();
1294 SourceLocation startLoc = body->getLocStart();
1295 SourceLocation endLoc = body->getLocEnd();
1296 const char *startBuf = SM->getCharacterData(startLoc);
1297 const char *endBuf = SM->getCharacterData(endLoc);
1298 assert((*startBuf == '{') && "bogus @finally body location");
1299 assert((*endBuf == '}') && "bogus @finally body location");
1300
1301 startLoc = startLoc.getFileLocWithOffset(1);
1302 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001303 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001304 endLoc = endLoc.getFileLocWithOffset(-1);
1305 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001306 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001307
1308 // Set lastCurlyLoc
1309 lastCurlyLoc = body->getLocEnd();
1310 }
1311 // Now emit the final closing curly brace...
1312 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1313 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001314 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001315 return 0;
1316}
1317
Ted Kremenek42730c52008-01-07 19:49:32 +00001318Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001319 return 0;
1320}
1321
Ted Kremenek42730c52008-01-07 19:49:32 +00001322Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001323 return 0;
1324}
1325
Chris Lattnerb1548372008-01-31 19:37:57 +00001326// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001327// the throw expression is typically a message expression that's already
1328// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001329Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001330 // Get the start location and compute the semi location.
1331 SourceLocation startLoc = S->getLocStart();
1332 const char *startBuf = SM->getCharacterData(startLoc);
1333
1334 assert((*startBuf == '@') && "bogus @throw location");
1335
1336 std::string buf;
1337 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001338 if (S->getThrowExpr())
1339 buf = "objc_exception_throw(";
1340 else // add an implicit argument
1341 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001342 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001343 const char *semiBuf = strchr(startBuf, ';');
1344 assert((*semiBuf == ';') && "@throw: can't find ';'");
1345 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1346 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001347 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001348 return 0;
1349}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001350
Chris Lattner0021f452007-10-24 16:57:36 +00001351Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001352 // Create a new string expression.
1353 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001354 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001355 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1356 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001357 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1358 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001359 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001360 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001361
Chris Lattner4478db92007-11-30 22:53:43 +00001362 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001363 delete Exp;
1364 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001365}
1366
Steve Naroff296b74f2007-11-05 14:50:49 +00001367Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1368 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1369 // Create a call to sel_registerName("selName").
1370 llvm::SmallVector<Expr*, 8> SelExprs;
1371 QualType argType = Context->getPointerType(Context->CharTy);
1372 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1373 Exp->getSelector().getName().size(),
1374 false, argType, SourceLocation(),
1375 SourceLocation()));
1376 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1377 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001378 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001379 delete Exp;
1380 return SelExp;
1381}
1382
Steve Naroff71226032007-10-24 22:48:43 +00001383CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1384 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001385 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001386 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001387
1388 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001389 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001390
1391 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001392 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001393 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1394
1395 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001396
Steve Naroff71226032007-10-24 22:48:43 +00001397 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1398}
1399
Steve Naroffc8a92d12007-11-01 13:24:47 +00001400static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1401 const char *&startRef, const char *&endRef) {
1402 while (startBuf < endBuf) {
1403 if (*startBuf == '<')
1404 startRef = startBuf; // mark the start.
1405 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001406 if (startRef && *startRef == '<') {
1407 endRef = startBuf; // mark the end.
1408 return true;
1409 }
1410 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001411 }
1412 startBuf++;
1413 }
1414 return false;
1415}
1416
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001417static void scanToNextArgument(const char *&argRef) {
1418 int angle = 0;
1419 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1420 if (*argRef == '<')
1421 angle++;
1422 else if (*argRef == '>')
1423 angle--;
1424 argRef++;
1425 }
1426 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1427}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001428
Steve Naroffc8a92d12007-11-01 13:24:47 +00001429bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001430
Ted Kremenek42730c52008-01-07 19:49:32 +00001431 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001432 return true;
1433
Ted Kremenek42730c52008-01-07 19:49:32 +00001434 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001435 return true;
1436
Steve Naroffc8a92d12007-11-01 13:24:47 +00001437 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001438 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001439 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001440 return true; // we have "Class <Protocol> *".
1441 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001442 return false;
1443}
1444
Ted Kremenek42730c52008-01-07 19:49:32 +00001445void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001446 SourceLocation Loc;
1447 QualType Type;
1448 const FunctionTypeProto *proto = 0;
1449 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1450 Loc = VD->getLocation();
1451 Type = VD->getType();
1452 }
1453 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1454 Loc = FD->getLocation();
1455 // Check for ObjC 'id' and class types that have been adorned with protocol
1456 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1457 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1458 assert(funcType && "missing function type");
1459 proto = dyn_cast<FunctionTypeProto>(funcType);
1460 if (!proto)
1461 return;
1462 Type = proto->getResultType();
1463 }
1464 else
1465 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001466
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001467 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001468 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001469
1470 const char *endBuf = SM->getCharacterData(Loc);
1471 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001472 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001473 startBuf--; // scan backward (from the decl location) for return type.
1474 const char *startRef = 0, *endRef = 0;
1475 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1476 // Get the locations of the startRef, endRef.
1477 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1478 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1479 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001480 InsertText(LessLoc, "/*", 2);
1481 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001482 }
1483 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001484 if (!proto)
1485 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001486 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001487 const char *startBuf = SM->getCharacterData(Loc);
1488 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001489 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1490 if (needToScanForQualifiers(proto->getArgType(i))) {
1491 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001492
Steve Naroffc8a92d12007-11-01 13:24:47 +00001493 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001494 // scan forward (from the decl location) for argument types.
1495 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001496 const char *startRef = 0, *endRef = 0;
1497 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1498 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001499 SourceLocation LessLoc =
1500 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1501 SourceLocation GreaterLoc =
1502 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001503 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001504 InsertText(LessLoc, "/*", 2);
1505 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001506 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001507 startBuf = ++endBuf;
1508 }
1509 else {
1510 while (*startBuf != ')' && *startBuf != ',')
1511 startBuf++; // scan forward (from the decl location) for argument types.
1512 startBuf++;
1513 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001514 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001515}
1516
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001517// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1518void RewriteTest::SynthSelGetUidFunctionDecl() {
1519 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1520 llvm::SmallVector<QualType, 16> ArgTys;
1521 ArgTys.push_back(Context->getPointerType(
1522 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001523 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001524 &ArgTys[0], ArgTys.size(),
1525 false /*isVariadic*/);
1526 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1527 SelGetUidIdent, getFuncType,
1528 FunctionDecl::Extern, false, 0);
1529}
1530
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001531// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1532void RewriteTest::SynthGetProtocolFunctionDecl() {
1533 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1534 llvm::SmallVector<QualType, 16> ArgTys;
1535 ArgTys.push_back(Context->getPointerType(
1536 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001537 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001538 &ArgTys[0], ArgTys.size(),
1539 false /*isVariadic*/);
1540 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1541 SelGetProtoIdent, getFuncType,
1542 FunctionDecl::Extern, false, 0);
1543}
1544
Steve Naroff02a82aa2007-10-30 23:14:51 +00001545void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1546 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001547 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001548 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001549 return;
1550 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001551 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001552}
1553
Steve Naroffbec4bf52008-03-11 17:37:02 +00001554// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1555void RewriteTest::SynthSuperContructorFunctionDecl() {
1556 if (SuperContructorFunctionDecl)
1557 return;
1558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1559 llvm::SmallVector<QualType, 16> ArgTys;
1560 QualType argT = Context->getObjCIdType();
1561 assert(!argT.isNull() && "Can't find 'id' type");
1562 ArgTys.push_back(argT);
1563 ArgTys.push_back(argT);
1564 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1565 &ArgTys[0], ArgTys.size(),
1566 false);
1567 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1568 msgSendIdent, msgSendType,
1569 FunctionDecl::Extern, false, 0);
1570}
1571
Steve Naroff02a82aa2007-10-30 23:14:51 +00001572// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1573void RewriteTest::SynthMsgSendFunctionDecl() {
1574 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1575 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001576 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001577 assert(!argT.isNull() && "Can't find 'id' type");
1578 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001579 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001580 assert(!argT.isNull() && "Can't find 'SEL' type");
1581 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001582 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001583 &ArgTys[0], ArgTys.size(),
1584 true /*isVariadic*/);
1585 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1586 msgSendIdent, msgSendType,
1587 FunctionDecl::Extern, false, 0);
1588}
1589
Steve Naroff764c1ae2007-11-15 10:28:18 +00001590// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1591void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1592 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1593 llvm::SmallVector<QualType, 16> ArgTys;
1594 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1595 &Context->Idents.get("objc_super"), 0);
1596 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1597 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1598 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001599 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001600 assert(!argT.isNull() && "Can't find 'SEL' type");
1601 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001602 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001603 &ArgTys[0], ArgTys.size(),
1604 true /*isVariadic*/);
1605 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1606 msgSendIdent, msgSendType,
1607 FunctionDecl::Extern, false, 0);
1608}
1609
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001610// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1611void RewriteTest::SynthMsgSendStretFunctionDecl() {
1612 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1613 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001614 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001615 assert(!argT.isNull() && "Can't find 'id' type");
1616 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001617 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001618 assert(!argT.isNull() && "Can't find 'SEL' type");
1619 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001620 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001621 &ArgTys[0], ArgTys.size(),
1622 true /*isVariadic*/);
1623 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1624 msgSendIdent, msgSendType,
1625 FunctionDecl::Extern, false, 0);
1626}
1627
1628// SynthMsgSendSuperStretFunctionDecl -
1629// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1630void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1631 IdentifierInfo *msgSendIdent =
1632 &Context->Idents.get("objc_msgSendSuper_stret");
1633 llvm::SmallVector<QualType, 16> ArgTys;
1634 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1635 &Context->Idents.get("objc_super"), 0);
1636 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1637 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1638 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001639 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001640 assert(!argT.isNull() && "Can't find 'SEL' type");
1641 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001642 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001643 &ArgTys[0], ArgTys.size(),
1644 true /*isVariadic*/);
1645 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1646 msgSendIdent, msgSendType,
1647 FunctionDecl::Extern, false, 0);
1648}
1649
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001650// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1651void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1652 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1653 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001654 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001655 assert(!argT.isNull() && "Can't find 'id' type");
1656 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001657 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001658 assert(!argT.isNull() && "Can't find 'SEL' type");
1659 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001660 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001661 &ArgTys[0], ArgTys.size(),
1662 true /*isVariadic*/);
1663 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1664 msgSendIdent, msgSendType,
1665 FunctionDecl::Extern, false, 0);
1666}
1667
Steve Naroff02a82aa2007-10-30 23:14:51 +00001668// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1669void RewriteTest::SynthGetClassFunctionDecl() {
1670 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1671 llvm::SmallVector<QualType, 16> ArgTys;
1672 ArgTys.push_back(Context->getPointerType(
1673 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001674 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001675 &ArgTys[0], ArgTys.size(),
1676 false /*isVariadic*/);
1677 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1678 getClassIdent, getClassType,
1679 FunctionDecl::Extern, false, 0);
1680}
1681
Steve Naroff3b1caac2007-12-07 03:50:46 +00001682// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1683void RewriteTest::SynthGetMetaClassFunctionDecl() {
1684 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1685 llvm::SmallVector<QualType, 16> ArgTys;
1686 ArgTys.push_back(Context->getPointerType(
1687 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001688 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001689 &ArgTys[0], ArgTys.size(),
1690 false /*isVariadic*/);
1691 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1692 getClassIdent, getClassType,
1693 FunctionDecl::Extern, false, 0);
1694}
1695
Steve Naroffabb96362007-11-08 14:30:50 +00001696// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1697void RewriteTest::SynthCFStringFunctionDecl() {
1698 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1699 llvm::SmallVector<QualType, 16> ArgTys;
1700 ArgTys.push_back(Context->getPointerType(
1701 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001702 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001703 &ArgTys[0], ArgTys.size(),
1704 false /*isVariadic*/);
1705 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1706 getClassIdent, getClassType,
1707 FunctionDecl::Extern, false, 0);
1708}
1709
Steve Naroff0add5d22007-11-03 11:27:19 +00001710Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001711#if 1
1712 // This rewrite is specific to GCC, which has builtin support for CFString.
1713 if (!CFStringFunctionDecl)
1714 SynthCFStringFunctionDecl();
1715 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1716 llvm::SmallVector<Expr*, 8> StrExpr;
1717 StrExpr.push_back(Exp->getString());
1718 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1719 &StrExpr[0], StrExpr.size());
1720 // cast to NSConstantString *
1721 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001722 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001723 delete Exp;
1724 return cast;
1725#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001726 assert(ConstantStringClassReference && "Can't find constant string reference");
1727 llvm::SmallVector<Expr*, 4> InitExprs;
1728
1729 // Synthesize "(Class)&_NSConstantStringClassReference"
1730 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1731 ConstantStringClassReference->getType(),
1732 SourceLocation());
1733 QualType expType = Context->getPointerType(ClsRef->getType());
1734 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1735 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001736 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001737 SourceLocation());
1738 InitExprs.push_back(cast); // set the 'isa'.
1739 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1740 unsigned IntSize = static_cast<unsigned>(
1741 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1742 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1743 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1744 Exp->getLocStart());
1745 InitExprs.push_back(len); // set "int numBytes".
1746
1747 // struct NSConstantString
1748 QualType CFConstantStrType = Context->getCFConstantStringType();
1749 // (struct NSConstantString) { <exprs from above> }
1750 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1751 &InitExprs[0], InitExprs.size(),
1752 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001753 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001754 // struct NSConstantString *
1755 expType = Context->getPointerType(StrRep->getType());
1756 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1757 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001758 // cast to NSConstantString *
1759 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001760 ReplaceStmt(Exp, cast);
Steve Naroff0add5d22007-11-03 11:27:19 +00001761 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001762 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001763#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001764}
1765
Ted Kremenek42730c52008-01-07 19:49:32 +00001766ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001767 // check if we are sending a message to 'super'
1768 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001769 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1771 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1772 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001773 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001774 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001775 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001776 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001777 if (ObjCInterfaceType *IT =
1778 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001779 if (IT->getDecl() ==
1780 CurMethodDecl->getClassInterface()->getSuperClass())
1781 return IT->getDecl();
1782 }
1783 }
1784 }
1785 }
1786 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001787 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001788 }
1789 return 0;
1790}
1791
1792// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1793QualType RewriteTest::getSuperStructType() {
1794 if (!SuperStructDecl) {
1795 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1796 &Context->Idents.get("objc_super"), 0);
1797 QualType FieldTypes[2];
1798
1799 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001800 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001801 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001802 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001803 // Create fields
1804 FieldDecl *FieldDecls[2];
1805
1806 for (unsigned i = 0; i < 2; ++i)
1807 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1808
1809 SuperStructDecl->defineBody(FieldDecls, 4);
1810 }
1811 return Context->getTagDeclType(SuperStructDecl);
1812}
1813
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001814Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001815 if (!SelGetUidFunctionDecl)
1816 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001817 if (!MsgSendFunctionDecl)
1818 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001819 if (!MsgSendSuperFunctionDecl)
1820 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001821 if (!MsgSendStretFunctionDecl)
1822 SynthMsgSendStretFunctionDecl();
1823 if (!MsgSendSuperStretFunctionDecl)
1824 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001825 if (!MsgSendFpretFunctionDecl)
1826 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001827 if (!GetClassFunctionDecl)
1828 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001829 if (!GetMetaClassFunctionDecl)
1830 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001831
Steve Naroff764c1ae2007-11-15 10:28:18 +00001832 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001833 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1834 // May need to use objc_msgSend_stret() as well.
1835 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001836 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001837 QualType resultType = mDecl->getResultType();
1838 if (resultType.getCanonicalType()->isStructureType()
1839 || resultType.getCanonicalType()->isUnionType())
1840 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001841 else if (resultType.getCanonicalType()->isRealFloatingType())
1842 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001843 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001844
Steve Naroff71226032007-10-24 22:48:43 +00001845 // Synthesize a call to objc_msgSend().
1846 llvm::SmallVector<Expr*, 8> MsgExprs;
1847 IdentifierInfo *clsName = Exp->getClassName();
1848
1849 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1850 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001851 if (!strcmp(clsName->getName(), "super")) {
1852 MsgSendFlavor = MsgSendSuperFunctionDecl;
1853 if (MsgSendStretFlavor)
1854 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1855 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1856
Ted Kremenek42730c52008-01-07 19:49:32 +00001857 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001858 CurMethodDecl->getClassInterface()->getSuperClass();
1859
1860 llvm::SmallVector<Expr*, 4> InitExprs;
1861
1862 // set the receiver to self, the first argument to all methods.
1863 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001864 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001865 SourceLocation()));
1866 llvm::SmallVector<Expr*, 8> ClsExprs;
1867 QualType argType = Context->getPointerType(Context->CharTy);
1868 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1869 SuperDecl->getIdentifier()->getLength(),
1870 false, argType, SourceLocation(),
1871 SourceLocation()));
1872 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1873 &ClsExprs[0],
1874 ClsExprs.size());
1875 // To turn off a warning, type-cast to 'id'
1876 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001877 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001878 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1879 // struct objc_super
1880 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001881
Steve Naroff3b1caac2007-12-07 03:50:46 +00001882 // (struct objc_super) { <exprs from above> }
1883 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1884 &InitExprs[0], InitExprs.size(),
1885 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001886 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001887 superType, ILE, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001888 // struct objc_super *
1889 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1890 Context->getPointerType(SuperRep->getType()),
1891 SourceLocation());
1892 MsgExprs.push_back(Unop);
1893 } else {
1894 llvm::SmallVector<Expr*, 8> ClsExprs;
1895 QualType argType = Context->getPointerType(Context->CharTy);
1896 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1897 clsName->getLength(),
1898 false, argType, SourceLocation(),
1899 SourceLocation()));
1900 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1901 &ClsExprs[0],
1902 ClsExprs.size());
1903 MsgExprs.push_back(Cls);
1904 }
Steve Naroff885e2122007-11-14 23:54:14 +00001905 } else { // instance message.
1906 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001907
Ted Kremenek42730c52008-01-07 19:49:32 +00001908 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001909 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001910 if (MsgSendStretFlavor)
1911 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001912 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1913
1914 llvm::SmallVector<Expr*, 4> InitExprs;
1915
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001916 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001917 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001918 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001919
1920 llvm::SmallVector<Expr*, 8> ClsExprs;
1921 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001922 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1923 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001924 false, argType, SourceLocation(),
1925 SourceLocation()));
1926 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001927 &ClsExprs[0],
1928 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001929 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001930 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001931 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001932 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001933 // struct objc_super
1934 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001935 Expr *SuperRep;
1936
1937 if (LangOpts.Microsoft) {
1938 SynthSuperContructorFunctionDecl();
1939 // Simulate a contructor call...
1940 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1941 superType, SourceLocation());
1942 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1943 superType, SourceLocation());
1944 } else {
1945 // (struct objc_super) { <exprs from above> }
1946 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1947 &InitExprs[0], InitExprs.size(),
1948 SourceLocation());
1949 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1950 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001951 // struct objc_super *
1952 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1953 Context->getPointerType(SuperRep->getType()),
1954 SourceLocation());
1955 MsgExprs.push_back(Unop);
1956 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001957 // Remove all type-casts because it may contain objc-style types; e.g.
1958 // Foo<Proto> *.
1959 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1960 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001961 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001962 MsgExprs.push_back(recExpr);
1963 }
Steve Naroff885e2122007-11-14 23:54:14 +00001964 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001965 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001966 llvm::SmallVector<Expr*, 8> SelExprs;
1967 QualType argType = Context->getPointerType(Context->CharTy);
1968 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1969 Exp->getSelector().getName().size(),
1970 false, argType, SourceLocation(),
1971 SourceLocation()));
1972 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1973 &SelExprs[0], SelExprs.size());
1974 MsgExprs.push_back(SelExp);
1975
1976 // Now push any user supplied arguments.
1977 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001978 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001979 // Make all implicit casts explicit...ICE comes in handy:-)
1980 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1981 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001982 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1983 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001984 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001985 }
1986 // Make id<P...> cast into an 'id' cast.
1987 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001988 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001989 while ((CE = dyn_cast<CastExpr>(userExpr)))
1990 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001992 userExpr, SourceLocation());
1993 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001994 }
Steve Naroff885e2122007-11-14 23:54:14 +00001995 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001996 // We've transferred the ownership to MsgExprs. Null out the argument in
1997 // the original expression, since we will delete it below.
1998 Exp->setArg(i, 0);
1999 }
Steve Naroff0744c472007-11-04 22:37:50 +00002000 // Generate the funky cast.
2001 CastExpr *cast;
2002 llvm::SmallVector<QualType, 8> ArgTypes;
2003 QualType returnType;
2004
2005 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002006 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2007 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2008 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002009 ArgTypes.push_back(Context->getObjCIdType());
2010 ArgTypes.push_back(Context->getObjCSelType());
2011 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002012 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00002013 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2015 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002016 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002017 ArgTypes.push_back(t);
2018 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002019 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2020 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002021 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002022 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002023 }
2024 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002025 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002026
2027 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002028 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2029 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002030
2031 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2032 // If we don't do this cast, we get the following bizarre warning/note:
2033 // xx.m:13: warning: function called through a non-compatible type
2034 // xx.m:13: note: if this code is reached, the program will abort
2035 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2036 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002037
Steve Naroff0744c472007-11-04 22:37:50 +00002038 // Now do the "normal" pointer to function cast.
2039 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002040 &ArgTypes[0], ArgTypes.size(),
2041 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00002042 castType = Context->getPointerType(castType);
2043 cast = new CastExpr(castType, cast, SourceLocation());
2044
2045 // Don't forget the parens to enforce the proper binding.
2046 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2047
2048 const FunctionType *FT = msgSendType->getAsFunctionType();
2049 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2050 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002051 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002052 if (MsgSendStretFlavor) {
2053 // We have the method which returns a struct/union. Must also generate
2054 // call to objc_msgSend_stret and hang both varieties on a conditional
2055 // expression which dictate which one to envoke depending on size of
2056 // method's return type.
2057
2058 // Create a reference to the objc_msgSend_stret() declaration.
2059 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2060 SourceLocation());
2061 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2062 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2063 SourceLocation());
2064 // Now do the "normal" pointer to function cast.
2065 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002066 &ArgTypes[0], ArgTypes.size(),
2067 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002068 castType = Context->getPointerType(castType);
2069 cast = new CastExpr(castType, cast, SourceLocation());
2070
2071 // Don't forget the parens to enforce the proper binding.
2072 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2073
2074 FT = msgSendType->getAsFunctionType();
2075 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2076 FT->getResultType(), SourceLocation());
2077
2078 // Build sizeof(returnType)
2079 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2080 returnType, Context->getSizeType(),
2081 SourceLocation(), SourceLocation());
2082 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2083 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2084 // For X86 it is more complicated and some kind of target specific routine
2085 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002086 unsigned IntSize =
2087 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002088 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2089 Context->IntTy,
2090 SourceLocation());
2091 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2092 BinaryOperator::LE,
2093 Context->IntTy,
2094 SourceLocation());
2095 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2096 ConditionalOperator *CondExpr =
2097 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002098 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002099 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002100 return ReplacingStmt;
2101}
2102
2103Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2104 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002105 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002106 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002107
Chris Lattner0021f452007-10-24 16:57:36 +00002108 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002109 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002110}
2111
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002112/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2113/// call to objc_getProtocol("proto-name").
2114Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2115 if (!GetProtocolFunctionDecl)
2116 SynthGetProtocolFunctionDecl();
2117 // Create a call to objc_getProtocol("ProtocolName").
2118 llvm::SmallVector<Expr*, 8> ProtoExprs;
2119 QualType argType = Context->getPointerType(Context->CharTy);
2120 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2121 strlen(Exp->getProtocol()->getName()),
2122 false, argType, SourceLocation(),
2123 SourceLocation()));
2124 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2125 &ProtoExprs[0],
2126 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002127 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002128 delete Exp;
2129 return ProtoExp;
2130
2131}
2132
Ted Kremenek42730c52008-01-07 19:49:32 +00002133/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002134/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002135void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002136 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002137 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2138 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002139 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002140 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002141 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002142 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002143 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002144 SourceLocation LocStart = CDecl->getLocStart();
2145 SourceLocation LocEnd = CDecl->getLocEnd();
2146
2147 const char *startBuf = SM->getCharacterData(LocStart);
2148 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002149 // If no ivars and no root or if its root, directly or indirectly,
2150 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002151 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002152 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002153 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002154 return;
2155 }
2156
2157 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002158 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002159 Result += "\nstruct ";
2160 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002161 if (LangOpts.Microsoft)
2162 Result += "_IMPL";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002163
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002164 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002165 const char *cursor = strchr(startBuf, '{');
2166 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002167 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002168
2169 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002170 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002171 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002172 Result = "\n struct ";
2173 Result += RCDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002174 if (LangOpts.Microsoft)
2175 Result += "_IMPL";
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002176 // Note: We don't name the field decl. This simplifies the "codegen" for
2177 // accessing a superclasses instance variables (and is similar to what gcc
2178 // does internally). The unnamed struct field feature is enabled with
2179 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2180 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002181 Result += ";\n";
2182
2183 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002184 SourceLocation OnePastCurly =
2185 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2186 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002187 }
2188 cursor++; // past '{'
2189
2190 // Now comment out any visibility specifiers.
2191 while (cursor < endBuf) {
2192 if (*cursor == '@') {
2193 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002194 // Skip whitespace.
2195 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2196 /*scan*/;
2197
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002198 // FIXME: presence of @public, etc. inside comment results in
2199 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002200 if (!strncmp(cursor, "public", strlen("public")) ||
2201 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002202 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002203 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002204 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002205 // FIXME: If there are cases where '<' is used in ivar declaration part
2206 // of user code, then scan the ivar list and use needToScanForQualifiers
2207 // for type checking.
2208 else if (*cursor == '<') {
2209 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002210 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002211 cursor = strchr(cursor, '>');
2212 cursor++;
2213 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002214 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002215 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002216 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002217 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002218 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002219 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002220 } else { // we don't have any instance variables - insert super struct.
2221 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2222 Result += " {\n struct ";
2223 Result += RCDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002224 if (LangOpts.Microsoft)
2225 Result += "_IMPL";
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002226 // Note: We don't name the field decl. This simplifies the "codegen" for
2227 // accessing a superclasses instance variables (and is similar to what gcc
2228 // does internally). The unnamed struct field feature is enabled with
2229 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2230 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002231 Result += ";\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002232 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002233 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002234 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002235 if (!ObjCSynthesizedStructs.insert(CDecl))
2236 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002237}
2238
Ted Kremenek42730c52008-01-07 19:49:32 +00002239// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002240/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002241void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002242 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002243 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002244 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002245 const char *ClassName,
2246 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002247 if (MethodBegin == MethodEnd) return;
2248
Fariborz Jahanian04455192007-10-22 21:41:37 +00002249 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002250 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002251 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002252 SEL _cmd;
2253 char *method_types;
2254 void *_imp;
2255 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002256 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002257 Result += "\nstruct _objc_method {\n";
2258 Result += "\tSEL _cmd;\n";
2259 Result += "\tchar *method_types;\n";
2260 Result += "\tvoid *_imp;\n";
2261 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002262
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002263 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002264 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002265
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002266 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002267
2268 /* struct {
2269 struct _objc_method_list *next_method;
2270 int method_count;
2271 struct _objc_method method_list[];
2272 }
2273 */
2274 Result += "\nstatic struct {\n";
2275 Result += "\tstruct _objc_method_list *next_method;\n";
2276 Result += "\tint method_count;\n";
2277 Result += "\tstruct _objc_method method_list[";
2278 Result += utostr(MethodEnd-MethodBegin);
2279 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002280 Result += prefix;
2281 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2282 Result += "_METHODS_";
2283 Result += ClassName;
2284 Result += " __attribute__ ((section (\"__OBJC, __";
2285 Result += IsInstanceMethod ? "inst" : "cls";
2286 Result += "_meth\")))= ";
2287 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002288
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002289 Result += "\t,{{(SEL)\"";
2290 Result += (*MethodBegin)->getSelector().getName().c_str();
2291 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002292 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002293 Result += "\", \"";
2294 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002295 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002296 Result += MethodInternalNames[*MethodBegin];
2297 Result += "}\n";
2298 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2299 Result += "\t ,{(SEL)\"";
2300 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002301 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002302 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002303 Result += "\", \"";
2304 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002305 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002306 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002307 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002308 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002309 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002310}
2311
Ted Kremenek42730c52008-01-07 19:49:32 +00002312/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2313void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002314 int NumProtocols,
2315 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002316 const char *ClassName,
2317 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002318 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002319 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002320 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002321 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002322 // Output struct protocol_methods holder of method selector and type.
2323 if (!objc_protocol_methods &&
2324 (PDecl->getNumInstanceMethods() > 0
2325 || PDecl->getNumClassMethods() > 0)) {
2326 /* struct protocol_methods {
2327 SEL _cmd;
2328 char *method_types;
2329 }
2330 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002331 Result += "\nstruct protocol_methods {\n";
2332 Result += "\tSEL _cmd;\n";
2333 Result += "\tchar *method_types;\n";
2334 Result += "};\n";
2335
2336 /* struct _objc_protocol_method_list {
2337 int protocol_method_count;
2338 struct protocol_methods protocols[];
2339 }
2340 */
2341 Result += "\nstruct _objc_protocol_method_list {\n";
2342 Result += "\tint protocol_method_count;\n";
2343 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002344 objc_protocol_methods = true;
2345 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002346
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002347 int NumMethods = PDecl->getNumInstanceMethods();
2348 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002349 Result += "\nstatic struct _objc_protocol_method_list "
2350 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2351 Result += PDecl->getName();
2352 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2353 "{\n\t" + utostr(NumMethods) + "\n";
2354
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002355 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002356 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002357 E = PDecl->instmeth_end(); I != E; ++I) {
2358 if (I == PDecl->instmeth_begin())
2359 Result += "\t ,{{(SEL)\"";
2360 else
2361 Result += "\t ,{(SEL)\"";
2362 Result += (*I)->getSelector().getName().c_str();
2363 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002364 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002365 Result += "\", \"";
2366 Result += MethodTypeString;
2367 Result += "\"}\n";
2368 }
2369 Result += "\t }\n};\n";
2370 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002371
2372 // Output class methods declared in this protocol.
2373 NumMethods = PDecl->getNumClassMethods();
2374 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002375 Result += "\nstatic struct _objc_protocol_method_list "
2376 "_OBJC_PROTOCOL_CLASS_METHODS_";
2377 Result += PDecl->getName();
2378 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2379 "{\n\t";
2380 Result += utostr(NumMethods);
2381 Result += "\n";
2382
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002383 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002384 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002385 E = PDecl->classmeth_end(); I != E; ++I) {
2386 if (I == PDecl->classmeth_begin())
2387 Result += "\t ,{{(SEL)\"";
2388 else
2389 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002390 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002391 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002392 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002393 Result += "\", \"";
2394 Result += MethodTypeString;
2395 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002396 }
2397 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002398 }
2399 // Output:
2400 /* struct _objc_protocol {
2401 // Objective-C 1.0 extensions
2402 struct _objc_protocol_extension *isa;
2403 char *protocol_name;
2404 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002405 struct _objc_protocol_method_list *instance_methods;
2406 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002407 };
2408 */
2409 static bool objc_protocol = false;
2410 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002411 Result += "\nstruct _objc_protocol {\n";
2412 Result += "\tstruct _objc_protocol_extension *isa;\n";
2413 Result += "\tchar *protocol_name;\n";
2414 Result += "\tstruct _objc_protocol **protocol_list;\n";
2415 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2416 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2417 Result += "};\n";
2418
2419 /* struct _objc_protocol_list {
2420 struct _objc_protocol_list *next;
2421 int protocol_count;
2422 struct _objc_protocol *class_protocols[];
2423 }
2424 */
2425 Result += "\nstruct _objc_protocol_list {\n";
2426 Result += "\tstruct _objc_protocol_list *next;\n";
2427 Result += "\tint protocol_count;\n";
2428 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2429 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002430 objc_protocol = true;
2431 }
2432
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002433 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2434 Result += PDecl->getName();
2435 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2436 "{\n\t0, \"";
2437 Result += PDecl->getName();
2438 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002439 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002440 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2441 Result += PDecl->getName();
2442 Result += ", ";
2443 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002444 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002445 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002446 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002447 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2448 Result += PDecl->getName();
2449 Result += "\n";
2450 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002451 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002452 Result += "0\n";
2453 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002454 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002455 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002456 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2457 Result += prefix;
2458 Result += "_PROTOCOLS_";
2459 Result += ClassName;
2460 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2461 "{\n\t0, ";
2462 Result += utostr(NumProtocols);
2463 Result += "\n";
2464
2465 Result += "\t,{&_OBJC_PROTOCOL_";
2466 Result += Protocols[0]->getName();
2467 Result += " \n";
2468
2469 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002470 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002471 Result += "\t ,&_OBJC_PROTOCOL_";
2472 Result += PDecl->getName();
2473 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002474 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002475 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002476 }
2477}
2478
Ted Kremenek42730c52008-01-07 19:49:32 +00002479/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002480/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002481void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002482 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002483 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002484 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002485 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002486 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2487 CDecl = CDecl->getNextClassCategory())
2488 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2489 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002490
Chris Lattnera661a4d2007-12-23 01:40:15 +00002491 std::string FullCategoryName = ClassDecl->getName();
2492 FullCategoryName += '_';
2493 FullCategoryName += IDecl->getName();
2494
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002495 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002496 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002497 true, "CATEGORY_", FullCategoryName.c_str(),
2498 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002499
2500 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002501 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002502 false, "CATEGORY_", FullCategoryName.c_str(),
2503 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002504
2505 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002506 // Null CDecl is case of a category implementation with no category interface
2507 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002508 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002509 CDecl->getNumReferencedProtocols(),
2510 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002511 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002512
2513 /* struct _objc_category {
2514 char *category_name;
2515 char *class_name;
2516 struct _objc_method_list *instance_methods;
2517 struct _objc_method_list *class_methods;
2518 struct _objc_protocol_list *protocols;
2519 // Objective-C 1.0 extensions
2520 uint32_t size; // sizeof (struct _objc_category)
2521 struct _objc_property_list *instance_properties; // category's own
2522 // @property decl.
2523 };
2524 */
2525
2526 static bool objc_category = false;
2527 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002528 Result += "\nstruct _objc_category {\n";
2529 Result += "\tchar *category_name;\n";
2530 Result += "\tchar *class_name;\n";
2531 Result += "\tstruct _objc_method_list *instance_methods;\n";
2532 Result += "\tstruct _objc_method_list *class_methods;\n";
2533 Result += "\tstruct _objc_protocol_list *protocols;\n";
2534 Result += "\tunsigned int size;\n";
2535 Result += "\tstruct _objc_property_list *instance_properties;\n";
2536 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002537 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002538 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002539 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2540 Result += FullCategoryName;
2541 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2542 Result += IDecl->getName();
2543 Result += "\"\n\t, \"";
2544 Result += ClassDecl->getName();
2545 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002546
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002547 if (IDecl->getNumInstanceMethods() > 0) {
2548 Result += "\t, (struct _objc_method_list *)"
2549 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2550 Result += FullCategoryName;
2551 Result += "\n";
2552 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002553 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002554 Result += "\t, 0\n";
2555 if (IDecl->getNumClassMethods() > 0) {
2556 Result += "\t, (struct _objc_method_list *)"
2557 "&_OBJC_CATEGORY_CLASS_METHODS_";
2558 Result += FullCategoryName;
2559 Result += "\n";
2560 }
2561 else
2562 Result += "\t, 0\n";
2563
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002564 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002565 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2566 Result += FullCategoryName;
2567 Result += "\n";
2568 }
2569 else
2570 Result += "\t, 0\n";
2571 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002572}
2573
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002574/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2575/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002576void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2577 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002578 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002579 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002580 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002581 if (LangOpts.Microsoft)
2582 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002583 Result += ", ";
2584 Result += ivar->getName();
2585 Result += ")";
2586}
2587
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002588//===----------------------------------------------------------------------===//
2589// Meta Data Emission
2590//===----------------------------------------------------------------------===//
2591
Ted Kremenek42730c52008-01-07 19:49:32 +00002592void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002593 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002594 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002595
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002596 // Explictly declared @interface's are already synthesized.
2597 if (CDecl->ImplicitInterfaceDecl()) {
2598 // FIXME: Implementation of a class with no @interface (legacy) doese not
2599 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002600 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002601 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002602
Chris Lattnerc7b06752007-12-12 07:56:42 +00002603 // Build _objc_ivar_list metadata for classes ivars if needed
2604 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2605 ? IDecl->getImplDeclNumIvars()
2606 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002607 if (NumIvars > 0) {
2608 static bool objc_ivar = false;
2609 if (!objc_ivar) {
2610 /* struct _objc_ivar {
2611 char *ivar_name;
2612 char *ivar_type;
2613 int ivar_offset;
2614 };
2615 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002616 Result += "\nstruct _objc_ivar {\n";
2617 Result += "\tchar *ivar_name;\n";
2618 Result += "\tchar *ivar_type;\n";
2619 Result += "\tint ivar_offset;\n";
2620 Result += "};\n";
2621
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002622 objc_ivar = true;
2623 }
2624
Steve Naroffc723eec2008-03-11 00:12:29 +00002625 /* struct {
2626 int ivar_count;
2627 struct _objc_ivar ivar_list[nIvars];
2628 };
2629 */
2630 Result += "\nstatic struct {\n";
2631 Result += "\tint ivar_count;\n";
2632 Result += "\tstruct _objc_ivar ivar_list[";
2633 Result += utostr(NumIvars);
2634 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002635 Result += IDecl->getName();
2636 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2637 "{\n\t";
2638 Result += utostr(NumIvars);
2639 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002640
Ted Kremenek42730c52008-01-07 19:49:32 +00002641 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002642 if (IDecl->getImplDeclNumIvars() > 0) {
2643 IVI = IDecl->ivar_begin();
2644 IVE = IDecl->ivar_end();
2645 } else {
2646 IVI = CDecl->ivar_begin();
2647 IVE = CDecl->ivar_end();
2648 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002649 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002650 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002651 Result += "\", \"";
2652 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002653 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2654 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002655 Result += StrEncoding;
2656 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002657 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002658 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002659 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002660 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002661 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002662 Result += "\", \"";
2663 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002664 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2665 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002666 Result += StrEncoding;
2667 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002668 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002669 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002670 }
2671
2672 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002673 }
2674
2675 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002676 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002677 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002678
2679 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002680 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002681 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002682
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002683 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002684 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002685 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002686 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002687
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002688
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002689 // Declaration of class/meta-class metadata
2690 /* struct _objc_class {
2691 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002692 const char *super_class_name;
2693 char *name;
2694 long version;
2695 long info;
2696 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002697 struct _objc_ivar_list *ivars;
2698 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002699 struct objc_cache *cache;
2700 struct objc_protocol_list *protocols;
2701 const char *ivar_layout;
2702 struct _objc_class_ext *ext;
2703 };
2704 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002705 static bool objc_class = false;
2706 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002707 Result += "\nstruct _objc_class {\n";
2708 Result += "\tstruct _objc_class *isa;\n";
2709 Result += "\tconst char *super_class_name;\n";
2710 Result += "\tchar *name;\n";
2711 Result += "\tlong version;\n";
2712 Result += "\tlong info;\n";
2713 Result += "\tlong instance_size;\n";
2714 Result += "\tstruct _objc_ivar_list *ivars;\n";
2715 Result += "\tstruct _objc_method_list *methods;\n";
2716 Result += "\tstruct objc_cache *cache;\n";
2717 Result += "\tstruct _objc_protocol_list *protocols;\n";
2718 Result += "\tconst char *ivar_layout;\n";
2719 Result += "\tstruct _objc_class_ext *ext;\n";
2720 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002721 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002722 }
2723
2724 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002725 ObjCInterfaceDecl *RootClass = 0;
2726 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002727 while (SuperClass) {
2728 RootClass = SuperClass;
2729 SuperClass = SuperClass->getSuperClass();
2730 }
2731 SuperClass = CDecl->getSuperClass();
2732
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002733 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2734 Result += CDecl->getName();
2735 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2736 "{\n\t(struct _objc_class *)\"";
2737 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2738 Result += "\"";
2739
2740 if (SuperClass) {
2741 Result += ", \"";
2742 Result += SuperClass->getName();
2743 Result += "\", \"";
2744 Result += CDecl->getName();
2745 Result += "\"";
2746 }
2747 else {
2748 Result += ", 0, \"";
2749 Result += CDecl->getName();
2750 Result += "\"";
2751 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002752 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002753 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002754 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002755 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002756 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002757 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002758 Result += "\n";
2759 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002760 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002761 Result += ", 0\n";
2762 if (CDecl->getNumIntfRefProtocols() > 0) {
2763 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2764 Result += CDecl->getName();
2765 Result += ",0,0\n";
2766 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002767 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002768 Result += "\t,0,0,0,0\n";
2769 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002770
2771 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002772 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2773 Result += CDecl->getName();
2774 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2775 "{\n\t&_OBJC_METACLASS_";
2776 Result += CDecl->getName();
2777 if (SuperClass) {
2778 Result += ", \"";
2779 Result += SuperClass->getName();
2780 Result += "\", \"";
2781 Result += CDecl->getName();
2782 Result += "\"";
2783 }
2784 else {
2785 Result += ", 0, \"";
2786 Result += CDecl->getName();
2787 Result += "\"";
2788 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002789 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002790 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002791 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002792 Result += ",0";
2793 else {
2794 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002795 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002796 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002797 if (LangOpts.Microsoft)
2798 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002799 Result += ")";
2800 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002801 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002802 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002803 Result += CDecl->getName();
2804 Result += "\n\t";
2805 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002806 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002807 Result += ",0";
2808 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002809 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002810 Result += CDecl->getName();
2811 Result += ", 0\n\t";
2812 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002813 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002814 Result += ",0,0";
2815 if (CDecl->getNumIntfRefProtocols() > 0) {
2816 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2817 Result += CDecl->getName();
2818 Result += ", 0,0\n";
2819 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002820 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002821 Result += ",0,0,0\n";
2822 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002823}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002824
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002825/// RewriteImplementations - This routine rewrites all method implementations
2826/// and emits meta-data.
2827
2828void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002829 int ClsDefCount = ClassImplementation.size();
2830 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002831
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002832 if (ClsDefCount == 0 && CatDefCount == 0)
2833 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002834 // Rewrite implemented methods
2835 for (int i = 0; i < ClsDefCount; i++)
2836 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002837
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002838 for (int i = 0; i < CatDefCount; i++)
2839 RewriteImplementationDecl(CategoryImplementation[i]);
2840
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002841 // This is needed for use of offsetof
2842 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002843
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002844 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002845 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002846 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002847
2848 // For each implemented category, write out all its meta data.
2849 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002850 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002851
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002852 // Write objc_symtab metadata
2853 /*
2854 struct _objc_symtab
2855 {
2856 long sel_ref_cnt;
2857 SEL *refs;
2858 short cls_def_cnt;
2859 short cat_def_cnt;
2860 void *defs[cls_def_cnt + cat_def_cnt];
2861 };
2862 */
2863
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002864 Result += "\nstruct _objc_symtab {\n";
2865 Result += "\tlong sel_ref_cnt;\n";
2866 Result += "\tSEL *refs;\n";
2867 Result += "\tshort cls_def_cnt;\n";
2868 Result += "\tshort cat_def_cnt;\n";
2869 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2870 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002871
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002872 Result += "static struct _objc_symtab "
2873 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2874 Result += "\t0, 0, " + utostr(ClsDefCount)
2875 + ", " + utostr(CatDefCount) + "\n";
2876 for (int i = 0; i < ClsDefCount; i++) {
2877 Result += "\t,&_OBJC_CLASS_";
2878 Result += ClassImplementation[i]->getName();
2879 Result += "\n";
2880 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002881
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002882 for (int i = 0; i < CatDefCount; i++) {
2883 Result += "\t,&_OBJC_CATEGORY_";
2884 Result += CategoryImplementation[i]->getClassInterface()->getName();
2885 Result += "_";
2886 Result += CategoryImplementation[i]->getName();
2887 Result += "\n";
2888 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002889
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002890 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002891
2892 // Write objc_module metadata
2893
2894 /*
2895 struct _objc_module {
2896 long version;
2897 long size;
2898 const char *name;
2899 struct _objc_symtab *symtab;
2900 }
2901 */
2902
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002903 Result += "\nstruct _objc_module {\n";
2904 Result += "\tlong version;\n";
2905 Result += "\tlong size;\n";
2906 Result += "\tconst char *name;\n";
2907 Result += "\tstruct _objc_symtab *symtab;\n";
2908 Result += "};\n\n";
2909 Result += "static struct _objc_module "
2910 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002911 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2912 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002913 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002914
2915 if (LangOpts.Microsoft) {
2916 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2917 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2918 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2919 Result += "&_OBJC_MODULES;\n";
2920 Result += "#pragma data_seg(pop)\n\n";
2921 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002922}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002923