blob: d53f23d00c02c008ef625d6a9ee80761ca39cb5c [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";
Steve Naroff6453aab2008-03-12 13:19:12 +0000284 if (LangOpts.Microsoft)
285 S += "extern \"C\" {\n";
286 S += "struct objc_object *objc_msgSend";
Steve Naroffde0da102008-03-10 23:16:54 +0000287 S += "(struct objc_object *, struct objc_selector *, ...);\n";
288 S += "extern struct objc_object *objc_msgSendSuper";
289 S += "(struct objc_super *, struct objc_selector *, ...);\n";
290 S += "extern struct objc_object *objc_msgSend_stret";
291 S += "(struct objc_object *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSendSuper_stret";
293 S += "(struct objc_super *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_msgSend_fpret";
295 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000296 S += "struct objc_object *objc_getClass";
Steve Naroffde0da102008-03-10 23:16:54 +0000297 S += "(const char *);\n";
298 S += "extern struct objc_object *objc_getMetaClass";
299 S += "(const char *);\n";
300 S += "extern void objc_exception_throw(struct objc_object *);\n";
301 S += "extern void objc_exception_try_enter(void *);\n";
302 S += "extern void objc_exception_try_exit(void *);\n";
303 S += "extern struct objc_object *objc_exception_extract(void *);\n";
304 S += "extern int objc_exception_match";
305 S += "(struct objc_class *, struct objc_object *, ...);\n";
306 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000307 if (LangOpts.Microsoft)
308 S += "} // end extern \"C\"\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000309 S += "#include <objc/objc.h>\n";
310 S += "#ifndef __FASTENUMERATIONSTATE\n";
311 S += "struct __objcFastEnumerationState {\n\t";
312 S += "unsigned long state;\n\t";
313 S += "id *itemsPtr;\n\t";
314 S += "unsigned long *mutationsPtr;\n\t";
315 S += "unsigned long extra[5];\n};\n";
316 S += "#define __FASTENUMERATIONSTATE\n";
317 S += "#endif\n";
318#if 0
319 if (LangOpts.Microsoft)
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000320 S += "#define __attribute__(X)\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000321#endif
Chris Lattner12499682008-01-31 19:38:44 +0000322 if (IsHeader) {
323 // insert the whole string when rewriting a header file
Steve Naroffde0da102008-03-10 23:16:54 +0000324 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner12499682008-01-31 19:38:44 +0000325 }
326 else {
327 // Not rewriting header, exclude the #pragma once pragma
Steve Naroffde0da102008-03-10 23:16:54 +0000328 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattner6216f292008-01-31 19:42:41 +0000329 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner12499682008-01-31 19:38:44 +0000330 }
331}
332
333
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000334//===----------------------------------------------------------------------===//
335// Top Level Driver Code
336//===----------------------------------------------------------------------===//
337
Chris Lattner569faa62007-10-11 18:38:32 +0000338void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000339 // Two cases: either the decl could be in the main file, or it could be in a
340 // #included file. If the former, rewrite it now. If the later, check to see
341 // if we rewrote the #include/#import.
342 SourceLocation Loc = D->getLocation();
343 Loc = SM->getLogicalLoc(Loc);
344
345 // If this is for a builtin, ignore it.
346 if (Loc.isInvalid()) return;
347
Steve Naroffe9780582007-10-23 23:50:29 +0000348 // Look for built-in declarations that we need to refer during the rewrite.
349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000350 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000351 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
352 // declared in <Foundation/NSString.h>
353 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
354 ConstantStringClassReference = FVD;
355 return;
356 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000357 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000358 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000359 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000360 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000361 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000362 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000363 } else if (ObjCForwardProtocolDecl *FP =
364 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000365 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000366 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000368 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
369 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000370}
371
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000372/// HandleDeclInMainFile - This is called for each top-level decl defined in the
373/// main file of the input.
374void RewriteTest::HandleDeclInMainFile(Decl *D) {
375 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
376 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000377 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000378
Ted Kremenek42730c52008-01-07 19:49:32 +0000379 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000380 if (Stmt *Body = MD->getBody()) {
381 //Body->dump();
382 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000383 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000384 CurMethodDecl = 0;
385 }
Steve Naroff18c83382007-11-13 23:01:27 +0000386 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000387 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000388 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000389 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000390 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000391 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000392 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000393 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000394 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000395 if (VD->getInit())
396 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
397 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000398 // Nothing yet.
399}
400
401RewriteTest::~RewriteTest() {
402 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000403
404 // Rewrite tabs if we care.
405 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000406
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000407 RewriteInclude();
408
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000409 // Rewrite Objective-c meta data*
410 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000411 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000412
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000413 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
414 // we are done.
415 if (const RewriteBuffer *RewriteBuf =
416 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000417 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000418 std::string S(RewriteBuf->begin(), RewriteBuf->end());
419 printf("%s\n", S.c_str());
420 } else {
421 printf("No changes\n");
422 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000423 // Emit metadata.
424 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000425}
426
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000427//===----------------------------------------------------------------------===//
428// Syntactic (non-AST) Rewriting Code
429//===----------------------------------------------------------------------===//
430
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000431void RewriteTest::RewriteInclude() {
432 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
433 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
434 const char *MainBufStart = MainBuf.first;
435 const char *MainBufEnd = MainBuf.second;
436 size_t ImportLen = strlen("import");
437 size_t IncludeLen = strlen("include");
438
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000439 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000440 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
441 if (*BufPtr == '#') {
442 if (++BufPtr == MainBufEnd)
443 return;
444 while (*BufPtr == ' ' || *BufPtr == '\t')
445 if (++BufPtr == MainBufEnd)
446 return;
447 if (!strncmp(BufPtr, "import", ImportLen)) {
448 // replace import with include
449 SourceLocation ImportLoc =
450 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000451 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000452 BufPtr += ImportLen;
453 }
454 }
455 }
Chris Lattner74db1682007-10-16 21:07:07 +0000456}
457
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000458void RewriteTest::RewriteTabs() {
459 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
460 const char *MainBufStart = MainBuf.first;
461 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000462
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000463 // Loop over the whole file, looking for tabs.
464 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
465 if (*BufPtr != '\t')
466 continue;
467
468 // Okay, we found a tab. This tab will turn into at least one character,
469 // but it depends on which 'virtual column' it is in. Compute that now.
470 unsigned VCol = 0;
471 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
472 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
473 ++VCol;
474
475 // Okay, now that we know the virtual column, we know how many spaces to
476 // insert. We assume 8-character tab-stops.
477 unsigned Spaces = 8-(VCol & 7);
478
479 // Get the location of the tab.
480 SourceLocation TabLoc =
481 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
482
483 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000484 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000485 }
Chris Lattner569faa62007-10-11 18:38:32 +0000486}
487
488
Ted Kremenek42730c52008-01-07 19:49:32 +0000489void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000490 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000491 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000492
493 // Get the start location and compute the semi location.
494 SourceLocation startLoc = ClassDecl->getLocation();
495 const char *startBuf = SM->getCharacterData(startLoc);
496 const char *semiPtr = strchr(startBuf, ';');
497
498 // Translate to typedef's that forward reference structs with the same name
499 // as the class. As a convenience, we include the original declaration
500 // as a comment.
501 std::string typedefString;
502 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000503 typedefString.append(startBuf, semiPtr-startBuf+1);
504 typedefString += "\n";
505 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000506 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000507 typedefString += "#ifndef _REWRITER_typedef_";
508 typedefString += ForwardDecl->getName();
509 typedefString += "\n";
510 typedefString += "#define _REWRITER_typedef_";
511 typedefString += ForwardDecl->getName();
512 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000513 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000514 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000515 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000516 }
517
518 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000519 ReplaceText(startLoc, semiPtr-startBuf+1,
520 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000521}
522
Ted Kremenek42730c52008-01-07 19:49:32 +0000523void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000524 SourceLocation LocStart = Method->getLocStart();
525 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000526
Steve Naroff2ce399a2007-12-14 23:37:57 +0000527 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000528 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000529 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000530 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000531 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000532 }
533}
534
Ted Kremenek42730c52008-01-07 19:49:32 +0000535void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000536{
537 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000538 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000539 SourceLocation Loc = Property->getLocation();
540
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000541 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000542
543 // FIXME: handle properties that are declared across multiple lines.
544 }
545}
546
Ted Kremenek42730c52008-01-07 19:49:32 +0000547void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000548 SourceLocation LocStart = CatDecl->getLocStart();
549
550 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000551 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000552
Ted Kremenek42730c52008-01-07 19:49:32 +0000553 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000554 E = CatDecl->instmeth_end(); I != E; ++I)
555 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000556 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000557 E = CatDecl->classmeth_end(); I != E; ++I)
558 RewriteMethodDeclaration(*I);
559
Steve Naroff667f1682007-10-30 13:30:57 +0000560 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000561 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000562}
563
Ted Kremenek42730c52008-01-07 19:49:32 +0000564void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000565 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000566
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000567 SourceLocation LocStart = PDecl->getLocStart();
568
569 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000570 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000571
Ted Kremenek42730c52008-01-07 19:49:32 +0000572 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000573 E = PDecl->instmeth_end(); I != E; ++I)
574 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000575 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000576 E = PDecl->classmeth_end(); I != E; ++I)
577 RewriteMethodDeclaration(*I);
578
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000579 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000580 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000581 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000582
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000583 // Must comment out @optional/@required
584 const char *startBuf = SM->getCharacterData(LocStart);
585 const char *endBuf = SM->getCharacterData(LocEnd);
586 for (const char *p = startBuf; p < endBuf; p++) {
587 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
588 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000589 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000590 ReplaceText(OptionalLoc, strlen("@optional"),
591 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000592
593 }
594 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
595 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000596 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000597 ReplaceText(OptionalLoc, strlen("@required"),
598 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000599
600 }
601 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000602}
603
Ted Kremenek42730c52008-01-07 19:49:32 +0000604void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000605 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000606 if (LocStart.isInvalid())
607 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000608 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000609 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000610}
611
Ted Kremenek42730c52008-01-07 19:49:32 +0000612void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000613 std::string &ResultStr) {
614 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000615 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000616 ResultStr += "id";
617 else
618 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000619 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000620
621 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000622 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000623
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000624 if (OMD->isInstance())
625 NameStr += "_I_";
626 else
627 NameStr += "_C_";
628
629 NameStr += OMD->getClassInterface()->getName();
630 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000631
632 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000633 if (ObjCCategoryImplDecl *CID =
634 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000635 NameStr += CID->getName();
636 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000637 }
638 // Append selector names, replacing ':' with '_'
639 const char *selName = OMD->getSelector().getName().c_str();
640 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000641 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000642 else {
643 std::string selString = OMD->getSelector().getName();
644 int len = selString.size();
645 for (int i = 0; i < len; i++)
646 if (selString[i] == ':')
647 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000648 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000649 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000650 // Remember this name for metadata emission
651 MethodInternalNames[OMD] = NameStr;
652 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000653
654 // Rewrite arguments
655 ResultStr += "(";
656
657 // invisible arguments
658 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000659 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000660 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000661 if (!LangOpts.Microsoft) {
662 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
663 ResultStr += "struct ";
664 }
665 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000666 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000667 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000668 }
669 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000670 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000671
672 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000673 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000674 ResultStr += " _cmd";
675
676 // Method arguments.
677 for (int i = 0; i < OMD->getNumParams(); i++) {
678 ParmVarDecl *PDecl = OMD->getParamDecl(i);
679 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000680 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000681 ResultStr += "id";
682 else
683 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000684 ResultStr += " ";
685 ResultStr += PDecl->getName();
686 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000687 if (OMD->isVariadic())
688 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000689 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000690
691}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000692void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000693 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
694 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000695
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000696 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000697 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000698 else
Chris Lattner6216f292008-01-31 19:42:41 +0000699 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000700
Ted Kremenek42730c52008-01-07 19:49:32 +0000701 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000702 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
703 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000704 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000705 ObjCMethodDecl *OMD = *I;
706 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000707 SourceLocation LocStart = OMD->getLocStart();
708 SourceLocation LocEnd = OMD->getBody()->getLocStart();
709
710 const char *startBuf = SM->getCharacterData(LocStart);
711 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000712 ReplaceText(LocStart, endBuf-startBuf,
713 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000714 }
715
Ted Kremenek42730c52008-01-07 19:49:32 +0000716 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000717 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
718 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000719 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000720 ObjCMethodDecl *OMD = *I;
721 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000722 SourceLocation LocStart = OMD->getLocStart();
723 SourceLocation LocEnd = OMD->getBody()->getLocStart();
724
725 const char *startBuf = SM->getCharacterData(LocStart);
726 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000727 ReplaceText(LocStart, endBuf-startBuf,
728 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000729 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000730 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000731 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000732 else
Chris Lattner6216f292008-01-31 19:42:41 +0000733 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000734}
735
Ted Kremenek42730c52008-01-07 19:49:32 +0000736void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000737 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000738 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000739 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000740 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000741 ResultStr += ClassDecl->getName();
742 ResultStr += "\n";
743 ResultStr += "#define _REWRITER_typedef_";
744 ResultStr += ClassDecl->getName();
745 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000746 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000747 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000748 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000749 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000750 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000751 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000752 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000753
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000754 RewriteProperties(ClassDecl->getNumPropertyDecl(),
755 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000756 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000757 E = ClassDecl->instmeth_end(); I != E; ++I)
758 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000759 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000760 E = ClassDecl->classmeth_end(); I != E; ++I)
761 RewriteMethodDeclaration(*I);
762
Steve Naroff1ccf4632007-10-30 03:43:13 +0000763 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000764 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000765}
766
Steve Naroff6b759ce2007-11-15 02:58:25 +0000767Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000768 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000769 if (CurMethodDecl) {
770 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
771 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
772 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000773 // lookup which class implements the instance variable.
774 ObjCInterfaceDecl *clsDeclared = 0;
775 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
776 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5d933112008-03-12 23:15:19 +0000777
778 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000779 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000780 RecName += "_IMPL";
781 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
782 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
783 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
784 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
785 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
786 // Don't forget the parens to enforce the proper binding.
787 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
788 if (IV->isFreeIvar()) {
789 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
790 ReplaceStmt(IV, ME);
791 delete IV;
792 return ME;
793 } else {
Chris Lattnerb1548372008-01-31 19:37:57 +0000794 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5d933112008-03-12 23:15:19 +0000795 // Cannot delete IV->getBase(), since PE points to it.
796 // Replace the old base with the cast. This is important when doing
797 // embedded rewrites. For example, [newInv->_container addObject:0].
798 IV->setBase(PE);
799 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000800 }
801 }
802 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000803 }
Steve Naroff5d933112008-03-12 23:15:19 +0000804 // FIXME: Implement public ivar access from a function.
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000805 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
806 IV->getLocation(), D->getType());
807 ReplaceStmt(IV, Replacement);
808 delete IV;
809 return Replacement;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000810}
811
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000812//===----------------------------------------------------------------------===//
813// Function Body / Expression rewriting
814//===----------------------------------------------------------------------===//
815
Steve Naroff334fbc22007-11-09 15:20:18 +0000816Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000817 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
818 isa<DoStmt>(S) || isa<ForStmt>(S))
819 Stmts.push_back(S);
820 else if (isa<ObjCForCollectionStmt>(S)) {
821 Stmts.push_back(S);
822 ObjCBcLabelNo.push_back(++BcLabelCount);
823 }
824
Chris Lattner2c022162008-01-31 05:10:40 +0000825 SourceLocation OrigStmtEnd = S->getLocEnd();
826
827 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000828 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
829 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000830 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000831 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000832 if (newStmt)
833 *CI = newStmt;
834 }
Steve Naroffe9780582007-10-23 23:50:29 +0000835
836 // Handle specific things.
837 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
838 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000839
840 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
841 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000842
843 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
844 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000845
Steve Naroff0add5d22007-11-03 11:27:19 +0000846 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
847 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000848
Steve Naroff71226032007-10-24 22:48:43 +0000849 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
850 // Before we rewrite it, put the original message expression in a comment.
851 SourceLocation startLoc = MessExpr->getLocStart();
852 SourceLocation endLoc = MessExpr->getLocEnd();
853
854 const char *startBuf = SM->getCharacterData(startLoc);
855 const char *endBuf = SM->getCharacterData(endLoc);
856
857 std::string messString;
858 messString += "// ";
859 messString.append(startBuf, endBuf-startBuf+1);
860 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000861
Chris Lattner6216f292008-01-31 19:42:41 +0000862 // FIXME: Missing definition of
863 // InsertText(clang::SourceLocation, char const*, unsigned int).
864 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000865 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000866 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000867 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000868 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000869
Ted Kremenek42730c52008-01-07 19:49:32 +0000870 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
871 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000872
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000873 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
874 return RewriteObjCSynchronizedStmt(StmtTry);
875
Ted Kremenek42730c52008-01-07 19:49:32 +0000876 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
877 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000878
879 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
880 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000881
882 if (ObjCForCollectionStmt *StmtForCollection =
883 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000884 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000885 if (BreakStmt *StmtBreakStmt =
886 dyn_cast<BreakStmt>(S))
887 return RewriteBreakStmt(StmtBreakStmt);
888 if (ContinueStmt *StmtContinueStmt =
889 dyn_cast<ContinueStmt>(S))
890 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000891
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000892 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
893 isa<DoStmt>(S) || isa<ForStmt>(S)) {
894 assert(!Stmts.empty() && "Statement stack is empty");
895 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
896 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
897 && "Statement stack mismatch");
898 Stmts.pop_back();
899 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000900#if 0
901 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
902 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
903 // Get the new text.
904 std::ostringstream Buf;
905 Replacement->printPretty(Buf);
906 const std::string &Str = Buf.str();
907
908 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000909 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000910 delete S;
911 return Replacement;
912 }
913#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000914 // Return this stmt unmodified.
915 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000916}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000917
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000918/// SynthCountByEnumWithState - To print:
919/// ((unsigned int (*)
920/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
921/// (void *)objc_msgSend)((id)l_collection,
922/// sel_registerName(
923/// "countByEnumeratingWithState:objects:count:"),
924/// &enumState,
925/// (id *)items, (unsigned int)16)
926///
927void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
928 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
929 "id *, unsigned int))(void *)objc_msgSend)";
930 buf += "\n\t\t";
931 buf += "((id)l_collection,\n\t\t";
932 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
933 buf += "\n\t\t";
934 buf += "&enumState, "
935 "(id *)items, (unsigned int)16)";
936}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000937
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000938/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
939/// statement to exit to its outer synthesized loop.
940///
941Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
942 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
943 return S;
944 // replace break with goto __break_label
945 std::string buf;
946
947 SourceLocation startLoc = S->getLocStart();
948 buf = "goto __break_label_";
949 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000950 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000951
952 return 0;
953}
954
955/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
956/// statement to continue with its inner synthesized loop.
957///
958Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
959 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
960 return S;
961 // replace continue with goto __continue_label
962 std::string buf;
963
964 SourceLocation startLoc = S->getLocStart();
965 buf = "goto __continue_label_";
966 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000967 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000968
969 return 0;
970}
971
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000972/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000973/// It rewrites:
974/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000975
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000976/// Into:
977/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000978/// type elem;
979/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000980/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000981/// id l_collection = (id)collection;
982/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
983/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000984/// if (limit) {
985/// unsigned long startMutations = *enumState.mutationsPtr;
986/// do {
987/// unsigned long counter = 0;
988/// do {
989/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000990/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000991/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000992/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000993/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000994/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000995/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
996/// objects:items count:16]);
997/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000998/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000999/// }
1000/// else
1001/// elem = nil;
1002/// }
1003///
Chris Lattner2c022162008-01-31 05:10:40 +00001004Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1005 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001006 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1007 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1008 "ObjCForCollectionStmt Statement stack mismatch");
1009 assert(!ObjCBcLabelNo.empty() &&
1010 "ObjCForCollectionStmt - Label No stack empty");
1011
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001012 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001013 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001014 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001015 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001016 std::string buf;
1017 buf = "\n{\n\t";
1018 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1019 // type elem;
1020 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001021 elementTypeAsString = ElementType.getAsString();
1022 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001023 buf += " ";
1024 elementName = DS->getDecl()->getName();
1025 buf += elementName;
1026 buf += ";\n\t";
1027 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001028 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001029 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001030 elementTypeAsString = DR->getDecl()->getType().getAsString();
1031 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001032 else
1033 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1034
1035 // struct __objcFastEnumerationState enumState = { 0 };
1036 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1037 // id items[16];
1038 buf += "id items[16];\n\t";
1039 // id l_collection = (id)
1040 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001041 // Find start location of 'collection' the hard way!
1042 const char *startCollectionBuf = startBuf;
1043 startCollectionBuf += 3; // skip 'for'
1044 startCollectionBuf = strchr(startCollectionBuf, '(');
1045 startCollectionBuf++; // skip '('
1046 // find 'in' and skip it.
1047 while (*startCollectionBuf != ' ' ||
1048 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1049 (*(startCollectionBuf+3) != ' ' &&
1050 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1051 startCollectionBuf++;
1052 startCollectionBuf += 3;
1053
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001054 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001055 ReplaceText(startLoc, startCollectionBuf - startBuf,
1056 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001057 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001058 SourceLocation rightParenLoc = S->getRParenLoc();
1059 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1060 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001061 buf = ";\n\t";
1062
1063 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1064 // objects:items count:16];
1065 // which is synthesized into:
1066 // unsigned int limit =
1067 // ((unsigned int (*)
1068 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1069 // (void *)objc_msgSend)((id)l_collection,
1070 // sel_registerName(
1071 // "countByEnumeratingWithState:objects:count:"),
1072 // (struct __objcFastEnumerationState *)&state,
1073 // (id *)items, (unsigned int)16);
1074 buf += "unsigned long limit =\n\t\t";
1075 SynthCountByEnumWithState(buf);
1076 buf += ";\n\t";
1077 /// if (limit) {
1078 /// unsigned long startMutations = *enumState.mutationsPtr;
1079 /// do {
1080 /// unsigned long counter = 0;
1081 /// do {
1082 /// if (startMutations != *enumState.mutationsPtr)
1083 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001084 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001085 buf += "if (limit) {\n\t";
1086 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1087 buf += "do {\n\t\t";
1088 buf += "unsigned long counter = 0;\n\t\t";
1089 buf += "do {\n\t\t\t";
1090 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1091 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1092 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001093 buf += " = (";
1094 buf += elementTypeAsString;
1095 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001096 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001097 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001098
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001099 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001100 /// } while (counter < limit);
1101 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1102 /// objects:items count:16]);
1103 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001104 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001105 /// }
1106 /// else
1107 /// elem = nil;
1108 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001109 ///
1110 buf = ";\n\t";
1111 buf += "__continue_label_";
1112 buf += utostr(ObjCBcLabelNo.back());
1113 buf += ": ;";
1114 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001115 buf += "} while (counter < limit);\n\t";
1116 buf += "} while (limit = ";
1117 SynthCountByEnumWithState(buf);
1118 buf += ");\n\t";
1119 buf += elementName;
1120 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001121 buf += "__break_label_";
1122 buf += utostr(ObjCBcLabelNo.back());
1123 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001124 buf += "}\n\t";
1125 buf += "else\n\t\t";
1126 buf += elementName;
1127 buf += " = nil;\n";
1128 buf += "}\n";
1129 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001130 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001131 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001132 Stmts.pop_back();
1133 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001134 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001135}
1136
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001137/// RewriteObjCSynchronizedStmt -
1138/// This routine rewrites @synchronized(expr) stmt;
1139/// into:
1140/// objc_sync_enter(expr);
1141/// @try stmt @finally { objc_sync_exit(expr); }
1142///
1143Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1144 // Get the start location and compute the semi location.
1145 SourceLocation startLoc = S->getLocStart();
1146 const char *startBuf = SM->getCharacterData(startLoc);
1147
1148 assert((*startBuf == '@') && "bogus @synchronized location");
1149
1150 std::string buf;
1151 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001152 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001153 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1154 const char *endBuf = SM->getCharacterData(endLoc);
1155 endBuf++;
1156 const char *rparenBuf = strchr(endBuf, ')');
1157 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1158 buf = ");\n";
1159 // declare a new scope with two variables, _stack and _rethrow.
1160 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1161 buf += "int buf[18/*32-bit i386*/];\n";
1162 buf += "char *pointers[4];} _stack;\n";
1163 buf += "id volatile _rethrow = 0;\n";
1164 buf += "objc_exception_try_enter(&_stack);\n";
1165 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001166 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001167 startLoc = S->getSynchBody()->getLocEnd();
1168 startBuf = SM->getCharacterData(startLoc);
1169
1170 assert((*startBuf == '}') && "bogus @try block");
1171 SourceLocation lastCurlyLoc = startLoc;
1172 buf = "}\nelse {\n";
1173 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1174 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1175 // FIXME: This must be objc_sync_exit(syncExpr);
1176 buf += " objc_sync_exit();\n";
1177 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1178 buf += "}\n";
1179 buf += "}";
1180
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001181 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001182 return 0;
1183}
1184
Ted Kremenek42730c52008-01-07 19:49:32 +00001185Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001186 // Get the start location and compute the semi location.
1187 SourceLocation startLoc = S->getLocStart();
1188 const char *startBuf = SM->getCharacterData(startLoc);
1189
1190 assert((*startBuf == '@') && "bogus @try location");
1191
1192 std::string buf;
1193 // declare a new scope with two variables, _stack and _rethrow.
1194 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1195 buf += "int buf[18/*32-bit i386*/];\n";
1196 buf += "char *pointers[4];} _stack;\n";
1197 buf += "id volatile _rethrow = 0;\n";
1198 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001199 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001200
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001201 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001202
1203 startLoc = S->getTryBody()->getLocEnd();
1204 startBuf = SM->getCharacterData(startLoc);
1205
1206 assert((*startBuf == '}') && "bogus @try block");
1207
1208 SourceLocation lastCurlyLoc = startLoc;
1209
1210 startLoc = startLoc.getFileLocWithOffset(1);
1211 buf = " /* @catch begin */ else {\n";
1212 buf += " id _caught = objc_exception_extract(&_stack);\n";
1213 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001214 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001215 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1216 buf += " else { /* @catch continue */";
1217
Chris Lattner6216f292008-01-31 19:42:41 +00001218 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001219
1220 bool sawIdTypedCatch = false;
1221 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001222 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001223 while (catchList) {
1224 Stmt *catchStmt = catchList->getCatchParamStmt();
1225
1226 if (catchList == S->getCatchStmts())
1227 buf = "if ("; // we are generating code for the first catch clause
1228 else
1229 buf = "else if (";
1230 startLoc = catchList->getLocStart();
1231 startBuf = SM->getCharacterData(startLoc);
1232
1233 assert((*startBuf == '@') && "bogus @catch location");
1234
1235 const char *lParenLoc = strchr(startBuf, '(');
1236
Steve Naroff397c4ce2008-02-01 22:08:12 +00001237 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001238 // Now rewrite the body...
1239 lastCatchBody = catchList->getCatchBody();
1240 SourceLocation rParenLoc = catchList->getRParenLoc();
1241 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1242 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1243 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1244 assert((*rParenBuf == ')') && "bogus @catch paren location");
1245 assert((*bodyBuf == '{') && "bogus @catch body location");
1246
1247 buf += "1) { id _tmp = _caught;";
1248 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1249 buf.c_str(), buf.size());
1250 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001251 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001252 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001253 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001254 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001255 sawIdTypedCatch = true;
1256 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001257 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001258
Ted Kremenek42730c52008-01-07 19:49:32 +00001259 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001260 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001261 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001262 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001263 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001264 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001265 }
1266 }
1267 // Now rewrite the body...
1268 lastCatchBody = catchList->getCatchBody();
1269 SourceLocation rParenLoc = catchList->getRParenLoc();
1270 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1271 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1272 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1273 assert((*rParenBuf == ')') && "bogus @catch paren location");
1274 assert((*bodyBuf == '{') && "bogus @catch body location");
1275
1276 buf = " = _caught;";
1277 // Here we replace ") {" with "= _caught;" (which initializes and
1278 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001279 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001280 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001281 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001282 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001283 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001284 catchList = catchList->getNextCatchStmt();
1285 }
1286 // Complete the catch list...
1287 if (lastCatchBody) {
1288 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1289 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1290 assert((*bodyBuf == '}') && "bogus @catch body location");
1291 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1292 buf = " } } /* @catch end */\n";
1293
Chris Lattner6216f292008-01-31 19:42:41 +00001294 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001295
1296 // Set lastCurlyLoc
1297 lastCurlyLoc = lastCatchBody->getLocEnd();
1298 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001299 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001300 startLoc = finalStmt->getLocStart();
1301 startBuf = SM->getCharacterData(startLoc);
1302 assert((*startBuf == '@') && "bogus @finally start");
1303
1304 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001305 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001306
1307 Stmt *body = finalStmt->getFinallyBody();
1308 SourceLocation startLoc = body->getLocStart();
1309 SourceLocation endLoc = body->getLocEnd();
1310 const char *startBuf = SM->getCharacterData(startLoc);
1311 const char *endBuf = SM->getCharacterData(endLoc);
1312 assert((*startBuf == '{') && "bogus @finally body location");
1313 assert((*endBuf == '}') && "bogus @finally body location");
1314
1315 startLoc = startLoc.getFileLocWithOffset(1);
1316 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001317 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001318 endLoc = endLoc.getFileLocWithOffset(-1);
1319 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001320 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001321
1322 // Set lastCurlyLoc
1323 lastCurlyLoc = body->getLocEnd();
1324 }
1325 // Now emit the final closing curly brace...
1326 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1327 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001328 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001329 return 0;
1330}
1331
Ted Kremenek42730c52008-01-07 19:49:32 +00001332Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001333 return 0;
1334}
1335
Ted Kremenek42730c52008-01-07 19:49:32 +00001336Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001337 return 0;
1338}
1339
Chris Lattnerb1548372008-01-31 19:37:57 +00001340// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001341// the throw expression is typically a message expression that's already
1342// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001343Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001344 // Get the start location and compute the semi location.
1345 SourceLocation startLoc = S->getLocStart();
1346 const char *startBuf = SM->getCharacterData(startLoc);
1347
1348 assert((*startBuf == '@') && "bogus @throw location");
1349
1350 std::string buf;
1351 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001352 if (S->getThrowExpr())
1353 buf = "objc_exception_throw(";
1354 else // add an implicit argument
1355 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001356 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001357 const char *semiBuf = strchr(startBuf, ';');
1358 assert((*semiBuf == ';') && "@throw: can't find ';'");
1359 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1360 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001361 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001362 return 0;
1363}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001364
Chris Lattner0021f452007-10-24 16:57:36 +00001365Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001366 // Create a new string expression.
1367 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001368 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001369 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1370 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001371 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1372 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001373 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001374 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001375
Chris Lattner4478db92007-11-30 22:53:43 +00001376 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001377 delete Exp;
1378 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001379}
1380
Steve Naroff296b74f2007-11-05 14:50:49 +00001381Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1382 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1383 // Create a call to sel_registerName("selName").
1384 llvm::SmallVector<Expr*, 8> SelExprs;
1385 QualType argType = Context->getPointerType(Context->CharTy);
1386 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1387 Exp->getSelector().getName().size(),
1388 false, argType, SourceLocation(),
1389 SourceLocation()));
1390 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1391 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001392 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001393 delete Exp;
1394 return SelExp;
1395}
1396
Steve Naroff71226032007-10-24 22:48:43 +00001397CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1398 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001399 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001400 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001401
1402 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001403 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001404
1405 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001406 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001407 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1408
1409 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001410
Steve Naroff71226032007-10-24 22:48:43 +00001411 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1412}
1413
Steve Naroffc8a92d12007-11-01 13:24:47 +00001414static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1415 const char *&startRef, const char *&endRef) {
1416 while (startBuf < endBuf) {
1417 if (*startBuf == '<')
1418 startRef = startBuf; // mark the start.
1419 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001420 if (startRef && *startRef == '<') {
1421 endRef = startBuf; // mark the end.
1422 return true;
1423 }
1424 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001425 }
1426 startBuf++;
1427 }
1428 return false;
1429}
1430
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001431static void scanToNextArgument(const char *&argRef) {
1432 int angle = 0;
1433 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1434 if (*argRef == '<')
1435 angle++;
1436 else if (*argRef == '>')
1437 angle--;
1438 argRef++;
1439 }
1440 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1441}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001442
Steve Naroffc8a92d12007-11-01 13:24:47 +00001443bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001444
Ted Kremenek42730c52008-01-07 19:49:32 +00001445 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001446 return true;
1447
Ted Kremenek42730c52008-01-07 19:49:32 +00001448 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001449 return true;
1450
Steve Naroffc8a92d12007-11-01 13:24:47 +00001451 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001452 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001453 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001454 return true; // we have "Class <Protocol> *".
1455 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001456 return false;
1457}
1458
Ted Kremenek42730c52008-01-07 19:49:32 +00001459void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001460 SourceLocation Loc;
1461 QualType Type;
1462 const FunctionTypeProto *proto = 0;
1463 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1464 Loc = VD->getLocation();
1465 Type = VD->getType();
1466 }
1467 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1468 Loc = FD->getLocation();
1469 // Check for ObjC 'id' and class types that have been adorned with protocol
1470 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1471 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1472 assert(funcType && "missing function type");
1473 proto = dyn_cast<FunctionTypeProto>(funcType);
1474 if (!proto)
1475 return;
1476 Type = proto->getResultType();
1477 }
1478 else
1479 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001480
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001481 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001482 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001483
1484 const char *endBuf = SM->getCharacterData(Loc);
1485 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001486 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001487 startBuf--; // scan backward (from the decl location) for return type.
1488 const char *startRef = 0, *endRef = 0;
1489 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1490 // Get the locations of the startRef, endRef.
1491 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1492 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1493 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001494 InsertText(LessLoc, "/*", 2);
1495 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001496 }
1497 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001498 if (!proto)
1499 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001500 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001501 const char *startBuf = SM->getCharacterData(Loc);
1502 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001503 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1504 if (needToScanForQualifiers(proto->getArgType(i))) {
1505 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001506
Steve Naroffc8a92d12007-11-01 13:24:47 +00001507 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001508 // scan forward (from the decl location) for argument types.
1509 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001510 const char *startRef = 0, *endRef = 0;
1511 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1512 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001513 SourceLocation LessLoc =
1514 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1515 SourceLocation GreaterLoc =
1516 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001517 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001518 InsertText(LessLoc, "/*", 2);
1519 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001520 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001521 startBuf = ++endBuf;
1522 }
1523 else {
1524 while (*startBuf != ')' && *startBuf != ',')
1525 startBuf++; // scan forward (from the decl location) for argument types.
1526 startBuf++;
1527 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001528 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001529}
1530
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001531// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1532void RewriteTest::SynthSelGetUidFunctionDecl() {
1533 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
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->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001538 &ArgTys[0], ArgTys.size(),
1539 false /*isVariadic*/);
1540 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1541 SelGetUidIdent, getFuncType,
1542 FunctionDecl::Extern, false, 0);
1543}
1544
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001545// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1546void RewriteTest::SynthGetProtocolFunctionDecl() {
1547 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1548 llvm::SmallVector<QualType, 16> ArgTys;
1549 ArgTys.push_back(Context->getPointerType(
1550 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001551 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001552 &ArgTys[0], ArgTys.size(),
1553 false /*isVariadic*/);
1554 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1555 SelGetProtoIdent, getFuncType,
1556 FunctionDecl::Extern, false, 0);
1557}
1558
Steve Naroff02a82aa2007-10-30 23:14:51 +00001559void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1560 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001561 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001562 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001563 return;
1564 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001565 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001566}
1567
Steve Naroffbec4bf52008-03-11 17:37:02 +00001568// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1569void RewriteTest::SynthSuperContructorFunctionDecl() {
1570 if (SuperContructorFunctionDecl)
1571 return;
1572 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1573 llvm::SmallVector<QualType, 16> ArgTys;
1574 QualType argT = Context->getObjCIdType();
1575 assert(!argT.isNull() && "Can't find 'id' type");
1576 ArgTys.push_back(argT);
1577 ArgTys.push_back(argT);
1578 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1579 &ArgTys[0], ArgTys.size(),
1580 false);
1581 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1582 msgSendIdent, msgSendType,
1583 FunctionDecl::Extern, false, 0);
1584}
1585
Steve Naroff02a82aa2007-10-30 23:14:51 +00001586// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1587void RewriteTest::SynthMsgSendFunctionDecl() {
1588 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1589 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001590 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001591 assert(!argT.isNull() && "Can't find 'id' type");
1592 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001593 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001594 assert(!argT.isNull() && "Can't find 'SEL' type");
1595 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001596 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001597 &ArgTys[0], ArgTys.size(),
1598 true /*isVariadic*/);
1599 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1600 msgSendIdent, msgSendType,
1601 FunctionDecl::Extern, false, 0);
1602}
1603
Steve Naroff764c1ae2007-11-15 10:28:18 +00001604// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1605void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1606 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1607 llvm::SmallVector<QualType, 16> ArgTys;
1608 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1609 &Context->Idents.get("objc_super"), 0);
1610 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1611 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1612 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001614 assert(!argT.isNull() && "Can't find 'SEL' type");
1615 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001616 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001617 &ArgTys[0], ArgTys.size(),
1618 true /*isVariadic*/);
1619 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1620 msgSendIdent, msgSendType,
1621 FunctionDecl::Extern, false, 0);
1622}
1623
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001624// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1625void RewriteTest::SynthMsgSendStretFunctionDecl() {
1626 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1627 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001628 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001629 assert(!argT.isNull() && "Can't find 'id' type");
1630 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001631 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001632 assert(!argT.isNull() && "Can't find 'SEL' type");
1633 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001634 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001635 &ArgTys[0], ArgTys.size(),
1636 true /*isVariadic*/);
1637 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1638 msgSendIdent, msgSendType,
1639 FunctionDecl::Extern, false, 0);
1640}
1641
1642// SynthMsgSendSuperStretFunctionDecl -
1643// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1644void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1645 IdentifierInfo *msgSendIdent =
1646 &Context->Idents.get("objc_msgSendSuper_stret");
1647 llvm::SmallVector<QualType, 16> ArgTys;
1648 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1649 &Context->Idents.get("objc_super"), 0);
1650 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1651 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1652 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001653 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001654 assert(!argT.isNull() && "Can't find 'SEL' type");
1655 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001656 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001657 &ArgTys[0], ArgTys.size(),
1658 true /*isVariadic*/);
1659 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1660 msgSendIdent, msgSendType,
1661 FunctionDecl::Extern, false, 0);
1662}
1663
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001664// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1665void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1666 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1667 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001668 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001669 assert(!argT.isNull() && "Can't find 'id' type");
1670 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001671 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001672 assert(!argT.isNull() && "Can't find 'SEL' type");
1673 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001674 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001675 &ArgTys[0], ArgTys.size(),
1676 true /*isVariadic*/);
1677 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1678 msgSendIdent, msgSendType,
1679 FunctionDecl::Extern, false, 0);
1680}
1681
Steve Naroff02a82aa2007-10-30 23:14:51 +00001682// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1683void RewriteTest::SynthGetClassFunctionDecl() {
1684 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
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 Naroff02a82aa2007-10-30 23:14:51 +00001689 &ArgTys[0], ArgTys.size(),
1690 false /*isVariadic*/);
1691 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1692 getClassIdent, getClassType,
1693 FunctionDecl::Extern, false, 0);
1694}
1695
Steve Naroff3b1caac2007-12-07 03:50:46 +00001696// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1697void RewriteTest::SynthGetMetaClassFunctionDecl() {
1698 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
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 Naroff3b1caac2007-12-07 03:50:46 +00001703 &ArgTys[0], ArgTys.size(),
1704 false /*isVariadic*/);
1705 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1706 getClassIdent, getClassType,
1707 FunctionDecl::Extern, false, 0);
1708}
1709
Steve Naroffabb96362007-11-08 14:30:50 +00001710// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1711void RewriteTest::SynthCFStringFunctionDecl() {
1712 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1713 llvm::SmallVector<QualType, 16> ArgTys;
1714 ArgTys.push_back(Context->getPointerType(
1715 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001716 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001717 &ArgTys[0], ArgTys.size(),
1718 false /*isVariadic*/);
1719 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1720 getClassIdent, getClassType,
1721 FunctionDecl::Extern, false, 0);
1722}
1723
Steve Naroff0add5d22007-11-03 11:27:19 +00001724Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001725#if 1
1726 // This rewrite is specific to GCC, which has builtin support for CFString.
1727 if (!CFStringFunctionDecl)
1728 SynthCFStringFunctionDecl();
1729 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1730 llvm::SmallVector<Expr*, 8> StrExpr;
1731 StrExpr.push_back(Exp->getString());
1732 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1733 &StrExpr[0], StrExpr.size());
1734 // cast to NSConstantString *
1735 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001736 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001737 delete Exp;
1738 return cast;
1739#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001740 assert(ConstantStringClassReference && "Can't find constant string reference");
1741 llvm::SmallVector<Expr*, 4> InitExprs;
1742
1743 // Synthesize "(Class)&_NSConstantStringClassReference"
1744 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1745 ConstantStringClassReference->getType(),
1746 SourceLocation());
1747 QualType expType = Context->getPointerType(ClsRef->getType());
1748 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1749 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001750 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001751 SourceLocation());
1752 InitExprs.push_back(cast); // set the 'isa'.
1753 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1754 unsigned IntSize = static_cast<unsigned>(
1755 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1756 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1757 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1758 Exp->getLocStart());
1759 InitExprs.push_back(len); // set "int numBytes".
1760
1761 // struct NSConstantString
1762 QualType CFConstantStrType = Context->getCFConstantStringType();
1763 // (struct NSConstantString) { <exprs from above> }
1764 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1765 &InitExprs[0], InitExprs.size(),
1766 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001767 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001768 // struct NSConstantString *
1769 expType = Context->getPointerType(StrRep->getType());
1770 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1771 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001772 // cast to NSConstantString *
1773 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001774 ReplaceStmt(Exp, cast);
Steve Naroff0add5d22007-11-03 11:27:19 +00001775 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001776 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001777#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001778}
1779
Ted Kremenek42730c52008-01-07 19:49:32 +00001780ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001781 // check if we are sending a message to 'super'
1782 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001783 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1784 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1785 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1786 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001787 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001788 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001789 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001790 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001791 if (ObjCInterfaceType *IT =
1792 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001793 if (IT->getDecl() ==
1794 CurMethodDecl->getClassInterface()->getSuperClass())
1795 return IT->getDecl();
1796 }
1797 }
1798 }
1799 }
1800 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001801 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001802 }
1803 return 0;
1804}
1805
1806// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1807QualType RewriteTest::getSuperStructType() {
1808 if (!SuperStructDecl) {
1809 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1810 &Context->Idents.get("objc_super"), 0);
1811 QualType FieldTypes[2];
1812
1813 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001814 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001815 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001816 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001817 // Create fields
1818 FieldDecl *FieldDecls[2];
1819
1820 for (unsigned i = 0; i < 2; ++i)
1821 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1822
1823 SuperStructDecl->defineBody(FieldDecls, 4);
1824 }
1825 return Context->getTagDeclType(SuperStructDecl);
1826}
1827
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001828Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001829 if (!SelGetUidFunctionDecl)
1830 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001831 if (!MsgSendFunctionDecl)
1832 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001833 if (!MsgSendSuperFunctionDecl)
1834 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001835 if (!MsgSendStretFunctionDecl)
1836 SynthMsgSendStretFunctionDecl();
1837 if (!MsgSendSuperStretFunctionDecl)
1838 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001839 if (!MsgSendFpretFunctionDecl)
1840 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001841 if (!GetClassFunctionDecl)
1842 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001843 if (!GetMetaClassFunctionDecl)
1844 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001845
Steve Naroff764c1ae2007-11-15 10:28:18 +00001846 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001847 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1848 // May need to use objc_msgSend_stret() as well.
1849 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001850 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001851 QualType resultType = mDecl->getResultType();
1852 if (resultType.getCanonicalType()->isStructureType()
1853 || resultType.getCanonicalType()->isUnionType())
1854 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001855 else if (resultType.getCanonicalType()->isRealFloatingType())
1856 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001857 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001858
Steve Naroff71226032007-10-24 22:48:43 +00001859 // Synthesize a call to objc_msgSend().
1860 llvm::SmallVector<Expr*, 8> MsgExprs;
1861 IdentifierInfo *clsName = Exp->getClassName();
1862
1863 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1864 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001865 if (!strcmp(clsName->getName(), "super")) {
1866 MsgSendFlavor = MsgSendSuperFunctionDecl;
1867 if (MsgSendStretFlavor)
1868 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1869 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1870
Ted Kremenek42730c52008-01-07 19:49:32 +00001871 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001872 CurMethodDecl->getClassInterface()->getSuperClass();
1873
1874 llvm::SmallVector<Expr*, 4> InitExprs;
1875
1876 // set the receiver to self, the first argument to all methods.
1877 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001878 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001879 SourceLocation()));
1880 llvm::SmallVector<Expr*, 8> ClsExprs;
1881 QualType argType = Context->getPointerType(Context->CharTy);
1882 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1883 SuperDecl->getIdentifier()->getLength(),
1884 false, argType, SourceLocation(),
1885 SourceLocation()));
1886 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1887 &ClsExprs[0],
1888 ClsExprs.size());
1889 // To turn off a warning, type-cast to 'id'
1890 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001891 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001892 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1893 // struct objc_super
1894 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001895 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001896
Steve Naroffdee066b2008-03-11 18:14:26 +00001897 if (LangOpts.Microsoft) {
1898 SynthSuperContructorFunctionDecl();
1899 // Simulate a contructor call...
1900 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1901 superType, SourceLocation());
1902 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1903 superType, SourceLocation());
1904 } else {
1905 // (struct objc_super) { <exprs from above> }
1906 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1907 &InitExprs[0], InitExprs.size(),
1908 SourceLocation());
1909 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1910 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001911 // struct objc_super *
1912 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1913 Context->getPointerType(SuperRep->getType()),
1914 SourceLocation());
1915 MsgExprs.push_back(Unop);
1916 } else {
1917 llvm::SmallVector<Expr*, 8> ClsExprs;
1918 QualType argType = Context->getPointerType(Context->CharTy);
1919 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1920 clsName->getLength(),
1921 false, argType, SourceLocation(),
1922 SourceLocation()));
1923 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1924 &ClsExprs[0],
1925 ClsExprs.size());
1926 MsgExprs.push_back(Cls);
1927 }
Steve Naroff885e2122007-11-14 23:54:14 +00001928 } else { // instance message.
1929 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001930
Ted Kremenek42730c52008-01-07 19:49:32 +00001931 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001932 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001933 if (MsgSendStretFlavor)
1934 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001935 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1936
1937 llvm::SmallVector<Expr*, 4> InitExprs;
1938
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001939 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001940 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001941 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001942
1943 llvm::SmallVector<Expr*, 8> ClsExprs;
1944 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001945 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1946 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001947 false, argType, SourceLocation(),
1948 SourceLocation()));
1949 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001950 &ClsExprs[0],
1951 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001952 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001953 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001954 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001955 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001956 // struct objc_super
1957 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001958 Expr *SuperRep;
1959
1960 if (LangOpts.Microsoft) {
1961 SynthSuperContructorFunctionDecl();
1962 // Simulate a contructor call...
1963 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1964 superType, SourceLocation());
1965 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1966 superType, SourceLocation());
1967 } else {
1968 // (struct objc_super) { <exprs from above> }
1969 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1970 &InitExprs[0], InitExprs.size(),
1971 SourceLocation());
1972 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1973 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001974 // struct objc_super *
1975 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1976 Context->getPointerType(SuperRep->getType()),
1977 SourceLocation());
1978 MsgExprs.push_back(Unop);
1979 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001980 // Remove all type-casts because it may contain objc-style types; e.g.
1981 // Foo<Proto> *.
1982 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1983 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001984 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001985 MsgExprs.push_back(recExpr);
1986 }
Steve Naroff885e2122007-11-14 23:54:14 +00001987 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001988 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001989 llvm::SmallVector<Expr*, 8> SelExprs;
1990 QualType argType = Context->getPointerType(Context->CharTy);
1991 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1992 Exp->getSelector().getName().size(),
1993 false, argType, SourceLocation(),
1994 SourceLocation()));
1995 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1996 &SelExprs[0], SelExprs.size());
1997 MsgExprs.push_back(SelExp);
1998
1999 // Now push any user supplied arguments.
2000 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002001 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002002 // Make all implicit casts explicit...ICE comes in handy:-)
2003 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2004 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002005 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2006 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002007 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002008 }
2009 // Make id<P...> cast into an 'id' cast.
2010 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002011 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002012 while ((CE = dyn_cast<CastExpr>(userExpr)))
2013 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002015 userExpr, SourceLocation());
2016 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002017 }
Steve Naroff885e2122007-11-14 23:54:14 +00002018 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002019 // We've transferred the ownership to MsgExprs. Null out the argument in
2020 // the original expression, since we will delete it below.
2021 Exp->setArg(i, 0);
2022 }
Steve Naroff0744c472007-11-04 22:37:50 +00002023 // Generate the funky cast.
2024 CastExpr *cast;
2025 llvm::SmallVector<QualType, 8> ArgTypes;
2026 QualType returnType;
2027
2028 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002029 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2030 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2031 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002032 ArgTypes.push_back(Context->getObjCIdType());
2033 ArgTypes.push_back(Context->getObjCSelType());
2034 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002035 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00002036 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002037 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2038 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002039 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002040 ArgTypes.push_back(t);
2041 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002042 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2043 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002044 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002045 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002046 }
2047 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002048 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002049
2050 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002051 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2052 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002053
2054 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2055 // If we don't do this cast, we get the following bizarre warning/note:
2056 // xx.m:13: warning: function called through a non-compatible type
2057 // xx.m:13: note: if this code is reached, the program will abort
2058 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2059 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002060
Steve Naroff0744c472007-11-04 22:37:50 +00002061 // Now do the "normal" pointer to function cast.
2062 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002063 &ArgTypes[0], ArgTypes.size(),
2064 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00002065 castType = Context->getPointerType(castType);
2066 cast = new CastExpr(castType, cast, SourceLocation());
2067
2068 // Don't forget the parens to enforce the proper binding.
2069 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2070
2071 const FunctionType *FT = msgSendType->getAsFunctionType();
2072 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2073 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002074 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002075 if (MsgSendStretFlavor) {
2076 // We have the method which returns a struct/union. Must also generate
2077 // call to objc_msgSend_stret and hang both varieties on a conditional
2078 // expression which dictate which one to envoke depending on size of
2079 // method's return type.
2080
2081 // Create a reference to the objc_msgSend_stret() declaration.
2082 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2083 SourceLocation());
2084 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2085 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2086 SourceLocation());
2087 // Now do the "normal" pointer to function cast.
2088 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002089 &ArgTypes[0], ArgTypes.size(),
2090 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002091 castType = Context->getPointerType(castType);
2092 cast = new CastExpr(castType, cast, SourceLocation());
2093
2094 // Don't forget the parens to enforce the proper binding.
2095 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2096
2097 FT = msgSendType->getAsFunctionType();
2098 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2099 FT->getResultType(), SourceLocation());
2100
2101 // Build sizeof(returnType)
2102 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2103 returnType, Context->getSizeType(),
2104 SourceLocation(), SourceLocation());
2105 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2106 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2107 // For X86 it is more complicated and some kind of target specific routine
2108 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002109 unsigned IntSize =
2110 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002111 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2112 Context->IntTy,
2113 SourceLocation());
2114 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2115 BinaryOperator::LE,
2116 Context->IntTy,
2117 SourceLocation());
2118 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2119 ConditionalOperator *CondExpr =
2120 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002121 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002122 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002123 return ReplacingStmt;
2124}
2125
2126Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2127 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002128 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002129 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002130
Chris Lattner0021f452007-10-24 16:57:36 +00002131 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002132 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002133}
2134
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002135/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2136/// call to objc_getProtocol("proto-name").
2137Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2138 if (!GetProtocolFunctionDecl)
2139 SynthGetProtocolFunctionDecl();
2140 // Create a call to objc_getProtocol("ProtocolName").
2141 llvm::SmallVector<Expr*, 8> ProtoExprs;
2142 QualType argType = Context->getPointerType(Context->CharTy);
2143 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2144 strlen(Exp->getProtocol()->getName()),
2145 false, argType, SourceLocation(),
2146 SourceLocation()));
2147 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2148 &ProtoExprs[0],
2149 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002150 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002151 delete Exp;
2152 return ProtoExp;
2153
2154}
2155
Ted Kremenek42730c52008-01-07 19:49:32 +00002156/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002157/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002158void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002159 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002160 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2161 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002162 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002163 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002164 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002165 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002166 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002167 SourceLocation LocStart = CDecl->getLocStart();
2168 SourceLocation LocEnd = CDecl->getLocEnd();
2169
2170 const char *startBuf = SM->getCharacterData(LocStart);
2171 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002172 // If no ivars and no root or if its root, directly or indirectly,
2173 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002174 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002175 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002176 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002177 return;
2178 }
2179
2180 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002181 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002182 Result += "\nstruct ";
2183 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002184 if (LangOpts.Microsoft)
2185 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002186
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002187 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002188 const char *cursor = strchr(startBuf, '{');
2189 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002190 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002191
2192 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002193 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002194 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002195 Result = "\n struct ";
2196 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002197 Result += "_IMPL ";
2198 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002199 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002200
2201 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002202 SourceLocation OnePastCurly =
2203 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2204 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002205 }
2206 cursor++; // past '{'
2207
2208 // Now comment out any visibility specifiers.
2209 while (cursor < endBuf) {
2210 if (*cursor == '@') {
2211 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002212 // Skip whitespace.
2213 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2214 /*scan*/;
2215
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002216 // FIXME: presence of @public, etc. inside comment results in
2217 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002218 if (!strncmp(cursor, "public", strlen("public")) ||
2219 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002220 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002221 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002222 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002223 // FIXME: If there are cases where '<' is used in ivar declaration part
2224 // of user code, then scan the ivar list and use needToScanForQualifiers
2225 // for type checking.
2226 else if (*cursor == '<') {
2227 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002228 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002229 cursor = strchr(cursor, '>');
2230 cursor++;
2231 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002232 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002233 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002234 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002235 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002236 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002237 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002238 } else { // we don't have any instance variables - insert super struct.
2239 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2240 Result += " {\n struct ";
2241 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002242 Result += "_IMPL ";
2243 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002244 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002245 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002246 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002247 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002248 if (!ObjCSynthesizedStructs.insert(CDecl))
2249 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002250}
2251
Ted Kremenek42730c52008-01-07 19:49:32 +00002252// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002253/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002254void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002255 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002256 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002257 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002258 const char *ClassName,
2259 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002260 if (MethodBegin == MethodEnd) return;
2261
Fariborz Jahanian04455192007-10-22 21:41:37 +00002262 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002263 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002264 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002265 SEL _cmd;
2266 char *method_types;
2267 void *_imp;
2268 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002269 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002270 Result += "\nstruct _objc_method {\n";
2271 Result += "\tSEL _cmd;\n";
2272 Result += "\tchar *method_types;\n";
2273 Result += "\tvoid *_imp;\n";
2274 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002275
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002276 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002277 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002278
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002279 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002280
2281 /* struct {
2282 struct _objc_method_list *next_method;
2283 int method_count;
2284 struct _objc_method method_list[];
2285 }
2286 */
2287 Result += "\nstatic struct {\n";
2288 Result += "\tstruct _objc_method_list *next_method;\n";
2289 Result += "\tint method_count;\n";
2290 Result += "\tstruct _objc_method method_list[";
2291 Result += utostr(MethodEnd-MethodBegin);
2292 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002293 Result += prefix;
2294 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2295 Result += "_METHODS_";
2296 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002297 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002298 Result += IsInstanceMethod ? "inst" : "cls";
2299 Result += "_meth\")))= ";
2300 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002301
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002302 Result += "\t,{{(SEL)\"";
2303 Result += (*MethodBegin)->getSelector().getName().c_str();
2304 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002305 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002306 Result += "\", \"";
2307 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002308 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002309 Result += MethodInternalNames[*MethodBegin];
2310 Result += "}\n";
2311 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2312 Result += "\t ,{(SEL)\"";
2313 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002314 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002315 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002316 Result += "\", \"";
2317 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002318 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002319 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002320 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002321 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002322 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002323}
2324
Ted Kremenek42730c52008-01-07 19:49:32 +00002325/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2326void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002327 int NumProtocols,
2328 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002329 const char *ClassName,
2330 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002331 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002332 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002333 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002334 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002335 // Output struct protocol_methods holder of method selector and type.
2336 if (!objc_protocol_methods &&
2337 (PDecl->getNumInstanceMethods() > 0
2338 || PDecl->getNumClassMethods() > 0)) {
2339 /* struct protocol_methods {
2340 SEL _cmd;
2341 char *method_types;
2342 }
2343 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002344 Result += "\nstruct protocol_methods {\n";
2345 Result += "\tSEL _cmd;\n";
2346 Result += "\tchar *method_types;\n";
2347 Result += "};\n";
2348
Steve Naroff27429432008-03-12 01:06:30 +00002349 objc_protocol_methods = true;
2350 }
2351 int NumMethods = PDecl->getNumInstanceMethods();
2352 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002353 /* struct _objc_protocol_method_list {
2354 int protocol_method_count;
2355 struct protocol_methods protocols[];
2356 }
2357 */
Steve Naroff27429432008-03-12 01:06:30 +00002358 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002359 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002360 Result += "\tstruct protocol_methods protocols[";
2361 Result += utostr(NumMethods);
2362 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002363 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002364 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002365 "{\n\t" + utostr(NumMethods) + "\n";
2366
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002367 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002368 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002369 E = PDecl->instmeth_end(); I != E; ++I) {
2370 if (I == PDecl->instmeth_begin())
2371 Result += "\t ,{{(SEL)\"";
2372 else
2373 Result += "\t ,{(SEL)\"";
2374 Result += (*I)->getSelector().getName().c_str();
2375 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002376 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002377 Result += "\", \"";
2378 Result += MethodTypeString;
2379 Result += "\"}\n";
2380 }
2381 Result += "\t }\n};\n";
2382 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002383
2384 // Output class methods declared in this protocol.
2385 NumMethods = PDecl->getNumClassMethods();
2386 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002387 /* struct _objc_protocol_method_list {
2388 int protocol_method_count;
2389 struct protocol_methods protocols[];
2390 }
2391 */
2392 Result += "\nstatic struct {\n";
2393 Result += "\tint protocol_method_count;\n";
2394 Result += "\tstruct protocol_methods protocols[";
2395 Result += utostr(NumMethods);
2396 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002397 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002398 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002399 "{\n\t";
2400 Result += utostr(NumMethods);
2401 Result += "\n";
2402
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002403 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002404 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002405 E = PDecl->classmeth_end(); I != E; ++I) {
2406 if (I == PDecl->classmeth_begin())
2407 Result += "\t ,{{(SEL)\"";
2408 else
2409 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002410 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002411 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002412 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002413 Result += "\", \"";
2414 Result += MethodTypeString;
2415 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002416 }
2417 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002418 }
2419 // Output:
2420 /* struct _objc_protocol {
2421 // Objective-C 1.0 extensions
2422 struct _objc_protocol_extension *isa;
2423 char *protocol_name;
2424 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002425 struct _objc_protocol_method_list *instance_methods;
2426 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002427 };
2428 */
2429 static bool objc_protocol = false;
2430 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002431 Result += "\nstruct _objc_protocol {\n";
2432 Result += "\tstruct _objc_protocol_extension *isa;\n";
2433 Result += "\tchar *protocol_name;\n";
2434 Result += "\tstruct _objc_protocol **protocol_list;\n";
2435 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2436 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2437 Result += "};\n";
2438
Fariborz Jahanian04455192007-10-22 21:41:37 +00002439 objc_protocol = true;
2440 }
2441
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002442 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2443 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002444 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002445 "{\n\t0, \"";
2446 Result += PDecl->getName();
2447 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002448 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002449 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002450 Result += PDecl->getName();
2451 Result += ", ";
2452 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002453 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002454 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002455 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002456 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002457 Result += PDecl->getName();
2458 Result += "\n";
2459 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002460 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002461 Result += "0\n";
2462 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002463 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002464 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002465 /* struct _objc_protocol_list {
2466 struct _objc_protocol_list *next;
2467 int protocol_count;
2468 struct _objc_protocol *class_protocols[];
2469 }
2470 */
2471 Result += "\nstatic struct {\n";
2472 Result += "\tstruct _objc_protocol_list *next;\n";
2473 Result += "\tint protocol_count;\n";
2474 Result += "\tstruct _objc_protocol *class_protocols[";
2475 Result += utostr(NumProtocols);
2476 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002477 Result += prefix;
2478 Result += "_PROTOCOLS_";
2479 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002480 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002481 "{\n\t0, ";
2482 Result += utostr(NumProtocols);
2483 Result += "\n";
2484
2485 Result += "\t,{&_OBJC_PROTOCOL_";
2486 Result += Protocols[0]->getName();
2487 Result += " \n";
2488
2489 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002490 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff27429432008-03-12 01:06:30 +00002491 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002492 Result += PDecl->getName();
2493 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002494 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002495 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002496 }
2497}
2498
Ted Kremenek42730c52008-01-07 19:49:32 +00002499/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002500/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002501void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002502 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002503 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002504 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002505 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002506 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2507 CDecl = CDecl->getNextClassCategory())
2508 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2509 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002510
Chris Lattnera661a4d2007-12-23 01:40:15 +00002511 std::string FullCategoryName = ClassDecl->getName();
2512 FullCategoryName += '_';
2513 FullCategoryName += IDecl->getName();
2514
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002515 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002516 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002517 true, "CATEGORY_", FullCategoryName.c_str(),
2518 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002519
2520 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002521 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002522 false, "CATEGORY_", FullCategoryName.c_str(),
2523 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002524
2525 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002526 // Null CDecl is case of a category implementation with no category interface
2527 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002528 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002529 CDecl->getNumReferencedProtocols(),
2530 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002531 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002532
2533 /* struct _objc_category {
2534 char *category_name;
2535 char *class_name;
2536 struct _objc_method_list *instance_methods;
2537 struct _objc_method_list *class_methods;
2538 struct _objc_protocol_list *protocols;
2539 // Objective-C 1.0 extensions
2540 uint32_t size; // sizeof (struct _objc_category)
2541 struct _objc_property_list *instance_properties; // category's own
2542 // @property decl.
2543 };
2544 */
2545
2546 static bool objc_category = false;
2547 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002548 Result += "\nstruct _objc_category {\n";
2549 Result += "\tchar *category_name;\n";
2550 Result += "\tchar *class_name;\n";
2551 Result += "\tstruct _objc_method_list *instance_methods;\n";
2552 Result += "\tstruct _objc_method_list *class_methods;\n";
2553 Result += "\tstruct _objc_protocol_list *protocols;\n";
2554 Result += "\tunsigned int size;\n";
2555 Result += "\tstruct _objc_property_list *instance_properties;\n";
2556 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002557 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002558 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002559 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2560 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002561 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002562 Result += IDecl->getName();
2563 Result += "\"\n\t, \"";
2564 Result += ClassDecl->getName();
2565 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002566
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002567 if (IDecl->getNumInstanceMethods() > 0) {
2568 Result += "\t, (struct _objc_method_list *)"
2569 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2570 Result += FullCategoryName;
2571 Result += "\n";
2572 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002573 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002574 Result += "\t, 0\n";
2575 if (IDecl->getNumClassMethods() > 0) {
2576 Result += "\t, (struct _objc_method_list *)"
2577 "&_OBJC_CATEGORY_CLASS_METHODS_";
2578 Result += FullCategoryName;
2579 Result += "\n";
2580 }
2581 else
2582 Result += "\t, 0\n";
2583
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002584 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002585 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2586 Result += FullCategoryName;
2587 Result += "\n";
2588 }
2589 else
2590 Result += "\t, 0\n";
2591 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002592}
2593
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002594/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2595/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002596void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2597 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002598 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002599 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002600 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002601 if (LangOpts.Microsoft)
2602 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002603 Result += ", ";
2604 Result += ivar->getName();
2605 Result += ")";
2606}
2607
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002608//===----------------------------------------------------------------------===//
2609// Meta Data Emission
2610//===----------------------------------------------------------------------===//
2611
Ted Kremenek42730c52008-01-07 19:49:32 +00002612void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002613 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002614 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002615
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002616 // Explictly declared @interface's are already synthesized.
2617 if (CDecl->ImplicitInterfaceDecl()) {
2618 // FIXME: Implementation of a class with no @interface (legacy) doese not
2619 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002620 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002621 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002622
Chris Lattnerc7b06752007-12-12 07:56:42 +00002623 // Build _objc_ivar_list metadata for classes ivars if needed
2624 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2625 ? IDecl->getImplDeclNumIvars()
2626 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002627 if (NumIvars > 0) {
2628 static bool objc_ivar = false;
2629 if (!objc_ivar) {
2630 /* struct _objc_ivar {
2631 char *ivar_name;
2632 char *ivar_type;
2633 int ivar_offset;
2634 };
2635 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002636 Result += "\nstruct _objc_ivar {\n";
2637 Result += "\tchar *ivar_name;\n";
2638 Result += "\tchar *ivar_type;\n";
2639 Result += "\tint ivar_offset;\n";
2640 Result += "};\n";
2641
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002642 objc_ivar = true;
2643 }
2644
Steve Naroffc723eec2008-03-11 00:12:29 +00002645 /* struct {
2646 int ivar_count;
2647 struct _objc_ivar ivar_list[nIvars];
2648 };
2649 */
2650 Result += "\nstatic struct {\n";
2651 Result += "\tint ivar_count;\n";
2652 Result += "\tstruct _objc_ivar ivar_list[";
2653 Result += utostr(NumIvars);
2654 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002655 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002656 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002657 "{\n\t";
2658 Result += utostr(NumIvars);
2659 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002660
Ted Kremenek42730c52008-01-07 19:49:32 +00002661 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002662 if (IDecl->getImplDeclNumIvars() > 0) {
2663 IVI = IDecl->ivar_begin();
2664 IVE = IDecl->ivar_end();
2665 } else {
2666 IVI = CDecl->ivar_begin();
2667 IVE = CDecl->ivar_end();
2668 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002669 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002670 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002671 Result += "\", \"";
2672 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002673 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2674 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002675 Result += StrEncoding;
2676 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002677 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002678 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002679 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002680 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002681 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002682 Result += "\", \"";
2683 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002684 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2685 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002686 Result += StrEncoding;
2687 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002688 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002689 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002690 }
2691
2692 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002693 }
2694
2695 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002696 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002697 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002698
2699 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002700 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002701 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002702
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002703 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002704 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002705 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002706 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002707
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002708
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002709 // Declaration of class/meta-class metadata
2710 /* struct _objc_class {
2711 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002712 const char *super_class_name;
2713 char *name;
2714 long version;
2715 long info;
2716 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002717 struct _objc_ivar_list *ivars;
2718 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002719 struct objc_cache *cache;
2720 struct objc_protocol_list *protocols;
2721 const char *ivar_layout;
2722 struct _objc_class_ext *ext;
2723 };
2724 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002725 static bool objc_class = false;
2726 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002727 Result += "\nstruct _objc_class {\n";
2728 Result += "\tstruct _objc_class *isa;\n";
2729 Result += "\tconst char *super_class_name;\n";
2730 Result += "\tchar *name;\n";
2731 Result += "\tlong version;\n";
2732 Result += "\tlong info;\n";
2733 Result += "\tlong instance_size;\n";
2734 Result += "\tstruct _objc_ivar_list *ivars;\n";
2735 Result += "\tstruct _objc_method_list *methods;\n";
2736 Result += "\tstruct objc_cache *cache;\n";
2737 Result += "\tstruct _objc_protocol_list *protocols;\n";
2738 Result += "\tconst char *ivar_layout;\n";
2739 Result += "\tstruct _objc_class_ext *ext;\n";
2740 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002741 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002742 }
2743
2744 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002745 ObjCInterfaceDecl *RootClass = 0;
2746 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002747 while (SuperClass) {
2748 RootClass = SuperClass;
2749 SuperClass = SuperClass->getSuperClass();
2750 }
2751 SuperClass = CDecl->getSuperClass();
2752
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002753 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2754 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002755 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002756 "{\n\t(struct _objc_class *)\"";
2757 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2758 Result += "\"";
2759
2760 if (SuperClass) {
2761 Result += ", \"";
2762 Result += SuperClass->getName();
2763 Result += "\", \"";
2764 Result += CDecl->getName();
2765 Result += "\"";
2766 }
2767 else {
2768 Result += ", 0, \"";
2769 Result += CDecl->getName();
2770 Result += "\"";
2771 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002772 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002773 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002774 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002775 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002776 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002777 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002778 Result += "\n";
2779 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002780 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002781 Result += ", 0\n";
2782 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002783 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002784 Result += CDecl->getName();
2785 Result += ",0,0\n";
2786 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002787 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002788 Result += "\t,0,0,0,0\n";
2789 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002790
2791 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002792 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2793 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002794 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002795 "{\n\t&_OBJC_METACLASS_";
2796 Result += CDecl->getName();
2797 if (SuperClass) {
2798 Result += ", \"";
2799 Result += SuperClass->getName();
2800 Result += "\", \"";
2801 Result += CDecl->getName();
2802 Result += "\"";
2803 }
2804 else {
2805 Result += ", 0, \"";
2806 Result += CDecl->getName();
2807 Result += "\"";
2808 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002809 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002810 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002811 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002812 Result += ",0";
2813 else {
2814 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002815 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002816 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002817 if (LangOpts.Microsoft)
2818 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002819 Result += ")";
2820 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002821 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002822 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002823 Result += CDecl->getName();
2824 Result += "\n\t";
2825 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002826 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002827 Result += ",0";
2828 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002829 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002830 Result += CDecl->getName();
2831 Result += ", 0\n\t";
2832 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002833 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002834 Result += ",0,0";
2835 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002836 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002837 Result += CDecl->getName();
2838 Result += ", 0,0\n";
2839 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002840 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002841 Result += ",0,0,0\n";
2842 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002843}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002844
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002845/// RewriteImplementations - This routine rewrites all method implementations
2846/// and emits meta-data.
2847
2848void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002849 int ClsDefCount = ClassImplementation.size();
2850 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002851
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002852 if (ClsDefCount == 0 && CatDefCount == 0)
2853 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002854 // Rewrite implemented methods
2855 for (int i = 0; i < ClsDefCount; i++)
2856 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002857
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002858 for (int i = 0; i < CatDefCount; i++)
2859 RewriteImplementationDecl(CategoryImplementation[i]);
2860
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002861 // This is needed for use of offsetof
2862 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002863
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002864 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002865 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002866 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002867
2868 // For each implemented category, write out all its meta data.
2869 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002870 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002871
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002872 // Write objc_symtab metadata
2873 /*
2874 struct _objc_symtab
2875 {
2876 long sel_ref_cnt;
2877 SEL *refs;
2878 short cls_def_cnt;
2879 short cat_def_cnt;
2880 void *defs[cls_def_cnt + cat_def_cnt];
2881 };
2882 */
2883
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002884 Result += "\nstruct _objc_symtab {\n";
2885 Result += "\tlong sel_ref_cnt;\n";
2886 Result += "\tSEL *refs;\n";
2887 Result += "\tshort cls_def_cnt;\n";
2888 Result += "\tshort cat_def_cnt;\n";
2889 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2890 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002891
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002892 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002893 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002894 Result += "\t0, 0, " + utostr(ClsDefCount)
2895 + ", " + utostr(CatDefCount) + "\n";
2896 for (int i = 0; i < ClsDefCount; i++) {
2897 Result += "\t,&_OBJC_CLASS_";
2898 Result += ClassImplementation[i]->getName();
2899 Result += "\n";
2900 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002901
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002902 for (int i = 0; i < CatDefCount; i++) {
2903 Result += "\t,&_OBJC_CATEGORY_";
2904 Result += CategoryImplementation[i]->getClassInterface()->getName();
2905 Result += "_";
2906 Result += CategoryImplementation[i]->getName();
2907 Result += "\n";
2908 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002909
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002910 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002911
2912 // Write objc_module metadata
2913
2914 /*
2915 struct _objc_module {
2916 long version;
2917 long size;
2918 const char *name;
2919 struct _objc_symtab *symtab;
2920 }
2921 */
2922
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002923 Result += "\nstruct _objc_module {\n";
2924 Result += "\tlong version;\n";
2925 Result += "\tlong size;\n";
2926 Result += "\tconst char *name;\n";
2927 Result += "\tstruct _objc_symtab *symtab;\n";
2928 Result += "};\n\n";
2929 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002930 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002931 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2932 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002933 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002934
2935 if (LangOpts.Microsoft) {
2936 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2937 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2938 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2939 Result += "&_OBJC_MODULES;\n";
2940 Result += "#pragma data_seg(pop)\n\n";
2941 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002942}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002943