blob: e947f243f21495cfca140ccf6b4f41431f0817e5 [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
Steve Naroff47e7fa22008-03-15 00:55:56 +000055 unsigned NumObjCStringLiterals;
56
Steve Naroffe9780582007-10-23 23:50:29 +000057 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000058 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000059 FunctionDecl *MsgSendStretFunctionDecl;
60 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000061 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000062 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000063 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000064 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000065 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000066 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000067 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000068
Steve Naroff0add5d22007-11-03 11:27:19 +000069 // ObjC string constant support.
70 FileVarDecl *ConstantStringClassReference;
71 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000072
Fariborz Jahanian22277422008-01-16 00:09:11 +000073 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000074 int BcLabelCount;
75
Steve Naroff764c1ae2007-11-15 10:28:18 +000076 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000077 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000079 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000081 // Needed for header files being rewritten
82 bool IsHeader;
83
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000084 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000085 public:
Chris Lattner12499682008-01-31 19:38:44 +000086 void Initialize(ASTContext &context);
87
Chris Lattner569faa62007-10-11 18:38:32 +000088
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000089 // Top Level Driver code.
90 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000091 void HandleDeclInMainFile(Decl *D);
Steve Naroff7fd0aff2008-03-10 20:43:59 +000092 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
93 Diags(D), LangOpts(LOpts) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +000094 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +000095 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
96 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +000097 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000098 ~RewriteTest();
Chris Lattnerb1548372008-01-31 19:37:57 +000099
100 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000101 // If replacement succeeded or warning disabled return with no warning.
102 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000103 return;
104
Chris Lattnerb1548372008-01-31 19:37:57 +0000105 SourceRange Range = Old->getSourceRange();
106 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
107 0, 0, &Range, 1);
108 }
109
Chris Lattner6216f292008-01-31 19:42:41 +0000110 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000111 // If insertion succeeded or warning disabled return with no warning.
Chris Lattner6216f292008-01-31 19:42:41 +0000112 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
113 SilenceRewriteMacroWarning)
114 return;
115
116 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
117 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000118
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000119 void RemoveText(SourceLocation Loc, unsigned StrLen) {
120 // If removal succeeded or warning disabled return with no warning.
121 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000126
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000127 void ReplaceText(SourceLocation Start, unsigned OrigLength,
128 const char *NewStr, unsigned NewLength) {
129 // If removal succeeded or warning disabled return with no warning.
130 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
131 SilenceRewriteMacroWarning)
132 return;
133
134 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
135 }
136
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000137 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000138 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000139 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000141 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
142 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000143 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000144 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
145 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
146 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
147 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
148 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
149 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000150 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000151 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000152 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000153 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000154 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000155 QualType getConstantStringStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000156
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000157 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000158 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000159 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000160 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000161 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000162 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000163 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000164 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000165 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000166 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000167 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
168 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
169 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000170 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
171 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000172 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
173 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000174 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000175 Stmt *RewriteBreakStmt(BreakStmt *S);
176 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000177 void SynthCountByEnumWithState(std::string &buf);
178
Steve Naroff02a82aa2007-10-30 23:14:51 +0000179 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000180 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000181 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000182 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000183 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000184 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000185 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000188 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000189
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000190 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000191 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
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 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000195 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000196
Ted Kremenek42730c52008-01-07 19:49:32 +0000197 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
198 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000199 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000200 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000201 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000202 const char *ClassName,
203 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000204
Ted Kremenek42730c52008-01-07 19:49:32 +0000205 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000206 int NumProtocols,
207 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000208 const char *ClassName,
209 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000211 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000212 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
213 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000214 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000215 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000216 };
217}
218
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000219static bool IsHeaderFile(const std::string &Filename) {
220 std::string::size_type DotPos = Filename.rfind('.');
221
222 if (DotPos == std::string::npos) {
223 // no file extension
224 return false;
225 }
226
227 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
228 // C header: .h
229 // C++ header: .hh or .H;
230 return Ext == "h" || Ext == "hh" || Ext == "H";
231}
232
233ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000234 Diagnostic &Diags,
235 const LangOptions &LOpts) {
236 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000237}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000238
Chris Lattner12499682008-01-31 19:38:44 +0000239void RewriteTest::Initialize(ASTContext &context) {
240 Context = &context;
241 SM = &Context->getSourceManager();
242 MsgSendFunctionDecl = 0;
243 MsgSendSuperFunctionDecl = 0;
244 MsgSendStretFunctionDecl = 0;
245 MsgSendSuperStretFunctionDecl = 0;
246 MsgSendFpretFunctionDecl = 0;
247 GetClassFunctionDecl = 0;
248 GetMetaClassFunctionDecl = 0;
249 SelGetUidFunctionDecl = 0;
250 CFStringFunctionDecl = 0;
251 GetProtocolFunctionDecl = 0;
252 ConstantStringClassReference = 0;
253 NSStringRecord = 0;
254 CurMethodDecl = 0;
255 SuperStructDecl = 0;
256 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000257 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000258 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000259
260 // Get the ID and start/end of the main file.
261 MainFileID = SM->getMainFileID();
262 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
263 MainFileStart = MainBuf->getBufferStart();
264 MainFileEnd = MainBuf->getBufferEnd();
265
266
267 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000268
Chris Lattner12499682008-01-31 19:38:44 +0000269 // declaring objc_selector outside the parameter list removes a silly
270 // scope related warning...
Steve Naroffde0da102008-03-10 23:16:54 +0000271 std::string S = "#pragma once\n";
272 S += "struct objc_selector; struct objc_class;\n";
273 S += "#ifndef OBJC_SUPER\n";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000274 S += "struct objc_super { struct objc_object *object; ";
275 S += "struct objc_object *superClass; ";
276 if (LangOpts.Microsoft) {
277 // Add a constructor for creating temporary objects.
278 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
279 S += "object(o), superClass(s) {} ";
280 }
281 S += "};\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000282 S += "#define OBJC_SUPER\n";
283 S += "#endif\n";
284 S += "#ifndef _REWRITER_typedef_Protocol\n";
285 S += "typedef struct objc_object Protocol;\n";
286 S += "#define _REWRITER_typedef_Protocol\n";
287 S += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000288 if (LangOpts.Microsoft)
289 S += "extern \"C\" {\n";
290 S += "struct objc_object *objc_msgSend";
Steve Naroffde0da102008-03-10 23:16:54 +0000291 S += "(struct objc_object *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSendSuper";
293 S += "(struct objc_super *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_msgSend_stret";
295 S += "(struct objc_object *, struct objc_selector *, ...);\n";
296 S += "extern struct objc_object *objc_msgSendSuper_stret";
297 S += "(struct objc_super *, struct objc_selector *, ...);\n";
298 S += "extern struct objc_object *objc_msgSend_fpret";
299 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000300 S += "struct objc_object *objc_getClass";
Steve Naroffde0da102008-03-10 23:16:54 +0000301 S += "(const char *);\n";
302 S += "extern struct objc_object *objc_getMetaClass";
303 S += "(const char *);\n";
304 S += "extern void objc_exception_throw(struct objc_object *);\n";
305 S += "extern void objc_exception_try_enter(void *);\n";
306 S += "extern void objc_exception_try_exit(void *);\n";
307 S += "extern struct objc_object *objc_exception_extract(void *);\n";
308 S += "extern int objc_exception_match";
309 S += "(struct objc_class *, struct objc_object *, ...);\n";
310 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000311 if (LangOpts.Microsoft)
312 S += "} // end extern \"C\"\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000313 S += "#include <objc/objc.h>\n";
314 S += "#ifndef __FASTENUMERATIONSTATE\n";
315 S += "struct __objcFastEnumerationState {\n\t";
316 S += "unsigned long state;\n\t";
317 S += "id *itemsPtr;\n\t";
318 S += "unsigned long *mutationsPtr;\n\t";
319 S += "unsigned long extra[5];\n};\n";
320 S += "#define __FASTENUMERATIONSTATE\n";
321 S += "#endif\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000322 S += "#ifndef __NSCONSTANTSTRINGIMPL\n";
323 S += "struct __NSConstantStringImpl {\n";
324 S += " struct objc_object *isa;\n";
325 S += " int flags;\n";
326 S += " char *str;\n";
327 S += " long length;\n";
328 S += " __NSConstantStringImpl(char *s, long l) :\n";
329 S += " flags(0), str(s), length(l)\n";
Steve Naroff64bce352008-03-15 01:36:04 +0000330 S += " { extern int __CFConstantStringClassReference[];\n";
331 S += " isa = (struct objc_object *)__CFConstantStringClassReference;}\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000332 S += "};\n";
333 S += "#define __NSCONSTANTSTRINGIMPL\n";
334 S += "#endif\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000335#if 0
336 if (LangOpts.Microsoft)
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000337 S += "#define __attribute__(X)\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000338#endif
Chris Lattner12499682008-01-31 19:38:44 +0000339 if (IsHeader) {
340 // insert the whole string when rewriting a header file
Steve Naroffde0da102008-03-10 23:16:54 +0000341 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner12499682008-01-31 19:38:44 +0000342 }
343 else {
344 // Not rewriting header, exclude the #pragma once pragma
Steve Naroffde0da102008-03-10 23:16:54 +0000345 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattner6216f292008-01-31 19:42:41 +0000346 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner12499682008-01-31 19:38:44 +0000347 }
348}
349
350
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000351//===----------------------------------------------------------------------===//
352// Top Level Driver Code
353//===----------------------------------------------------------------------===//
354
Chris Lattner569faa62007-10-11 18:38:32 +0000355void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000356 // Two cases: either the decl could be in the main file, or it could be in a
357 // #included file. If the former, rewrite it now. If the later, check to see
358 // if we rewrote the #include/#import.
359 SourceLocation Loc = D->getLocation();
360 Loc = SM->getLogicalLoc(Loc);
361
362 // If this is for a builtin, ignore it.
363 if (Loc.isInvalid()) return;
364
Steve Naroffe9780582007-10-23 23:50:29 +0000365 // Look for built-in declarations that we need to refer during the rewrite.
366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000367 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000368 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
369 // declared in <Foundation/NSString.h>
370 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
371 ConstantStringClassReference = FVD;
372 return;
373 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000374 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000375 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000376 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000377 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000378 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000379 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000380 } else if (ObjCForwardProtocolDecl *FP =
381 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000382 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000383 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000384 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000385 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
386 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000387}
388
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000389/// HandleDeclInMainFile - This is called for each top-level decl defined in the
390/// main file of the input.
391void RewriteTest::HandleDeclInMainFile(Decl *D) {
392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
393 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000394 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000395
Ted Kremenek42730c52008-01-07 19:49:32 +0000396 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000397 if (Stmt *Body = MD->getBody()) {
398 //Body->dump();
399 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000400 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000401 CurMethodDecl = 0;
402 }
Steve Naroff18c83382007-11-13 23:01:27 +0000403 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000404 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000405 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000406 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000407 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000408 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000409 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000410 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000411 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000412 if (VD->getInit())
413 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
414 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000415 // Nothing yet.
416}
417
418RewriteTest::~RewriteTest() {
419 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000420
421 // Rewrite tabs if we care.
422 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000423
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000424 RewriteInclude();
425
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000426 // Rewrite Objective-c meta data*
427 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000428 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000429
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
431 // we are done.
432 if (const RewriteBuffer *RewriteBuf =
433 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000434 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000435 std::string S(RewriteBuf->begin(), RewriteBuf->end());
436 printf("%s\n", S.c_str());
437 } else {
438 printf("No changes\n");
439 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000440 // Emit metadata.
441 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000442}
443
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000444//===----------------------------------------------------------------------===//
445// Syntactic (non-AST) Rewriting Code
446//===----------------------------------------------------------------------===//
447
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000448void RewriteTest::RewriteInclude() {
449 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
450 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
451 const char *MainBufStart = MainBuf.first;
452 const char *MainBufEnd = MainBuf.second;
453 size_t ImportLen = strlen("import");
454 size_t IncludeLen = strlen("include");
455
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000456 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000457 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
458 if (*BufPtr == '#') {
459 if (++BufPtr == MainBufEnd)
460 return;
461 while (*BufPtr == ' ' || *BufPtr == '\t')
462 if (++BufPtr == MainBufEnd)
463 return;
464 if (!strncmp(BufPtr, "import", ImportLen)) {
465 // replace import with include
466 SourceLocation ImportLoc =
467 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000468 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000469 BufPtr += ImportLen;
470 }
471 }
472 }
Chris Lattner74db1682007-10-16 21:07:07 +0000473}
474
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000475void RewriteTest::RewriteTabs() {
476 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
477 const char *MainBufStart = MainBuf.first;
478 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000479
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000480 // Loop over the whole file, looking for tabs.
481 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
482 if (*BufPtr != '\t')
483 continue;
484
485 // Okay, we found a tab. This tab will turn into at least one character,
486 // but it depends on which 'virtual column' it is in. Compute that now.
487 unsigned VCol = 0;
488 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
489 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
490 ++VCol;
491
492 // Okay, now that we know the virtual column, we know how many spaces to
493 // insert. We assume 8-character tab-stops.
494 unsigned Spaces = 8-(VCol & 7);
495
496 // Get the location of the tab.
497 SourceLocation TabLoc =
498 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
499
500 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000501 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000502 }
Chris Lattner569faa62007-10-11 18:38:32 +0000503}
504
505
Ted Kremenek42730c52008-01-07 19:49:32 +0000506void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000507 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000508 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000509
510 // Get the start location and compute the semi location.
511 SourceLocation startLoc = ClassDecl->getLocation();
512 const char *startBuf = SM->getCharacterData(startLoc);
513 const char *semiPtr = strchr(startBuf, ';');
514
515 // Translate to typedef's that forward reference structs with the same name
516 // as the class. As a convenience, we include the original declaration
517 // as a comment.
518 std::string typedefString;
519 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000520 typedefString.append(startBuf, semiPtr-startBuf+1);
521 typedefString += "\n";
522 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000523 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000524 typedefString += "#ifndef _REWRITER_typedef_";
525 typedefString += ForwardDecl->getName();
526 typedefString += "\n";
527 typedefString += "#define _REWRITER_typedef_";
528 typedefString += ForwardDecl->getName();
529 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000530 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000531 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000532 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000533 }
534
535 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000536 ReplaceText(startLoc, semiPtr-startBuf+1,
537 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000538}
539
Ted Kremenek42730c52008-01-07 19:49:32 +0000540void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000541 SourceLocation LocStart = Method->getLocStart();
542 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000543
Steve Naroff2ce399a2007-12-14 23:37:57 +0000544 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000545 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000546 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000547 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000548 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000549 }
550}
551
Ted Kremenek42730c52008-01-07 19:49:32 +0000552void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000553{
554 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000556 SourceLocation Loc = Property->getLocation();
557
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000558 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000559
560 // FIXME: handle properties that are declared across multiple lines.
561 }
562}
563
Ted Kremenek42730c52008-01-07 19:49:32 +0000564void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000565 SourceLocation LocStart = CatDecl->getLocStart();
566
567 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000568 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000569
Ted Kremenek42730c52008-01-07 19:49:32 +0000570 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000571 E = CatDecl->instmeth_end(); I != E; ++I)
572 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000574 E = CatDecl->classmeth_end(); I != E; ++I)
575 RewriteMethodDeclaration(*I);
576
Steve Naroff667f1682007-10-30 13:30:57 +0000577 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000578 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000579}
580
Ted Kremenek42730c52008-01-07 19:49:32 +0000581void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000582 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000583
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000584 SourceLocation LocStart = PDecl->getLocStart();
585
586 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000587 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000588
Ted Kremenek42730c52008-01-07 19:49:32 +0000589 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000590 E = PDecl->instmeth_end(); I != E; ++I)
591 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000592 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000593 E = PDecl->classmeth_end(); I != E; ++I)
594 RewriteMethodDeclaration(*I);
595
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000596 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000597 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000598 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000599
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000600 // Must comment out @optional/@required
601 const char *startBuf = SM->getCharacterData(LocStart);
602 const char *endBuf = SM->getCharacterData(LocEnd);
603 for (const char *p = startBuf; p < endBuf; p++) {
604 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
605 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000606 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000607 ReplaceText(OptionalLoc, strlen("@optional"),
608 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000609
610 }
611 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
612 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000613 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000614 ReplaceText(OptionalLoc, strlen("@required"),
615 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000616
617 }
618 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000619}
620
Ted Kremenek42730c52008-01-07 19:49:32 +0000621void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000622 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000623 if (LocStart.isInvalid())
624 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000625 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000626 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000627}
628
Ted Kremenek42730c52008-01-07 19:49:32 +0000629void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000630 std::string &ResultStr) {
631 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000632 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000633 ResultStr += "id";
634 else
635 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000636 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000637
638 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000639 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000640
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000641 if (OMD->isInstance())
642 NameStr += "_I_";
643 else
644 NameStr += "_C_";
645
646 NameStr += OMD->getClassInterface()->getName();
647 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000648
649 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000650 if (ObjCCategoryImplDecl *CID =
651 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000652 NameStr += CID->getName();
653 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000654 }
655 // Append selector names, replacing ':' with '_'
656 const char *selName = OMD->getSelector().getName().c_str();
657 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000658 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000659 else {
660 std::string selString = OMD->getSelector().getName();
661 int len = selString.size();
662 for (int i = 0; i < len; i++)
663 if (selString[i] == ':')
664 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000665 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000666 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000667 // Remember this name for metadata emission
668 MethodInternalNames[OMD] = NameStr;
669 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000670
671 // Rewrite arguments
672 ResultStr += "(";
673
674 // invisible arguments
675 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000676 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000677 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000678 if (!LangOpts.Microsoft) {
679 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
680 ResultStr += "struct ";
681 }
682 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000683 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000684 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000685 }
686 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000687 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000688
689 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000690 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000691 ResultStr += " _cmd";
692
693 // Method arguments.
694 for (int i = 0; i < OMD->getNumParams(); i++) {
695 ParmVarDecl *PDecl = OMD->getParamDecl(i);
696 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000697 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000698 ResultStr += "id";
699 else
700 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000701 ResultStr += " ";
702 ResultStr += PDecl->getName();
703 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000704 if (OMD->isVariadic())
705 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000706 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000707
708}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000709void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000710 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
711 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000712
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000713 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000714 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000715 else
Chris Lattner6216f292008-01-31 19:42:41 +0000716 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000717
Ted Kremenek42730c52008-01-07 19:49:32 +0000718 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000719 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
720 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000721 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000722 ObjCMethodDecl *OMD = *I;
723 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724 SourceLocation LocStart = OMD->getLocStart();
725 SourceLocation LocEnd = OMD->getBody()->getLocStart();
726
727 const char *startBuf = SM->getCharacterData(LocStart);
728 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000729 ReplaceText(LocStart, endBuf-startBuf,
730 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000731 }
732
Ted Kremenek42730c52008-01-07 19:49:32 +0000733 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000734 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
735 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000736 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000737 ObjCMethodDecl *OMD = *I;
738 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000739 SourceLocation LocStart = OMD->getLocStart();
740 SourceLocation LocEnd = OMD->getBody()->getLocStart();
741
742 const char *startBuf = SM->getCharacterData(LocStart);
743 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000744 ReplaceText(LocStart, endBuf-startBuf,
745 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000746 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000747 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000748 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000749 else
Chris Lattner6216f292008-01-31 19:42:41 +0000750 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000751}
752
Ted Kremenek42730c52008-01-07 19:49:32 +0000753void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000754 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000755 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000756 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000757 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000758 ResultStr += ClassDecl->getName();
759 ResultStr += "\n";
760 ResultStr += "#define _REWRITER_typedef_";
761 ResultStr += ClassDecl->getName();
762 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000763 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000764 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000765 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000766 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000767 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000768 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000769 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000770
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000771 RewriteProperties(ClassDecl->getNumPropertyDecl(),
772 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000773 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000774 E = ClassDecl->instmeth_end(); I != E; ++I)
775 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000776 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000777 E = ClassDecl->classmeth_end(); I != E; ++I)
778 RewriteMethodDeclaration(*I);
779
Steve Naroff1ccf4632007-10-30 03:43:13 +0000780 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000781 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000782}
783
Steve Naroff6b759ce2007-11-15 02:58:25 +0000784Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000785 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000786 if (CurMethodDecl) {
787 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
788 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
789 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000790 // lookup which class implements the instance variable.
791 ObjCInterfaceDecl *clsDeclared = 0;
792 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
793 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5d933112008-03-12 23:15:19 +0000794
795 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000796 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000797 RecName += "_IMPL";
798 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
799 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
800 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
801 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
802 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
803 // Don't forget the parens to enforce the proper binding.
804 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
805 if (IV->isFreeIvar()) {
806 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
807 ReplaceStmt(IV, ME);
808 delete IV;
809 return ME;
810 } else {
Chris Lattnerb1548372008-01-31 19:37:57 +0000811 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5d933112008-03-12 23:15:19 +0000812 // Cannot delete IV->getBase(), since PE points to it.
813 // Replace the old base with the cast. This is important when doing
814 // embedded rewrites. For example, [newInv->_container addObject:0].
815 IV->setBase(PE);
816 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000817 }
818 }
819 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000820 }
Steve Naroff5d933112008-03-12 23:15:19 +0000821 // FIXME: Implement public ivar access from a function.
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000822 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
823 IV->getLocation(), D->getType());
824 ReplaceStmt(IV, Replacement);
825 delete IV;
826 return Replacement;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000827}
828
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000829//===----------------------------------------------------------------------===//
830// Function Body / Expression rewriting
831//===----------------------------------------------------------------------===//
832
Steve Naroff334fbc22007-11-09 15:20:18 +0000833Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000834 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
835 isa<DoStmt>(S) || isa<ForStmt>(S))
836 Stmts.push_back(S);
837 else if (isa<ObjCForCollectionStmt>(S)) {
838 Stmts.push_back(S);
839 ObjCBcLabelNo.push_back(++BcLabelCount);
840 }
841
Chris Lattner2c022162008-01-31 05:10:40 +0000842 SourceLocation OrigStmtEnd = S->getLocEnd();
843
844 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000845 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
846 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000847 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000848 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000849 if (newStmt)
850 *CI = newStmt;
851 }
Steve Naroffe9780582007-10-23 23:50:29 +0000852
853 // Handle specific things.
854 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
855 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000856
857 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
858 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000859
860 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
861 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000862
Steve Naroff0add5d22007-11-03 11:27:19 +0000863 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
864 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000865
Steve Naroff71226032007-10-24 22:48:43 +0000866 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
867 // Before we rewrite it, put the original message expression in a comment.
868 SourceLocation startLoc = MessExpr->getLocStart();
869 SourceLocation endLoc = MessExpr->getLocEnd();
870
871 const char *startBuf = SM->getCharacterData(startLoc);
872 const char *endBuf = SM->getCharacterData(endLoc);
873
874 std::string messString;
875 messString += "// ";
876 messString.append(startBuf, endBuf-startBuf+1);
877 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000878
Chris Lattner6216f292008-01-31 19:42:41 +0000879 // FIXME: Missing definition of
880 // InsertText(clang::SourceLocation, char const*, unsigned int).
881 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000882 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000883 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000884 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000885 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000886
Ted Kremenek42730c52008-01-07 19:49:32 +0000887 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
888 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000889
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000890 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
891 return RewriteObjCSynchronizedStmt(StmtTry);
892
Ted Kremenek42730c52008-01-07 19:49:32 +0000893 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
894 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000895
896 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
897 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000898
899 if (ObjCForCollectionStmt *StmtForCollection =
900 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000901 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000902 if (BreakStmt *StmtBreakStmt =
903 dyn_cast<BreakStmt>(S))
904 return RewriteBreakStmt(StmtBreakStmt);
905 if (ContinueStmt *StmtContinueStmt =
906 dyn_cast<ContinueStmt>(S))
907 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000908
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000909 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
910 isa<DoStmt>(S) || isa<ForStmt>(S)) {
911 assert(!Stmts.empty() && "Statement stack is empty");
912 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
913 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
914 && "Statement stack mismatch");
915 Stmts.pop_back();
916 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000917#if 0
918 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
919 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
920 // Get the new text.
921 std::ostringstream Buf;
922 Replacement->printPretty(Buf);
923 const std::string &Str = Buf.str();
924
925 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000926 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000927 delete S;
928 return Replacement;
929 }
930#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000931 // Return this stmt unmodified.
932 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000933}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000934
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000935/// SynthCountByEnumWithState - To print:
936/// ((unsigned int (*)
937/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
938/// (void *)objc_msgSend)((id)l_collection,
939/// sel_registerName(
940/// "countByEnumeratingWithState:objects:count:"),
941/// &enumState,
942/// (id *)items, (unsigned int)16)
943///
944void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
945 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
946 "id *, unsigned int))(void *)objc_msgSend)";
947 buf += "\n\t\t";
948 buf += "((id)l_collection,\n\t\t";
949 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
950 buf += "\n\t\t";
951 buf += "&enumState, "
952 "(id *)items, (unsigned int)16)";
953}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000954
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000955/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
956/// statement to exit to its outer synthesized loop.
957///
958Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
959 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
960 return S;
961 // replace break with goto __break_label
962 std::string buf;
963
964 SourceLocation startLoc = S->getLocStart();
965 buf = "goto __break_label_";
966 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000967 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000968
969 return 0;
970}
971
972/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
973/// statement to continue with its inner synthesized loop.
974///
975Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
976 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
977 return S;
978 // replace continue with goto __continue_label
979 std::string buf;
980
981 SourceLocation startLoc = S->getLocStart();
982 buf = "goto __continue_label_";
983 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000984 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000985
986 return 0;
987}
988
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000989/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000990/// It rewrites:
991/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000992
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000993/// Into:
994/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000995/// type elem;
996/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000997/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000998/// id l_collection = (id)collection;
999/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1000/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001001/// if (limit) {
1002/// unsigned long startMutations = *enumState.mutationsPtr;
1003/// do {
1004/// unsigned long counter = 0;
1005/// do {
1006/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001007/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001008/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001009/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001010/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001011/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001012/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1013/// objects:items count:16]);
1014/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001015/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001016/// }
1017/// else
1018/// elem = nil;
1019/// }
1020///
Chris Lattner2c022162008-01-31 05:10:40 +00001021Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1022 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001023 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1024 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1025 "ObjCForCollectionStmt Statement stack mismatch");
1026 assert(!ObjCBcLabelNo.empty() &&
1027 "ObjCForCollectionStmt - Label No stack empty");
1028
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001029 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001030 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001031 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001032 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001033 std::string buf;
1034 buf = "\n{\n\t";
1035 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1036 // type elem;
1037 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001038 elementTypeAsString = ElementType.getAsString();
1039 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001040 buf += " ";
1041 elementName = DS->getDecl()->getName();
1042 buf += elementName;
1043 buf += ";\n\t";
1044 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001045 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001046 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001047 elementTypeAsString = DR->getDecl()->getType().getAsString();
1048 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001049 else
1050 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1051
1052 // struct __objcFastEnumerationState enumState = { 0 };
1053 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1054 // id items[16];
1055 buf += "id items[16];\n\t";
1056 // id l_collection = (id)
1057 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001058 // Find start location of 'collection' the hard way!
1059 const char *startCollectionBuf = startBuf;
1060 startCollectionBuf += 3; // skip 'for'
1061 startCollectionBuf = strchr(startCollectionBuf, '(');
1062 startCollectionBuf++; // skip '('
1063 // find 'in' and skip it.
1064 while (*startCollectionBuf != ' ' ||
1065 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1066 (*(startCollectionBuf+3) != ' ' &&
1067 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1068 startCollectionBuf++;
1069 startCollectionBuf += 3;
1070
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001071 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001072 ReplaceText(startLoc, startCollectionBuf - startBuf,
1073 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001074 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001075 SourceLocation rightParenLoc = S->getRParenLoc();
1076 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1077 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001078 buf = ";\n\t";
1079
1080 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1081 // objects:items count:16];
1082 // which is synthesized into:
1083 // unsigned int limit =
1084 // ((unsigned int (*)
1085 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1086 // (void *)objc_msgSend)((id)l_collection,
1087 // sel_registerName(
1088 // "countByEnumeratingWithState:objects:count:"),
1089 // (struct __objcFastEnumerationState *)&state,
1090 // (id *)items, (unsigned int)16);
1091 buf += "unsigned long limit =\n\t\t";
1092 SynthCountByEnumWithState(buf);
1093 buf += ";\n\t";
1094 /// if (limit) {
1095 /// unsigned long startMutations = *enumState.mutationsPtr;
1096 /// do {
1097 /// unsigned long counter = 0;
1098 /// do {
1099 /// if (startMutations != *enumState.mutationsPtr)
1100 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001101 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001102 buf += "if (limit) {\n\t";
1103 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1104 buf += "do {\n\t\t";
1105 buf += "unsigned long counter = 0;\n\t\t";
1106 buf += "do {\n\t\t\t";
1107 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1108 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1109 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001110 buf += " = (";
1111 buf += elementTypeAsString;
1112 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001113 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001114 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001115
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001116 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001117 /// } while (counter < limit);
1118 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1119 /// objects:items count:16]);
1120 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001121 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001122 /// }
1123 /// else
1124 /// elem = nil;
1125 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001126 ///
1127 buf = ";\n\t";
1128 buf += "__continue_label_";
1129 buf += utostr(ObjCBcLabelNo.back());
1130 buf += ": ;";
1131 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001132 buf += "} while (counter < limit);\n\t";
1133 buf += "} while (limit = ";
1134 SynthCountByEnumWithState(buf);
1135 buf += ");\n\t";
1136 buf += elementName;
1137 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001138 buf += "__break_label_";
1139 buf += utostr(ObjCBcLabelNo.back());
1140 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001141 buf += "}\n\t";
1142 buf += "else\n\t\t";
1143 buf += elementName;
1144 buf += " = nil;\n";
1145 buf += "}\n";
1146 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001147 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001148 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001149 Stmts.pop_back();
1150 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001151 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001152}
1153
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001154/// RewriteObjCSynchronizedStmt -
1155/// This routine rewrites @synchronized(expr) stmt;
1156/// into:
1157/// objc_sync_enter(expr);
1158/// @try stmt @finally { objc_sync_exit(expr); }
1159///
1160Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1161 // Get the start location and compute the semi location.
1162 SourceLocation startLoc = S->getLocStart();
1163 const char *startBuf = SM->getCharacterData(startLoc);
1164
1165 assert((*startBuf == '@') && "bogus @synchronized location");
1166
1167 std::string buf;
1168 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001169 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001170 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1171 const char *endBuf = SM->getCharacterData(endLoc);
1172 endBuf++;
1173 const char *rparenBuf = strchr(endBuf, ')');
1174 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1175 buf = ");\n";
1176 // declare a new scope with two variables, _stack and _rethrow.
1177 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1178 buf += "int buf[18/*32-bit i386*/];\n";
1179 buf += "char *pointers[4];} _stack;\n";
1180 buf += "id volatile _rethrow = 0;\n";
1181 buf += "objc_exception_try_enter(&_stack);\n";
1182 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001183 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001184 startLoc = S->getSynchBody()->getLocEnd();
1185 startBuf = SM->getCharacterData(startLoc);
1186
1187 assert((*startBuf == '}') && "bogus @try block");
1188 SourceLocation lastCurlyLoc = startLoc;
1189 buf = "}\nelse {\n";
1190 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1191 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1192 // FIXME: This must be objc_sync_exit(syncExpr);
1193 buf += " objc_sync_exit();\n";
1194 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1195 buf += "}\n";
1196 buf += "}";
1197
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001198 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001199 return 0;
1200}
1201
Ted Kremenek42730c52008-01-07 19:49:32 +00001202Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001203 // Get the start location and compute the semi location.
1204 SourceLocation startLoc = S->getLocStart();
1205 const char *startBuf = SM->getCharacterData(startLoc);
1206
1207 assert((*startBuf == '@') && "bogus @try location");
1208
1209 std::string buf;
1210 // declare a new scope with two variables, _stack and _rethrow.
1211 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1212 buf += "int buf[18/*32-bit i386*/];\n";
1213 buf += "char *pointers[4];} _stack;\n";
1214 buf += "id volatile _rethrow = 0;\n";
1215 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001216 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001217
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001218 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001219
1220 startLoc = S->getTryBody()->getLocEnd();
1221 startBuf = SM->getCharacterData(startLoc);
1222
1223 assert((*startBuf == '}') && "bogus @try block");
1224
1225 SourceLocation lastCurlyLoc = startLoc;
1226
1227 startLoc = startLoc.getFileLocWithOffset(1);
1228 buf = " /* @catch begin */ else {\n";
1229 buf += " id _caught = objc_exception_extract(&_stack);\n";
1230 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001231 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001232 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1233 buf += " else { /* @catch continue */";
1234
Chris Lattner6216f292008-01-31 19:42:41 +00001235 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001236
1237 bool sawIdTypedCatch = false;
1238 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001239 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001240 while (catchList) {
1241 Stmt *catchStmt = catchList->getCatchParamStmt();
1242
1243 if (catchList == S->getCatchStmts())
1244 buf = "if ("; // we are generating code for the first catch clause
1245 else
1246 buf = "else if (";
1247 startLoc = catchList->getLocStart();
1248 startBuf = SM->getCharacterData(startLoc);
1249
1250 assert((*startBuf == '@') && "bogus @catch location");
1251
1252 const char *lParenLoc = strchr(startBuf, '(');
1253
Steve Naroff397c4ce2008-02-01 22:08:12 +00001254 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001255 // Now rewrite the body...
1256 lastCatchBody = catchList->getCatchBody();
1257 SourceLocation rParenLoc = catchList->getRParenLoc();
1258 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1259 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1260 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1261 assert((*rParenBuf == ')') && "bogus @catch paren location");
1262 assert((*bodyBuf == '{') && "bogus @catch body location");
1263
1264 buf += "1) { id _tmp = _caught;";
1265 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1266 buf.c_str(), buf.size());
1267 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001268 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001269 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001270 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001271 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001272 sawIdTypedCatch = true;
1273 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001274 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001275
Ted Kremenek42730c52008-01-07 19:49:32 +00001276 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001277 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001278 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001279 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001280 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001281 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001282 }
1283 }
1284 // Now rewrite the body...
1285 lastCatchBody = catchList->getCatchBody();
1286 SourceLocation rParenLoc = catchList->getRParenLoc();
1287 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1288 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1289 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1290 assert((*rParenBuf == ')') && "bogus @catch paren location");
1291 assert((*bodyBuf == '{') && "bogus @catch body location");
1292
1293 buf = " = _caught;";
1294 // Here we replace ") {" with "= _caught;" (which initializes and
1295 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001296 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001297 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001298 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001299 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001300 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001301 catchList = catchList->getNextCatchStmt();
1302 }
1303 // Complete the catch list...
1304 if (lastCatchBody) {
1305 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1306 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1307 assert((*bodyBuf == '}') && "bogus @catch body location");
1308 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1309 buf = " } } /* @catch end */\n";
1310
Chris Lattner6216f292008-01-31 19:42:41 +00001311 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001312
1313 // Set lastCurlyLoc
1314 lastCurlyLoc = lastCatchBody->getLocEnd();
1315 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001316 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001317 startLoc = finalStmt->getLocStart();
1318 startBuf = SM->getCharacterData(startLoc);
1319 assert((*startBuf == '@') && "bogus @finally start");
1320
1321 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001322 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001323
1324 Stmt *body = finalStmt->getFinallyBody();
1325 SourceLocation startLoc = body->getLocStart();
1326 SourceLocation endLoc = body->getLocEnd();
1327 const char *startBuf = SM->getCharacterData(startLoc);
1328 const char *endBuf = SM->getCharacterData(endLoc);
1329 assert((*startBuf == '{') && "bogus @finally body location");
1330 assert((*endBuf == '}') && "bogus @finally body location");
1331
1332 startLoc = startLoc.getFileLocWithOffset(1);
1333 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001334 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001335 endLoc = endLoc.getFileLocWithOffset(-1);
1336 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001337 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001338
1339 // Set lastCurlyLoc
1340 lastCurlyLoc = body->getLocEnd();
1341 }
1342 // Now emit the final closing curly brace...
1343 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1344 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001345 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001346 return 0;
1347}
1348
Ted Kremenek42730c52008-01-07 19:49:32 +00001349Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001350 return 0;
1351}
1352
Ted Kremenek42730c52008-01-07 19:49:32 +00001353Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001354 return 0;
1355}
1356
Chris Lattnerb1548372008-01-31 19:37:57 +00001357// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001358// the throw expression is typically a message expression that's already
1359// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001360Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001361 // Get the start location and compute the semi location.
1362 SourceLocation startLoc = S->getLocStart();
1363 const char *startBuf = SM->getCharacterData(startLoc);
1364
1365 assert((*startBuf == '@') && "bogus @throw location");
1366
1367 std::string buf;
1368 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001369 if (S->getThrowExpr())
1370 buf = "objc_exception_throw(";
1371 else // add an implicit argument
1372 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001373 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001374 const char *semiBuf = strchr(startBuf, ';');
1375 assert((*semiBuf == ';') && "@throw: can't find ';'");
1376 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1377 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001378 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001379 return 0;
1380}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001381
Chris Lattner0021f452007-10-24 16:57:36 +00001382Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001383 // Create a new string expression.
1384 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001385 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001386 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1387 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001388 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1389 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001390 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001391 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001392
Chris Lattner4478db92007-11-30 22:53:43 +00001393 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001394 delete Exp;
1395 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001396}
1397
Steve Naroff296b74f2007-11-05 14:50:49 +00001398Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1399 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1400 // Create a call to sel_registerName("selName").
1401 llvm::SmallVector<Expr*, 8> SelExprs;
1402 QualType argType = Context->getPointerType(Context->CharTy);
1403 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1404 Exp->getSelector().getName().size(),
1405 false, argType, SourceLocation(),
1406 SourceLocation()));
1407 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1408 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001409 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001410 delete Exp;
1411 return SelExp;
1412}
1413
Steve Naroff71226032007-10-24 22:48:43 +00001414CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1415 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001416 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001417 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001418
1419 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001420 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001421
1422 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001423 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001424 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1425
1426 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001427
Steve Naroff71226032007-10-24 22:48:43 +00001428 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1429}
1430
Steve Naroffc8a92d12007-11-01 13:24:47 +00001431static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1432 const char *&startRef, const char *&endRef) {
1433 while (startBuf < endBuf) {
1434 if (*startBuf == '<')
1435 startRef = startBuf; // mark the start.
1436 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001437 if (startRef && *startRef == '<') {
1438 endRef = startBuf; // mark the end.
1439 return true;
1440 }
1441 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001442 }
1443 startBuf++;
1444 }
1445 return false;
1446}
1447
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001448static void scanToNextArgument(const char *&argRef) {
1449 int angle = 0;
1450 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1451 if (*argRef == '<')
1452 angle++;
1453 else if (*argRef == '>')
1454 angle--;
1455 argRef++;
1456 }
1457 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1458}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001459
Steve Naroffc8a92d12007-11-01 13:24:47 +00001460bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001461
Ted Kremenek42730c52008-01-07 19:49:32 +00001462 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001463 return true;
1464
Ted Kremenek42730c52008-01-07 19:49:32 +00001465 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001466 return true;
1467
Steve Naroffc8a92d12007-11-01 13:24:47 +00001468 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001469 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001470 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001471 return true; // we have "Class <Protocol> *".
1472 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001473 return false;
1474}
1475
Ted Kremenek42730c52008-01-07 19:49:32 +00001476void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001477 SourceLocation Loc;
1478 QualType Type;
1479 const FunctionTypeProto *proto = 0;
1480 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1481 Loc = VD->getLocation();
1482 Type = VD->getType();
1483 }
1484 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1485 Loc = FD->getLocation();
1486 // Check for ObjC 'id' and class types that have been adorned with protocol
1487 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1488 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1489 assert(funcType && "missing function type");
1490 proto = dyn_cast<FunctionTypeProto>(funcType);
1491 if (!proto)
1492 return;
1493 Type = proto->getResultType();
1494 }
1495 else
1496 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001497
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001498 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001499 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001500
1501 const char *endBuf = SM->getCharacterData(Loc);
1502 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001503 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001504 startBuf--; // scan backward (from the decl location) for return type.
1505 const char *startRef = 0, *endRef = 0;
1506 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1507 // Get the locations of the startRef, endRef.
1508 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1509 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1510 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001511 InsertText(LessLoc, "/*", 2);
1512 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001513 }
1514 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001515 if (!proto)
1516 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001517 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001518 const char *startBuf = SM->getCharacterData(Loc);
1519 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001520 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1521 if (needToScanForQualifiers(proto->getArgType(i))) {
1522 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001523
Steve Naroffc8a92d12007-11-01 13:24:47 +00001524 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001525 // scan forward (from the decl location) for argument types.
1526 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001527 const char *startRef = 0, *endRef = 0;
1528 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1529 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001530 SourceLocation LessLoc =
1531 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1532 SourceLocation GreaterLoc =
1533 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001534 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001535 InsertText(LessLoc, "/*", 2);
1536 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001537 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001538 startBuf = ++endBuf;
1539 }
1540 else {
1541 while (*startBuf != ')' && *startBuf != ',')
1542 startBuf++; // scan forward (from the decl location) for argument types.
1543 startBuf++;
1544 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001545 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001546}
1547
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001548// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1549void RewriteTest::SynthSelGetUidFunctionDecl() {
1550 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1551 llvm::SmallVector<QualType, 16> ArgTys;
1552 ArgTys.push_back(Context->getPointerType(
1553 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001554 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001555 &ArgTys[0], ArgTys.size(),
1556 false /*isVariadic*/);
1557 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1558 SelGetUidIdent, getFuncType,
1559 FunctionDecl::Extern, false, 0);
1560}
1561
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001562// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1563void RewriteTest::SynthGetProtocolFunctionDecl() {
1564 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1565 llvm::SmallVector<QualType, 16> ArgTys;
1566 ArgTys.push_back(Context->getPointerType(
1567 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001568 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001569 &ArgTys[0], ArgTys.size(),
1570 false /*isVariadic*/);
1571 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1572 SelGetProtoIdent, getFuncType,
1573 FunctionDecl::Extern, false, 0);
1574}
1575
Steve Naroff02a82aa2007-10-30 23:14:51 +00001576void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1577 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001578 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001579 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001580 return;
1581 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001582 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001583}
1584
Steve Naroffbec4bf52008-03-11 17:37:02 +00001585// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1586void RewriteTest::SynthSuperContructorFunctionDecl() {
1587 if (SuperContructorFunctionDecl)
1588 return;
1589 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1590 llvm::SmallVector<QualType, 16> ArgTys;
1591 QualType argT = Context->getObjCIdType();
1592 assert(!argT.isNull() && "Can't find 'id' type");
1593 ArgTys.push_back(argT);
1594 ArgTys.push_back(argT);
1595 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1596 &ArgTys[0], ArgTys.size(),
1597 false);
1598 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1599 msgSendIdent, msgSendType,
1600 FunctionDecl::Extern, false, 0);
1601}
1602
Steve Naroff02a82aa2007-10-30 23:14:51 +00001603// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1604void RewriteTest::SynthMsgSendFunctionDecl() {
1605 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1606 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001607 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001608 assert(!argT.isNull() && "Can't find 'id' type");
1609 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001610 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001611 assert(!argT.isNull() && "Can't find 'SEL' type");
1612 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001614 &ArgTys[0], ArgTys.size(),
1615 true /*isVariadic*/);
1616 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1617 msgSendIdent, msgSendType,
1618 FunctionDecl::Extern, false, 0);
1619}
1620
Steve Naroff764c1ae2007-11-15 10:28:18 +00001621// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1622void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1623 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1624 llvm::SmallVector<QualType, 16> ArgTys;
1625 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1626 &Context->Idents.get("objc_super"), 0);
1627 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1628 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1629 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001630 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001631 assert(!argT.isNull() && "Can't find 'SEL' type");
1632 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001633 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001634 &ArgTys[0], ArgTys.size(),
1635 true /*isVariadic*/);
1636 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1637 msgSendIdent, msgSendType,
1638 FunctionDecl::Extern, false, 0);
1639}
1640
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001641// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1642void RewriteTest::SynthMsgSendStretFunctionDecl() {
1643 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1644 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001645 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001646 assert(!argT.isNull() && "Can't find 'id' type");
1647 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001648 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001649 assert(!argT.isNull() && "Can't find 'SEL' type");
1650 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001651 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001652 &ArgTys[0], ArgTys.size(),
1653 true /*isVariadic*/);
1654 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1655 msgSendIdent, msgSendType,
1656 FunctionDecl::Extern, false, 0);
1657}
1658
1659// SynthMsgSendSuperStretFunctionDecl -
1660// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1661void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1662 IdentifierInfo *msgSendIdent =
1663 &Context->Idents.get("objc_msgSendSuper_stret");
1664 llvm::SmallVector<QualType, 16> ArgTys;
1665 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1666 &Context->Idents.get("objc_super"), 0);
1667 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1668 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1669 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001670 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001671 assert(!argT.isNull() && "Can't find 'SEL' type");
1672 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001673 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001674 &ArgTys[0], ArgTys.size(),
1675 true /*isVariadic*/);
1676 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1677 msgSendIdent, msgSendType,
1678 FunctionDecl::Extern, false, 0);
1679}
1680
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001681// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1682void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1683 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1684 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001685 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001686 assert(!argT.isNull() && "Can't find 'id' type");
1687 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001688 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001689 assert(!argT.isNull() && "Can't find 'SEL' type");
1690 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001691 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001692 &ArgTys[0], ArgTys.size(),
1693 true /*isVariadic*/);
1694 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1695 msgSendIdent, msgSendType,
1696 FunctionDecl::Extern, false, 0);
1697}
1698
Steve Naroff02a82aa2007-10-30 23:14:51 +00001699// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1700void RewriteTest::SynthGetClassFunctionDecl() {
1701 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1702 llvm::SmallVector<QualType, 16> ArgTys;
1703 ArgTys.push_back(Context->getPointerType(
1704 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001705 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001706 &ArgTys[0], ArgTys.size(),
1707 false /*isVariadic*/);
1708 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1709 getClassIdent, getClassType,
1710 FunctionDecl::Extern, false, 0);
1711}
1712
Steve Naroff3b1caac2007-12-07 03:50:46 +00001713// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1714void RewriteTest::SynthGetMetaClassFunctionDecl() {
1715 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1716 llvm::SmallVector<QualType, 16> ArgTys;
1717 ArgTys.push_back(Context->getPointerType(
1718 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001719 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001720 &ArgTys[0], ArgTys.size(),
1721 false /*isVariadic*/);
1722 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1723 getClassIdent, getClassType,
1724 FunctionDecl::Extern, false, 0);
1725}
1726
Steve Naroff0add5d22007-11-03 11:27:19 +00001727Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001728 QualType strType = getConstantStringStructType();
1729
1730 std::string S = "__NSConstantStringImpl_";
1731 S += utostr(NumObjCStringLiterals++);
1732
1733 std::string StrObjDecl = "static __NSConstantStringImpl " + S;
1734 StrObjDecl += " = __NSConstantStringImpl(";
1735 // The pretty printer for StringLiteral handles escape characters properly.
1736 std::ostringstream prettyBuf;
1737 Exp->getString()->printPretty(prettyBuf);
1738 StrObjDecl += prettyBuf.str();
1739 StrObjDecl += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001740 // The minus 2 removes the begin/end double quotes.
1741 StrObjDecl += utostr(prettyBuf.str().size()-2) + ");\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001742 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
1743 StrObjDecl.c_str(), StrObjDecl.size());
1744
1745 FileVarDecl *NewVD = new FileVarDecl(SourceLocation(),
1746 &Context->Idents.get(S.c_str()), strType,
1747 VarDecl::Static, NULL);
1748 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1749 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1750 Context->getPointerType(DRE->getType()),
1751 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001752 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001753 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001754 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001755 delete Exp;
1756 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001757}
1758
Ted Kremenek42730c52008-01-07 19:49:32 +00001759ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001760 // check if we are sending a message to 'super'
1761 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001762 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1763 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1764 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1765 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001766 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001767 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001768 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001769 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001770 if (ObjCInterfaceType *IT =
1771 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001772 if (IT->getDecl() ==
1773 CurMethodDecl->getClassInterface()->getSuperClass())
1774 return IT->getDecl();
1775 }
1776 }
1777 }
1778 }
1779 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001780 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001781 }
1782 return 0;
1783}
1784
1785// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1786QualType RewriteTest::getSuperStructType() {
1787 if (!SuperStructDecl) {
1788 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1789 &Context->Idents.get("objc_super"), 0);
1790 QualType FieldTypes[2];
1791
1792 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001793 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001794 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001795 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001796 // Create fields
1797 FieldDecl *FieldDecls[2];
1798
1799 for (unsigned i = 0; i < 2; ++i)
1800 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1801
1802 SuperStructDecl->defineBody(FieldDecls, 4);
1803 }
1804 return Context->getTagDeclType(SuperStructDecl);
1805}
1806
Steve Naroff47e7fa22008-03-15 00:55:56 +00001807QualType RewriteTest::getConstantStringStructType() {
1808 if (!ConstantStringDecl) {
1809 ConstantStringDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1810 &Context->Idents.get("__NSConstantStringImpl"), 0);
1811 QualType FieldTypes[4];
1812
1813 // struct objc_object *receiver;
1814 FieldTypes[0] = Context->getObjCIdType();
1815 // int flags;
1816 FieldTypes[1] = Context->IntTy;
1817 // char *str;
1818 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1819 // long length;
1820 FieldTypes[3] = Context->LongTy;
1821 // Create fields
1822 FieldDecl *FieldDecls[2];
1823
1824 for (unsigned i = 0; i < 4; ++i)
1825 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1826
1827 ConstantStringDecl->defineBody(FieldDecls, 4);
1828 }
1829 return Context->getTagDeclType(ConstantStringDecl);
1830}
1831
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001832Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001833 if (!SelGetUidFunctionDecl)
1834 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001835 if (!MsgSendFunctionDecl)
1836 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001837 if (!MsgSendSuperFunctionDecl)
1838 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001839 if (!MsgSendStretFunctionDecl)
1840 SynthMsgSendStretFunctionDecl();
1841 if (!MsgSendSuperStretFunctionDecl)
1842 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001843 if (!MsgSendFpretFunctionDecl)
1844 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001845 if (!GetClassFunctionDecl)
1846 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001847 if (!GetMetaClassFunctionDecl)
1848 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001849
Steve Naroff764c1ae2007-11-15 10:28:18 +00001850 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001851 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1852 // May need to use objc_msgSend_stret() as well.
1853 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001854 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001855 QualType resultType = mDecl->getResultType();
1856 if (resultType.getCanonicalType()->isStructureType()
1857 || resultType.getCanonicalType()->isUnionType())
1858 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001859 else if (resultType.getCanonicalType()->isRealFloatingType())
1860 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001861 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001862
Steve Naroff71226032007-10-24 22:48:43 +00001863 // Synthesize a call to objc_msgSend().
1864 llvm::SmallVector<Expr*, 8> MsgExprs;
1865 IdentifierInfo *clsName = Exp->getClassName();
1866
1867 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1868 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001869 if (!strcmp(clsName->getName(), "super")) {
1870 MsgSendFlavor = MsgSendSuperFunctionDecl;
1871 if (MsgSendStretFlavor)
1872 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1873 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1874
Ted Kremenek42730c52008-01-07 19:49:32 +00001875 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001876 CurMethodDecl->getClassInterface()->getSuperClass();
1877
1878 llvm::SmallVector<Expr*, 4> InitExprs;
1879
1880 // set the receiver to self, the first argument to all methods.
1881 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001882 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001883 SourceLocation()));
1884 llvm::SmallVector<Expr*, 8> ClsExprs;
1885 QualType argType = Context->getPointerType(Context->CharTy);
1886 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1887 SuperDecl->getIdentifier()->getLength(),
1888 false, argType, SourceLocation(),
1889 SourceLocation()));
1890 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1891 &ClsExprs[0],
1892 ClsExprs.size());
1893 // To turn off a warning, type-cast to 'id'
1894 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001895 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001896 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1897 // struct objc_super
1898 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001899 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001900
Steve Naroffdee066b2008-03-11 18:14:26 +00001901 if (LangOpts.Microsoft) {
1902 SynthSuperContructorFunctionDecl();
1903 // Simulate a contructor call...
1904 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1905 superType, SourceLocation());
1906 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1907 superType, SourceLocation());
1908 } else {
1909 // (struct objc_super) { <exprs from above> }
1910 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1911 &InitExprs[0], InitExprs.size(),
1912 SourceLocation());
1913 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1914 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001915 // struct objc_super *
1916 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1917 Context->getPointerType(SuperRep->getType()),
1918 SourceLocation());
1919 MsgExprs.push_back(Unop);
1920 } else {
1921 llvm::SmallVector<Expr*, 8> ClsExprs;
1922 QualType argType = Context->getPointerType(Context->CharTy);
1923 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1924 clsName->getLength(),
1925 false, argType, SourceLocation(),
1926 SourceLocation()));
1927 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1928 &ClsExprs[0],
1929 ClsExprs.size());
1930 MsgExprs.push_back(Cls);
1931 }
Steve Naroff885e2122007-11-14 23:54:14 +00001932 } else { // instance message.
1933 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001934
Ted Kremenek42730c52008-01-07 19:49:32 +00001935 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001936 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001937 if (MsgSendStretFlavor)
1938 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001939 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1940
1941 llvm::SmallVector<Expr*, 4> InitExprs;
1942
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001943 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001944 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001945 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001946
1947 llvm::SmallVector<Expr*, 8> ClsExprs;
1948 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001949 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1950 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001951 false, argType, SourceLocation(),
1952 SourceLocation()));
1953 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001954 &ClsExprs[0],
1955 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001956 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001957 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001958 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001959 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001960 // struct objc_super
1961 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001962 Expr *SuperRep;
1963
1964 if (LangOpts.Microsoft) {
1965 SynthSuperContructorFunctionDecl();
1966 // Simulate a contructor call...
1967 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1968 superType, SourceLocation());
1969 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1970 superType, SourceLocation());
1971 } else {
1972 // (struct objc_super) { <exprs from above> }
1973 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1974 &InitExprs[0], InitExprs.size(),
1975 SourceLocation());
1976 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1977 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001978 // struct objc_super *
1979 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1980 Context->getPointerType(SuperRep->getType()),
1981 SourceLocation());
1982 MsgExprs.push_back(Unop);
1983 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001984 // Remove all type-casts because it may contain objc-style types; e.g.
1985 // Foo<Proto> *.
1986 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1987 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001988 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001989 MsgExprs.push_back(recExpr);
1990 }
Steve Naroff885e2122007-11-14 23:54:14 +00001991 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001992 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001993 llvm::SmallVector<Expr*, 8> SelExprs;
1994 QualType argType = Context->getPointerType(Context->CharTy);
1995 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1996 Exp->getSelector().getName().size(),
1997 false, argType, SourceLocation(),
1998 SourceLocation()));
1999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2000 &SelExprs[0], SelExprs.size());
2001 MsgExprs.push_back(SelExp);
2002
2003 // Now push any user supplied arguments.
2004 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002005 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002006 // Make all implicit casts explicit...ICE comes in handy:-)
2007 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2008 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002009 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2010 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002011 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002012 }
2013 // Make id<P...> cast into an 'id' cast.
2014 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002015 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002016 while ((CE = dyn_cast<CastExpr>(userExpr)))
2017 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002018 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002019 userExpr, SourceLocation());
2020 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002021 }
Steve Naroff885e2122007-11-14 23:54:14 +00002022 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002023 // We've transferred the ownership to MsgExprs. Null out the argument in
2024 // the original expression, since we will delete it below.
2025 Exp->setArg(i, 0);
2026 }
Steve Naroff0744c472007-11-04 22:37:50 +00002027 // Generate the funky cast.
2028 CastExpr *cast;
2029 llvm::SmallVector<QualType, 8> ArgTypes;
2030 QualType returnType;
2031
2032 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002033 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2034 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2035 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002036 ArgTypes.push_back(Context->getObjCIdType());
2037 ArgTypes.push_back(Context->getObjCSelType());
2038 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002039 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00002040 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002041 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2042 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002043 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002044 ArgTypes.push_back(t);
2045 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002046 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2047 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002048 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002049 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002050 }
2051 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002052 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002053
2054 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002055 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2056 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002057
2058 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2059 // If we don't do this cast, we get the following bizarre warning/note:
2060 // xx.m:13: warning: function called through a non-compatible type
2061 // xx.m:13: note: if this code is reached, the program will abort
2062 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2063 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002064
Steve Naroff0744c472007-11-04 22:37:50 +00002065 // Now do the "normal" pointer to function cast.
2066 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002067 &ArgTypes[0], ArgTypes.size(),
2068 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00002069 castType = Context->getPointerType(castType);
2070 cast = new CastExpr(castType, cast, SourceLocation());
2071
2072 // Don't forget the parens to enforce the proper binding.
2073 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2074
2075 const FunctionType *FT = msgSendType->getAsFunctionType();
2076 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2077 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002078 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002079 if (MsgSendStretFlavor) {
2080 // We have the method which returns a struct/union. Must also generate
2081 // call to objc_msgSend_stret and hang both varieties on a conditional
2082 // expression which dictate which one to envoke depending on size of
2083 // method's return type.
2084
2085 // Create a reference to the objc_msgSend_stret() declaration.
2086 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2087 SourceLocation());
2088 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2089 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2090 SourceLocation());
2091 // Now do the "normal" pointer to function cast.
2092 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002093 &ArgTypes[0], ArgTypes.size(),
2094 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002095 castType = Context->getPointerType(castType);
2096 cast = new CastExpr(castType, cast, SourceLocation());
2097
2098 // Don't forget the parens to enforce the proper binding.
2099 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2100
2101 FT = msgSendType->getAsFunctionType();
2102 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2103 FT->getResultType(), SourceLocation());
2104
2105 // Build sizeof(returnType)
2106 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2107 returnType, Context->getSizeType(),
2108 SourceLocation(), SourceLocation());
2109 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2110 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2111 // For X86 it is more complicated and some kind of target specific routine
2112 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002113 unsigned IntSize =
2114 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002115 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2116 Context->IntTy,
2117 SourceLocation());
2118 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2119 BinaryOperator::LE,
2120 Context->IntTy,
2121 SourceLocation());
2122 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2123 ConditionalOperator *CondExpr =
2124 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002125 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002126 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002127 return ReplacingStmt;
2128}
2129
2130Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2131 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002132 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002133 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002134
Chris Lattner0021f452007-10-24 16:57:36 +00002135 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002136 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002137}
2138
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002139/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2140/// call to objc_getProtocol("proto-name").
2141Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2142 if (!GetProtocolFunctionDecl)
2143 SynthGetProtocolFunctionDecl();
2144 // Create a call to objc_getProtocol("ProtocolName").
2145 llvm::SmallVector<Expr*, 8> ProtoExprs;
2146 QualType argType = Context->getPointerType(Context->CharTy);
2147 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2148 strlen(Exp->getProtocol()->getName()),
2149 false, argType, SourceLocation(),
2150 SourceLocation()));
2151 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2152 &ProtoExprs[0],
2153 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002154 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002155 delete Exp;
2156 return ProtoExp;
2157
2158}
2159
Ted Kremenek42730c52008-01-07 19:49:32 +00002160/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002161/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002162void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002163 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002164 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2165 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002166 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002167 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002168 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002169 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002170 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002171 SourceLocation LocStart = CDecl->getLocStart();
2172 SourceLocation LocEnd = CDecl->getLocEnd();
2173
2174 const char *startBuf = SM->getCharacterData(LocStart);
2175 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002176 // If no ivars and no root or if its root, directly or indirectly,
2177 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002178 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002179 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002180 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002181 return;
2182 }
2183
2184 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002185 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002186 Result += "\nstruct ";
2187 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002188 if (LangOpts.Microsoft)
2189 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002190
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002191 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002192 const char *cursor = strchr(startBuf, '{');
2193 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002194 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002195
2196 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002197 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002198 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002199 Result = "\n struct ";
2200 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002201 Result += "_IMPL ";
2202 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002203 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002204
2205 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002206 SourceLocation OnePastCurly =
2207 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2208 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002209 }
2210 cursor++; // past '{'
2211
2212 // Now comment out any visibility specifiers.
2213 while (cursor < endBuf) {
2214 if (*cursor == '@') {
2215 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002216 // Skip whitespace.
2217 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2218 /*scan*/;
2219
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002220 // FIXME: presence of @public, etc. inside comment results in
2221 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002222 if (!strncmp(cursor, "public", strlen("public")) ||
2223 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002224 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002225 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002226 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002227 // FIXME: If there are cases where '<' is used in ivar declaration part
2228 // of user code, then scan the ivar list and use needToScanForQualifiers
2229 // for type checking.
2230 else if (*cursor == '<') {
2231 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002232 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002233 cursor = strchr(cursor, '>');
2234 cursor++;
2235 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002236 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002237 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002238 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002239 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002240 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002241 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002242 } else { // we don't have any instance variables - insert super struct.
2243 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2244 Result += " {\n struct ";
2245 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002246 Result += "_IMPL ";
2247 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002248 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002249 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002250 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002251 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002252 if (!ObjCSynthesizedStructs.insert(CDecl))
2253 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002254}
2255
Ted Kremenek42730c52008-01-07 19:49:32 +00002256// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002257/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002258void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002259 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002260 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002261 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002262 const char *ClassName,
2263 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002264 if (MethodBegin == MethodEnd) return;
2265
Fariborz Jahanian04455192007-10-22 21:41:37 +00002266 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002267 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002268 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002269 SEL _cmd;
2270 char *method_types;
2271 void *_imp;
2272 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002273 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002274 Result += "\nstruct _objc_method {\n";
2275 Result += "\tSEL _cmd;\n";
2276 Result += "\tchar *method_types;\n";
2277 Result += "\tvoid *_imp;\n";
2278 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002279
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002280 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002281 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002282
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002283 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002284
2285 /* struct {
2286 struct _objc_method_list *next_method;
2287 int method_count;
2288 struct _objc_method method_list[];
2289 }
2290 */
2291 Result += "\nstatic struct {\n";
2292 Result += "\tstruct _objc_method_list *next_method;\n";
2293 Result += "\tint method_count;\n";
2294 Result += "\tstruct _objc_method method_list[";
2295 Result += utostr(MethodEnd-MethodBegin);
2296 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002297 Result += prefix;
2298 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2299 Result += "_METHODS_";
2300 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002301 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002302 Result += IsInstanceMethod ? "inst" : "cls";
2303 Result += "_meth\")))= ";
2304 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002305
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002306 Result += "\t,{{(SEL)\"";
2307 Result += (*MethodBegin)->getSelector().getName().c_str();
2308 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002309 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002310 Result += "\", \"";
2311 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002312 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002313 Result += MethodInternalNames[*MethodBegin];
2314 Result += "}\n";
2315 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2316 Result += "\t ,{(SEL)\"";
2317 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002318 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002319 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002320 Result += "\", \"";
2321 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002322 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002323 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002324 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002325 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002326 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002327}
2328
Ted Kremenek42730c52008-01-07 19:49:32 +00002329/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2330void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002331 int NumProtocols,
2332 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002333 const char *ClassName,
2334 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002335 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002336 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002337 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002338 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002339 // Output struct protocol_methods holder of method selector and type.
2340 if (!objc_protocol_methods &&
2341 (PDecl->getNumInstanceMethods() > 0
2342 || PDecl->getNumClassMethods() > 0)) {
2343 /* struct protocol_methods {
2344 SEL _cmd;
2345 char *method_types;
2346 }
2347 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002348 Result += "\nstruct protocol_methods {\n";
2349 Result += "\tSEL _cmd;\n";
2350 Result += "\tchar *method_types;\n";
2351 Result += "};\n";
2352
Steve Naroff27429432008-03-12 01:06:30 +00002353 objc_protocol_methods = true;
2354 }
2355 int NumMethods = PDecl->getNumInstanceMethods();
2356 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002357 /* struct _objc_protocol_method_list {
2358 int protocol_method_count;
2359 struct protocol_methods protocols[];
2360 }
2361 */
Steve Naroff27429432008-03-12 01:06:30 +00002362 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002363 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002364 Result += "\tstruct protocol_methods protocols[";
2365 Result += utostr(NumMethods);
2366 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002367 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002368 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002369 "{\n\t" + utostr(NumMethods) + "\n";
2370
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002371 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002372 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002373 E = PDecl->instmeth_end(); I != E; ++I) {
2374 if (I == PDecl->instmeth_begin())
2375 Result += "\t ,{{(SEL)\"";
2376 else
2377 Result += "\t ,{(SEL)\"";
2378 Result += (*I)->getSelector().getName().c_str();
2379 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002380 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002381 Result += "\", \"";
2382 Result += MethodTypeString;
2383 Result += "\"}\n";
2384 }
2385 Result += "\t }\n};\n";
2386 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002387
2388 // Output class methods declared in this protocol.
2389 NumMethods = PDecl->getNumClassMethods();
2390 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002391 /* struct _objc_protocol_method_list {
2392 int protocol_method_count;
2393 struct protocol_methods protocols[];
2394 }
2395 */
2396 Result += "\nstatic struct {\n";
2397 Result += "\tint protocol_method_count;\n";
2398 Result += "\tstruct protocol_methods protocols[";
2399 Result += utostr(NumMethods);
2400 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002401 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002402 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002403 "{\n\t";
2404 Result += utostr(NumMethods);
2405 Result += "\n";
2406
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002407 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002408 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002409 E = PDecl->classmeth_end(); I != E; ++I) {
2410 if (I == PDecl->classmeth_begin())
2411 Result += "\t ,{{(SEL)\"";
2412 else
2413 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002414 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002415 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002416 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002417 Result += "\", \"";
2418 Result += MethodTypeString;
2419 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002420 }
2421 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002422 }
2423 // Output:
2424 /* struct _objc_protocol {
2425 // Objective-C 1.0 extensions
2426 struct _objc_protocol_extension *isa;
2427 char *protocol_name;
2428 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002429 struct _objc_protocol_method_list *instance_methods;
2430 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002431 };
2432 */
2433 static bool objc_protocol = false;
2434 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002435 Result += "\nstruct _objc_protocol {\n";
2436 Result += "\tstruct _objc_protocol_extension *isa;\n";
2437 Result += "\tchar *protocol_name;\n";
2438 Result += "\tstruct _objc_protocol **protocol_list;\n";
2439 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2440 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2441 Result += "};\n";
2442
Fariborz Jahanian04455192007-10-22 21:41:37 +00002443 objc_protocol = true;
2444 }
2445
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002446 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2447 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002448 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002449 "{\n\t0, \"";
2450 Result += PDecl->getName();
2451 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002452 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002453 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002454 Result += PDecl->getName();
2455 Result += ", ";
2456 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002457 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002458 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002459 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002460 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002461 Result += PDecl->getName();
2462 Result += "\n";
2463 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002464 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002465 Result += "0\n";
2466 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002467 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002468 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002469 /* struct _objc_protocol_list {
2470 struct _objc_protocol_list *next;
2471 int protocol_count;
2472 struct _objc_protocol *class_protocols[];
2473 }
2474 */
2475 Result += "\nstatic struct {\n";
2476 Result += "\tstruct _objc_protocol_list *next;\n";
2477 Result += "\tint protocol_count;\n";
2478 Result += "\tstruct _objc_protocol *class_protocols[";
2479 Result += utostr(NumProtocols);
2480 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002481 Result += prefix;
2482 Result += "_PROTOCOLS_";
2483 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002484 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002485 "{\n\t0, ";
2486 Result += utostr(NumProtocols);
2487 Result += "\n";
2488
2489 Result += "\t,{&_OBJC_PROTOCOL_";
2490 Result += Protocols[0]->getName();
2491 Result += " \n";
2492
2493 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002494 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff27429432008-03-12 01:06:30 +00002495 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002496 Result += PDecl->getName();
2497 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002498 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002499 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002500 }
2501}
2502
Ted Kremenek42730c52008-01-07 19:49:32 +00002503/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002504/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002505void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002506 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002507 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002508 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002509 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002510 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2511 CDecl = CDecl->getNextClassCategory())
2512 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2513 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002514
Chris Lattnera661a4d2007-12-23 01:40:15 +00002515 std::string FullCategoryName = ClassDecl->getName();
2516 FullCategoryName += '_';
2517 FullCategoryName += IDecl->getName();
2518
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002519 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002520 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002521 true, "CATEGORY_", FullCategoryName.c_str(),
2522 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002523
2524 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002525 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002526 false, "CATEGORY_", FullCategoryName.c_str(),
2527 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002528
2529 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002530 // Null CDecl is case of a category implementation with no category interface
2531 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002532 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002533 CDecl->getNumReferencedProtocols(),
2534 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002535 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002536
2537 /* struct _objc_category {
2538 char *category_name;
2539 char *class_name;
2540 struct _objc_method_list *instance_methods;
2541 struct _objc_method_list *class_methods;
2542 struct _objc_protocol_list *protocols;
2543 // Objective-C 1.0 extensions
2544 uint32_t size; // sizeof (struct _objc_category)
2545 struct _objc_property_list *instance_properties; // category's own
2546 // @property decl.
2547 };
2548 */
2549
2550 static bool objc_category = false;
2551 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002552 Result += "\nstruct _objc_category {\n";
2553 Result += "\tchar *category_name;\n";
2554 Result += "\tchar *class_name;\n";
2555 Result += "\tstruct _objc_method_list *instance_methods;\n";
2556 Result += "\tstruct _objc_method_list *class_methods;\n";
2557 Result += "\tstruct _objc_protocol_list *protocols;\n";
2558 Result += "\tunsigned int size;\n";
2559 Result += "\tstruct _objc_property_list *instance_properties;\n";
2560 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002561 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002562 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002563 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2564 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002565 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002566 Result += IDecl->getName();
2567 Result += "\"\n\t, \"";
2568 Result += ClassDecl->getName();
2569 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002570
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002571 if (IDecl->getNumInstanceMethods() > 0) {
2572 Result += "\t, (struct _objc_method_list *)"
2573 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2574 Result += FullCategoryName;
2575 Result += "\n";
2576 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002577 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002578 Result += "\t, 0\n";
2579 if (IDecl->getNumClassMethods() > 0) {
2580 Result += "\t, (struct _objc_method_list *)"
2581 "&_OBJC_CATEGORY_CLASS_METHODS_";
2582 Result += FullCategoryName;
2583 Result += "\n";
2584 }
2585 else
2586 Result += "\t, 0\n";
2587
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002588 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002589 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2590 Result += FullCategoryName;
2591 Result += "\n";
2592 }
2593 else
2594 Result += "\t, 0\n";
2595 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002596}
2597
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002598/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2599/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002600void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2601 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002602 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002603 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002604 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002605 if (LangOpts.Microsoft)
2606 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002607 Result += ", ";
2608 Result += ivar->getName();
2609 Result += ")";
2610}
2611
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002612//===----------------------------------------------------------------------===//
2613// Meta Data Emission
2614//===----------------------------------------------------------------------===//
2615
Ted Kremenek42730c52008-01-07 19:49:32 +00002616void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002617 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002618 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002619
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002620 // Explictly declared @interface's are already synthesized.
2621 if (CDecl->ImplicitInterfaceDecl()) {
2622 // FIXME: Implementation of a class with no @interface (legacy) doese not
2623 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002624 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002625 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002626
Chris Lattnerc7b06752007-12-12 07:56:42 +00002627 // Build _objc_ivar_list metadata for classes ivars if needed
2628 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2629 ? IDecl->getImplDeclNumIvars()
2630 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002631 if (NumIvars > 0) {
2632 static bool objc_ivar = false;
2633 if (!objc_ivar) {
2634 /* struct _objc_ivar {
2635 char *ivar_name;
2636 char *ivar_type;
2637 int ivar_offset;
2638 };
2639 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002640 Result += "\nstruct _objc_ivar {\n";
2641 Result += "\tchar *ivar_name;\n";
2642 Result += "\tchar *ivar_type;\n";
2643 Result += "\tint ivar_offset;\n";
2644 Result += "};\n";
2645
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002646 objc_ivar = true;
2647 }
2648
Steve Naroffc723eec2008-03-11 00:12:29 +00002649 /* struct {
2650 int ivar_count;
2651 struct _objc_ivar ivar_list[nIvars];
2652 };
2653 */
2654 Result += "\nstatic struct {\n";
2655 Result += "\tint ivar_count;\n";
2656 Result += "\tstruct _objc_ivar ivar_list[";
2657 Result += utostr(NumIvars);
2658 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002659 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002660 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002661 "{\n\t";
2662 Result += utostr(NumIvars);
2663 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002664
Ted Kremenek42730c52008-01-07 19:49:32 +00002665 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002666 if (IDecl->getImplDeclNumIvars() > 0) {
2667 IVI = IDecl->ivar_begin();
2668 IVE = IDecl->ivar_end();
2669 } else {
2670 IVI = CDecl->ivar_begin();
2671 IVE = CDecl->ivar_end();
2672 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002673 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002674 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002675 Result += "\", \"";
2676 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002677 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2678 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002679 Result += StrEncoding;
2680 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002681 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002682 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002683 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002684 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002685 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002686 Result += "\", \"";
2687 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002688 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2689 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002690 Result += StrEncoding;
2691 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002692 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002693 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002694 }
2695
2696 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002697 }
2698
2699 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002700 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002701 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002702
2703 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002704 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002705 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002706
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002707 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002708 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002709 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002710 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002711
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002712
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002713 // Declaration of class/meta-class metadata
2714 /* struct _objc_class {
2715 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002716 const char *super_class_name;
2717 char *name;
2718 long version;
2719 long info;
2720 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002721 struct _objc_ivar_list *ivars;
2722 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002723 struct objc_cache *cache;
2724 struct objc_protocol_list *protocols;
2725 const char *ivar_layout;
2726 struct _objc_class_ext *ext;
2727 };
2728 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002729 static bool objc_class = false;
2730 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002731 Result += "\nstruct _objc_class {\n";
2732 Result += "\tstruct _objc_class *isa;\n";
2733 Result += "\tconst char *super_class_name;\n";
2734 Result += "\tchar *name;\n";
2735 Result += "\tlong version;\n";
2736 Result += "\tlong info;\n";
2737 Result += "\tlong instance_size;\n";
2738 Result += "\tstruct _objc_ivar_list *ivars;\n";
2739 Result += "\tstruct _objc_method_list *methods;\n";
2740 Result += "\tstruct objc_cache *cache;\n";
2741 Result += "\tstruct _objc_protocol_list *protocols;\n";
2742 Result += "\tconst char *ivar_layout;\n";
2743 Result += "\tstruct _objc_class_ext *ext;\n";
2744 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002745 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002746 }
2747
2748 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002749 ObjCInterfaceDecl *RootClass = 0;
2750 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002751 while (SuperClass) {
2752 RootClass = SuperClass;
2753 SuperClass = SuperClass->getSuperClass();
2754 }
2755 SuperClass = CDecl->getSuperClass();
2756
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002757 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2758 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002759 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002760 "{\n\t(struct _objc_class *)\"";
2761 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2762 Result += "\"";
2763
2764 if (SuperClass) {
2765 Result += ", \"";
2766 Result += SuperClass->getName();
2767 Result += "\", \"";
2768 Result += CDecl->getName();
2769 Result += "\"";
2770 }
2771 else {
2772 Result += ", 0, \"";
2773 Result += CDecl->getName();
2774 Result += "\"";
2775 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002776 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002777 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002778 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002779 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002780 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002781 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002782 Result += "\n";
2783 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002784 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002785 Result += ", 0\n";
2786 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002787 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002788 Result += CDecl->getName();
2789 Result += ",0,0\n";
2790 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002791 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002792 Result += "\t,0,0,0,0\n";
2793 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002794
2795 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002796 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2797 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002798 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002799 "{\n\t&_OBJC_METACLASS_";
2800 Result += CDecl->getName();
2801 if (SuperClass) {
2802 Result += ", \"";
2803 Result += SuperClass->getName();
2804 Result += "\", \"";
2805 Result += CDecl->getName();
2806 Result += "\"";
2807 }
2808 else {
2809 Result += ", 0, \"";
2810 Result += CDecl->getName();
2811 Result += "\"";
2812 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002813 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002814 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002815 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002816 Result += ",0";
2817 else {
2818 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002819 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002820 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002821 if (LangOpts.Microsoft)
2822 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002823 Result += ")";
2824 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002825 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002826 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002827 Result += CDecl->getName();
2828 Result += "\n\t";
2829 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002830 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002831 Result += ",0";
2832 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002833 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002834 Result += CDecl->getName();
2835 Result += ", 0\n\t";
2836 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002837 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002838 Result += ",0,0";
2839 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002840 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002841 Result += CDecl->getName();
2842 Result += ", 0,0\n";
2843 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002844 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002845 Result += ",0,0,0\n";
2846 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002847}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002848
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002849/// RewriteImplementations - This routine rewrites all method implementations
2850/// and emits meta-data.
2851
2852void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002853 int ClsDefCount = ClassImplementation.size();
2854 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002855
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002856 if (ClsDefCount == 0 && CatDefCount == 0)
2857 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002858 // Rewrite implemented methods
2859 for (int i = 0; i < ClsDefCount; i++)
2860 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002861
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002862 for (int i = 0; i < CatDefCount; i++)
2863 RewriteImplementationDecl(CategoryImplementation[i]);
2864
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002865 // This is needed for use of offsetof
2866 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002867
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002868 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002869 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002870 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002871
2872 // For each implemented category, write out all its meta data.
2873 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002874 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002875
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002876 // Write objc_symtab metadata
2877 /*
2878 struct _objc_symtab
2879 {
2880 long sel_ref_cnt;
2881 SEL *refs;
2882 short cls_def_cnt;
2883 short cat_def_cnt;
2884 void *defs[cls_def_cnt + cat_def_cnt];
2885 };
2886 */
2887
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002888 Result += "\nstruct _objc_symtab {\n";
2889 Result += "\tlong sel_ref_cnt;\n";
2890 Result += "\tSEL *refs;\n";
2891 Result += "\tshort cls_def_cnt;\n";
2892 Result += "\tshort cat_def_cnt;\n";
2893 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2894 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002895
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002896 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002897 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002898 Result += "\t0, 0, " + utostr(ClsDefCount)
2899 + ", " + utostr(CatDefCount) + "\n";
2900 for (int i = 0; i < ClsDefCount; i++) {
2901 Result += "\t,&_OBJC_CLASS_";
2902 Result += ClassImplementation[i]->getName();
2903 Result += "\n";
2904 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002905
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002906 for (int i = 0; i < CatDefCount; i++) {
2907 Result += "\t,&_OBJC_CATEGORY_";
2908 Result += CategoryImplementation[i]->getClassInterface()->getName();
2909 Result += "_";
2910 Result += CategoryImplementation[i]->getName();
2911 Result += "\n";
2912 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002913
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002914 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002915
2916 // Write objc_module metadata
2917
2918 /*
2919 struct _objc_module {
2920 long version;
2921 long size;
2922 const char *name;
2923 struct _objc_symtab *symtab;
2924 }
2925 */
2926
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002927 Result += "\nstruct _objc_module {\n";
2928 Result += "\tlong version;\n";
2929 Result += "\tlong size;\n";
2930 Result += "\tconst char *name;\n";
2931 Result += "\tstruct _objc_symtab *symtab;\n";
2932 Result += "};\n\n";
2933 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002934 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002935 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2936 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002937 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002938
2939 if (LangOpts.Microsoft) {
2940 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2941 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2942 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2943 Result += "&_OBJC_MODULES;\n";
2944 Result += "#pragma data_seg(pop)\n\n";
2945 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002946}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002947