blob: afd34b968e4a9608fbc51cf8f83332e1ee5cb21c [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"
Chris Lattner673f2bd2008-03-22 00:08:40 +000026#include "llvm/System/Path.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000027#include <sstream>
Chris Lattner673f2bd2008-03-22 00:08:40 +000028#include <fstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000029using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000031
Steve Naroff1c46cf12008-01-28 21:34:52 +000032static llvm::cl::opt<bool>
33SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
34 llvm::cl::desc("Silence ObjC rewriting warnings"));
35
Chris Lattnerb429ae42007-10-11 00:43:27 +000036namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000037 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000038 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000039 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000040 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000041 unsigned RewriteFailedDiag;
42
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000043 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000044 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000045 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000046 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000047 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000048
Ted Kremenek42730c52008-01-07 19:49:32 +000049 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
50 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
51 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
52 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
53 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000054 llvm::SmallVector<Stmt *, 32> Stmts;
55 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000056 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000057
Steve Naroff47e7fa22008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffe9780582007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000069 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000070 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000071
Steve Naroff0add5d22007-11-03 11:27:19 +000072 // ObjC string constant support.
73 FileVarDecl *ConstantStringClassReference;
74 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000075
Fariborz Jahanian22277422008-01-16 00:09:11 +000076 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000077 int BcLabelCount;
78
Steve Naroff764c1ae2007-11-15 10:28:18 +000079 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000080 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000081 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000082 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000083
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000084 // Needed for header files being rewritten
85 bool IsHeader;
86
Chris Lattner673f2bd2008-03-22 00:08:40 +000087 std::ostream &OutFile;
88
Steve Narofffef037c2008-03-27 22:29:16 +000089 std::string Preamble;
90
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000091 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000092 public:
Chris Lattner12499682008-01-31 19:38:44 +000093 void Initialize(ASTContext &context);
94
Chris Lattner569faa62007-10-11 18:38:32 +000095
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000096 // Top Level Driver code.
97 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000098 void HandleDeclInMainFile(Decl *D);
Chris Lattner673f2bd2008-03-22 00:08:40 +000099 RewriteTest(bool isHeader, std::ostream &outFile,
100 Diagnostic &D, const LangOptions &LOpts)
101 : Diags(D), LangOpts(LOpts), OutFile(outFile) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000102 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +0000103 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
104 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000105 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000106 ~RewriteTest();
Chris Lattnerb1548372008-01-31 19:37:57 +0000107
108 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000109 // If replacement succeeded or warning disabled return with no warning.
110 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000111 return;
112
Chris Lattnerb1548372008-01-31 19:37:57 +0000113 SourceRange Range = Old->getSourceRange();
114 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
115 0, 0, &Range, 1);
116 }
117
Steve Narofffef037c2008-03-27 22:29:16 +0000118 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
119 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000120 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000121 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000122 SilenceRewriteMacroWarning)
123 return;
124
125 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
126 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000127
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000128 void RemoveText(SourceLocation Loc, unsigned StrLen) {
129 // If removal succeeded or warning disabled return with no warning.
130 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
131 return;
132
133 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
134 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000135
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000136 void ReplaceText(SourceLocation Start, unsigned OrigLength,
137 const char *NewStr, unsigned NewLength) {
138 // If removal succeeded or warning disabled return with no warning.
139 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
140 SilenceRewriteMacroWarning)
141 return;
142
143 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
144 }
145
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000146 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000147 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000148 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000149 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000150 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
151 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000152 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000153 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
154 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
155 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
156 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
157 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattnercffe3662008-03-16 21:23:50 +0000158 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000159 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000160 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000161 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000162 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000163 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000164 QualType getConstantStringStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000165
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000166 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000167 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000168 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000169 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000170 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000171 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000172 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000173 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000174 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000175 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000176 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
177 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
178 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000179 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
180 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000181 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
182 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000183 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000184 Stmt *RewriteBreakStmt(BreakStmt *S);
185 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000186 void SynthCountByEnumWithState(std::string &buf);
187
Steve Naroff02a82aa2007-10-30 23:14:51 +0000188 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000189 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000190 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000191 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000192 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000193 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000194 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000195 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000196 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000197 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000198
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000199 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000200 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000201 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000202
Ted Kremenek42730c52008-01-07 19:49:32 +0000203 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000204 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000205
Ted Kremenek42730c52008-01-07 19:49:32 +0000206 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
207 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000208 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000209 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000210 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000211 const char *ClassName,
212 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000213
Ted Kremenek42730c52008-01-07 19:49:32 +0000214 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000215 int NumProtocols,
216 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000217 const char *ClassName,
218 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000219 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000220 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000221 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
222 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000223 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000224 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000225 };
226}
227
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000228static bool IsHeaderFile(const std::string &Filename) {
229 std::string::size_type DotPos = Filename.rfind('.');
230
231 if (DotPos == std::string::npos) {
232 // no file extension
233 return false;
234 }
235
236 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
237 // C header: .h
238 // C++ header: .hh or .H;
239 return Ext == "h" || Ext == "hh" || Ext == "H";
240}
241
242ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000243 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000244 Diagnostic &Diags,
245 const LangOptions &LOpts) {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000246 // Create the output file.
247
248 std::ostream *Out;
249 if (OutFile == "-") {
250 Out = llvm::cout.stream();
251 } else if (!OutFile.empty()) {
252 Out = new std::ofstream(OutFile.c_str(),
253 std::ios_base::binary|std::ios_base::out);
254 } else if (InFile == "-") {
255 Out = llvm::cout.stream();
256 } else {
257 llvm::sys::Path Path(InFile);
258 Path.eraseSuffix();
259 Path.appendSuffix("cpp");
260 Out = new std::ofstream(Path.toString().c_str(),
261 std::ios_base::binary|std::ios_base::out);
262 }
263
264 return new RewriteTest(IsHeaderFile(InFile), *Out, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000265}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000266
Chris Lattner12499682008-01-31 19:38:44 +0000267void RewriteTest::Initialize(ASTContext &context) {
268 Context = &context;
269 SM = &Context->getSourceManager();
270 MsgSendFunctionDecl = 0;
271 MsgSendSuperFunctionDecl = 0;
272 MsgSendStretFunctionDecl = 0;
273 MsgSendSuperStretFunctionDecl = 0;
274 MsgSendFpretFunctionDecl = 0;
275 GetClassFunctionDecl = 0;
276 GetMetaClassFunctionDecl = 0;
277 SelGetUidFunctionDecl = 0;
278 CFStringFunctionDecl = 0;
279 GetProtocolFunctionDecl = 0;
280 ConstantStringClassReference = 0;
281 NSStringRecord = 0;
282 CurMethodDecl = 0;
283 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000284 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000285 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000286 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000287 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000288
289 // Get the ID and start/end of the main file.
290 MainFileID = SM->getMainFileID();
291 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
292 MainFileStart = MainBuf->getBufferStart();
293 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000294
Chris Lattner12499682008-01-31 19:38:44 +0000295 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000296
Chris Lattner12499682008-01-31 19:38:44 +0000297 // declaring objc_selector outside the parameter list removes a silly
298 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000299 if (IsHeader)
300 Preamble = "#pragma once\n";
301 Preamble += "struct objc_selector; struct objc_class;\n";
302 Preamble += "#ifndef OBJC_SUPER\n";
303 Preamble += "struct objc_super { struct objc_object *object; ";
304 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000305 if (LangOpts.Microsoft) {
306 // Add a constructor for creating temporary objects.
Steve Narofffef037c2008-03-27 22:29:16 +0000307 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
308 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000309 }
Steve Narofffef037c2008-03-27 22:29:16 +0000310 Preamble += "};\n";
311 Preamble += "#define OBJC_SUPER\n";
312 Preamble += "#endif\n";
313 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
314 Preamble += "typedef struct objc_object Protocol;\n";
315 Preamble += "#define _REWRITER_typedef_Protocol\n";
316 Preamble += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000317 if (LangOpts.Microsoft)
Steve Narofffef037c2008-03-27 22:29:16 +0000318 Preamble += "extern \"C\" {\n";
319 Preamble += "struct objc_object *objc_msgSend";
320 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
321 Preamble += "extern struct objc_object *objc_msgSendSuper";
322 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
323 Preamble += "extern struct objc_object *objc_msgSend_stret";
324 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
325 Preamble += "extern struct objc_object *objc_msgSendSuper_stret";
326 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
327 Preamble += "extern struct objc_object *objc_msgSend_fpret";
328 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
329 Preamble += "struct objc_object *objc_getClass";
330 Preamble += "(const char *);\n";
331 Preamble += "extern struct objc_object *objc_getMetaClass";
332 Preamble += "(const char *);\n";
333 Preamble += "extern void objc_exception_throw(struct objc_object *);\n";
334 Preamble += "extern void objc_exception_try_enter(void *);\n";
335 Preamble += "extern void objc_exception_try_exit(void *);\n";
336 Preamble += "extern struct objc_object *objc_exception_extract(void *);\n";
337 Preamble += "extern int objc_exception_match";
338 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
339 Preamble += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000340 if (LangOpts.Microsoft)
Steve Narofffef037c2008-03-27 22:29:16 +0000341 Preamble += "} // end extern \"C\"\n";
342 Preamble += "#include <objc/objc.h>\n";
343 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
344 Preamble += "struct __objcFastEnumerationState {\n\t";
345 Preamble += "unsigned long state;\n\t";
346 Preamble += "id *itemsPtr;\n\t";
347 Preamble += "unsigned long *mutationsPtr;\n\t";
348 Preamble += "unsigned long extra[5];\n};\n";
349 Preamble += "#define __FASTENUMERATIONSTATE\n";
350 Preamble += "#endif\n";
351 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
352 Preamble += "struct __NSConstantStringImpl {\n";
353 Preamble += " int *isa;\n";
354 Preamble += " int flags;\n";
355 Preamble += " char *str;\n";
356 Preamble += " long length;\n";
357 Preamble += "};\n";
358 Preamble += "extern int __CFConstantStringClassReference[];\n";
359 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
360 Preamble += "#endif\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000361 if (LangOpts.Microsoft)
Steve Narofffef037c2008-03-27 22:29:16 +0000362 Preamble += "#define __attribute__(X)\n";
Chris Lattner12499682008-01-31 19:38:44 +0000363}
364
365
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000366//===----------------------------------------------------------------------===//
367// Top Level Driver Code
368//===----------------------------------------------------------------------===//
369
Chris Lattner569faa62007-10-11 18:38:32 +0000370void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000371 // Two cases: either the decl could be in the main file, or it could be in a
372 // #included file. If the former, rewrite it now. If the later, check to see
373 // if we rewrote the #include/#import.
374 SourceLocation Loc = D->getLocation();
375 Loc = SM->getLogicalLoc(Loc);
376
377 // If this is for a builtin, ignore it.
378 if (Loc.isInvalid()) return;
379
Steve Naroffe9780582007-10-23 23:50:29 +0000380 // Look for built-in declarations that we need to refer during the rewrite.
381 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000382 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000383 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
384 // declared in <Foundation/NSString.h>
385 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
386 ConstantStringClassReference = FVD;
387 return;
388 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000389 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000390 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000391 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000392 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000393 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000394 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000395 } else if (ObjCForwardProtocolDecl *FP =
396 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000397 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000398 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000399 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000400 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
401 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000402}
403
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000404/// HandleDeclInMainFile - This is called for each top-level decl defined in the
405/// main file of the input.
406void RewriteTest::HandleDeclInMainFile(Decl *D) {
407 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
408 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000409 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000410
Ted Kremenek42730c52008-01-07 19:49:32 +0000411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000412 if (Stmt *Body = MD->getBody()) {
413 //Body->dump();
414 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000415 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000416 CurMethodDecl = 0;
417 }
Steve Naroff18c83382007-11-13 23:01:27 +0000418 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000419 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000420 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000421 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000422 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000423 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000424 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000425 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000426 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000427 if (VD->getInit())
428 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
429 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 // Nothing yet.
431}
432
433RewriteTest::~RewriteTest() {
434 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000435
436 // Rewrite tabs if we care.
437 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000438
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000439 RewriteInclude();
440
Steve Narofffef037c2008-03-27 22:29:16 +0000441 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
442 Preamble.c_str(), Preamble.size(), false);
443
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000444 // Rewrite Objective-c meta data*
445 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000446 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000447
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000448 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
449 // we are done.
450 if (const RewriteBuffer *RewriteBuf =
451 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000452 //printf("Changed:\n");
Chris Lattner673f2bd2008-03-22 00:08:40 +0000453 OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000454 } else {
Chris Lattner673f2bd2008-03-22 00:08:40 +0000455 fprintf(stderr, "No changes\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000456 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000457 // Emit metadata.
Chris Lattner673f2bd2008-03-22 00:08:40 +0000458 OutFile << ResultStr;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000459}
460
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000461//===----------------------------------------------------------------------===//
462// Syntactic (non-AST) Rewriting Code
463//===----------------------------------------------------------------------===//
464
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000465void RewriteTest::RewriteInclude() {
466 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
467 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
468 const char *MainBufStart = MainBuf.first;
469 const char *MainBufEnd = MainBuf.second;
470 size_t ImportLen = strlen("import");
471 size_t IncludeLen = strlen("include");
472
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000473 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000474 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
475 if (*BufPtr == '#') {
476 if (++BufPtr == MainBufEnd)
477 return;
478 while (*BufPtr == ' ' || *BufPtr == '\t')
479 if (++BufPtr == MainBufEnd)
480 return;
481 if (!strncmp(BufPtr, "import", ImportLen)) {
482 // replace import with include
483 SourceLocation ImportLoc =
484 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000485 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000486 BufPtr += ImportLen;
487 }
488 }
489 }
Chris Lattner74db1682007-10-16 21:07:07 +0000490}
491
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000492void RewriteTest::RewriteTabs() {
493 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
494 const char *MainBufStart = MainBuf.first;
495 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000496
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000497 // Loop over the whole file, looking for tabs.
498 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
499 if (*BufPtr != '\t')
500 continue;
501
502 // Okay, we found a tab. This tab will turn into at least one character,
503 // but it depends on which 'virtual column' it is in. Compute that now.
504 unsigned VCol = 0;
505 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
506 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
507 ++VCol;
508
509 // Okay, now that we know the virtual column, we know how many spaces to
510 // insert. We assume 8-character tab-stops.
511 unsigned Spaces = 8-(VCol & 7);
512
513 // Get the location of the tab.
514 SourceLocation TabLoc =
515 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
516
517 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000518 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000519 }
Chris Lattner569faa62007-10-11 18:38:32 +0000520}
521
522
Ted Kremenek42730c52008-01-07 19:49:32 +0000523void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000524 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000525 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000526
527 // Get the start location and compute the semi location.
528 SourceLocation startLoc = ClassDecl->getLocation();
529 const char *startBuf = SM->getCharacterData(startLoc);
530 const char *semiPtr = strchr(startBuf, ';');
531
532 // Translate to typedef's that forward reference structs with the same name
533 // as the class. As a convenience, we include the original declaration
534 // as a comment.
535 std::string typedefString;
536 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000537 typedefString.append(startBuf, semiPtr-startBuf+1);
538 typedefString += "\n";
539 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000540 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000541 typedefString += "#ifndef _REWRITER_typedef_";
542 typedefString += ForwardDecl->getName();
543 typedefString += "\n";
544 typedefString += "#define _REWRITER_typedef_";
545 typedefString += ForwardDecl->getName();
546 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000547 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000548 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000549 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000550 }
551
552 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000553 ReplaceText(startLoc, semiPtr-startBuf+1,
554 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000555}
556
Ted Kremenek42730c52008-01-07 19:49:32 +0000557void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000558 SourceLocation LocStart = Method->getLocStart();
559 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000560
Steve Naroff2ce399a2007-12-14 23:37:57 +0000561 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000562 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000563 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000564 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000565 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000566 }
567}
568
Chris Lattnercffe3662008-03-16 21:23:50 +0000569void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000570{
Chris Lattnercffe3662008-03-16 21:23:50 +0000571 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000572 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000573 SourceLocation Loc = Property->getLocation();
574
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000575 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000576
577 // FIXME: handle properties that are declared across multiple lines.
578 }
579}
580
Ted Kremenek42730c52008-01-07 19:49:32 +0000581void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000582 SourceLocation LocStart = CatDecl->getLocStart();
583
584 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000585 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000586
Ted Kremenek42730c52008-01-07 19:49:32 +0000587 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000588 E = CatDecl->instmeth_end(); I != E; ++I)
589 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000590 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000591 E = CatDecl->classmeth_end(); I != E; ++I)
592 RewriteMethodDeclaration(*I);
593
Steve Naroff667f1682007-10-30 13:30:57 +0000594 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000595 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000596}
597
Ted Kremenek42730c52008-01-07 19:49:32 +0000598void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000599 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000600
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000601 SourceLocation LocStart = PDecl->getLocStart();
602
603 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000604 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000605
Ted Kremenek42730c52008-01-07 19:49:32 +0000606 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000607 E = PDecl->instmeth_end(); I != E; ++I)
608 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000609 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000610 E = PDecl->classmeth_end(); I != E; ++I)
611 RewriteMethodDeclaration(*I);
612
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000613 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000614 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000615 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000616
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000617 // Must comment out @optional/@required
618 const char *startBuf = SM->getCharacterData(LocStart);
619 const char *endBuf = SM->getCharacterData(LocEnd);
620 for (const char *p = startBuf; p < endBuf; p++) {
621 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
622 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000623 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000624 ReplaceText(OptionalLoc, strlen("@optional"),
625 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000626
627 }
628 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
629 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000630 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000631 ReplaceText(OptionalLoc, strlen("@required"),
632 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000633
634 }
635 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000636}
637
Ted Kremenek42730c52008-01-07 19:49:32 +0000638void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000639 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000640 if (LocStart.isInvalid())
641 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000642 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000643 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000644}
645
Ted Kremenek42730c52008-01-07 19:49:32 +0000646void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000647 std::string &ResultStr) {
648 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000649 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000650 ResultStr += "id";
651 else
652 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000653 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000654
655 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000656 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000657
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000658 if (OMD->isInstance())
659 NameStr += "_I_";
660 else
661 NameStr += "_C_";
662
663 NameStr += OMD->getClassInterface()->getName();
664 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000665
666 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000667 if (ObjCCategoryImplDecl *CID =
668 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000669 NameStr += CID->getName();
670 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000671 }
672 // Append selector names, replacing ':' with '_'
673 const char *selName = OMD->getSelector().getName().c_str();
674 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000675 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000676 else {
677 std::string selString = OMD->getSelector().getName();
678 int len = selString.size();
679 for (int i = 0; i < len; i++)
680 if (selString[i] == ':')
681 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000682 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000683 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000684 // Remember this name for metadata emission
685 MethodInternalNames[OMD] = NameStr;
686 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000687
688 // Rewrite arguments
689 ResultStr += "(";
690
691 // invisible arguments
692 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000693 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000694 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000695 if (!LangOpts.Microsoft) {
696 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
697 ResultStr += "struct ";
698 }
699 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000700 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000701 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000702 }
703 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000704 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000705
706 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000708 ResultStr += " _cmd";
709
710 // Method arguments.
Chris Lattner685d7922008-03-16 01:07:14 +0000711 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000712 ParmVarDecl *PDecl = OMD->getParamDecl(i);
713 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000714 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000715 ResultStr += "id";
716 else
717 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000718 ResultStr += " ";
719 ResultStr += PDecl->getName();
720 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000721 if (OMD->isVariadic())
722 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000723 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724
725}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000726void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000727 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
728 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000729
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000730 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000731 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000732 else
Chris Lattner6216f292008-01-31 19:42:41 +0000733 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000734
Ted Kremenek42730c52008-01-07 19:49:32 +0000735 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000736 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
737 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000738 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000739 ObjCMethodDecl *OMD = *I;
740 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000741 SourceLocation LocStart = OMD->getLocStart();
742 SourceLocation LocEnd = OMD->getBody()->getLocStart();
743
744 const char *startBuf = SM->getCharacterData(LocStart);
745 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000746 ReplaceText(LocStart, endBuf-startBuf,
747 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000748 }
749
Ted Kremenek42730c52008-01-07 19:49:32 +0000750 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000751 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
752 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000753 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000754 ObjCMethodDecl *OMD = *I;
755 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000756 SourceLocation LocStart = OMD->getLocStart();
757 SourceLocation LocEnd = OMD->getBody()->getLocStart();
758
759 const char *startBuf = SM->getCharacterData(LocStart);
760 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000761 ReplaceText(LocStart, endBuf-startBuf,
762 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000763 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000764 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000765 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000766 else
Chris Lattner6216f292008-01-31 19:42:41 +0000767 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000768}
769
Ted Kremenek42730c52008-01-07 19:49:32 +0000770void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000771 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000772 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000773 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000774 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000775 ResultStr += ClassDecl->getName();
776 ResultStr += "\n";
777 ResultStr += "#define _REWRITER_typedef_";
778 ResultStr += ClassDecl->getName();
779 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000780 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000781 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000782 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000783 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000784 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000785 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000786 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000787
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000788 RewriteProperties(ClassDecl->getNumPropertyDecl(),
789 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000790 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000791 E = ClassDecl->instmeth_end(); I != E; ++I)
792 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000793 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000794 E = ClassDecl->classmeth_end(); I != E; ++I)
795 RewriteMethodDeclaration(*I);
796
Steve Naroff1ccf4632007-10-30 03:43:13 +0000797 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000798 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000799}
800
Steve Naroff6b759ce2007-11-15 02:58:25 +0000801Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000802 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000803 if (CurMethodDecl) {
804 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
805 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
806 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000807 // lookup which class implements the instance variable.
808 ObjCInterfaceDecl *clsDeclared = 0;
809 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
810 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5d933112008-03-12 23:15:19 +0000811
812 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000813 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000814 RecName += "_IMPL";
815 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattner58114f02008-03-15 21:32:50 +0000816 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct,
817 SourceLocation(), II, 0);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000818 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
819 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
820 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
821 // Don't forget the parens to enforce the proper binding.
822 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
823 if (IV->isFreeIvar()) {
824 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
825 ReplaceStmt(IV, ME);
826 delete IV;
827 return ME;
828 } else {
Chris Lattnerb1548372008-01-31 19:37:57 +0000829 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5d933112008-03-12 23:15:19 +0000830 // Cannot delete IV->getBase(), since PE points to it.
831 // Replace the old base with the cast. This is important when doing
832 // embedded rewrites. For example, [newInv->_container addObject:0].
833 IV->setBase(PE);
834 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000835 }
836 }
837 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000838 }
Steve Naroff5d933112008-03-12 23:15:19 +0000839 // FIXME: Implement public ivar access from a function.
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000840 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
841 IV->getLocation(), D->getType());
842 ReplaceStmt(IV, Replacement);
843 delete IV;
844 return Replacement;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000845}
846
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000847//===----------------------------------------------------------------------===//
848// Function Body / Expression rewriting
849//===----------------------------------------------------------------------===//
850
Steve Naroff334fbc22007-11-09 15:20:18 +0000851Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000852 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
853 isa<DoStmt>(S) || isa<ForStmt>(S))
854 Stmts.push_back(S);
855 else if (isa<ObjCForCollectionStmt>(S)) {
856 Stmts.push_back(S);
857 ObjCBcLabelNo.push_back(++BcLabelCount);
858 }
859
Chris Lattner2c022162008-01-31 05:10:40 +0000860 SourceLocation OrigStmtEnd = S->getLocEnd();
861
862 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000863 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
864 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000865 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000866 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000867 if (newStmt)
868 *CI = newStmt;
869 }
Steve Naroffe9780582007-10-23 23:50:29 +0000870
871 // Handle specific things.
872 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
873 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000874
875 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
876 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000877
878 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
879 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000880
Steve Naroff0add5d22007-11-03 11:27:19 +0000881 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
882 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000883
Steve Naroff71226032007-10-24 22:48:43 +0000884 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
885 // Before we rewrite it, put the original message expression in a comment.
886 SourceLocation startLoc = MessExpr->getLocStart();
887 SourceLocation endLoc = MessExpr->getLocEnd();
888
889 const char *startBuf = SM->getCharacterData(startLoc);
890 const char *endBuf = SM->getCharacterData(endLoc);
891
892 std::string messString;
893 messString += "// ";
894 messString.append(startBuf, endBuf-startBuf+1);
895 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000896
Chris Lattner6216f292008-01-31 19:42:41 +0000897 // FIXME: Missing definition of
898 // InsertText(clang::SourceLocation, char const*, unsigned int).
899 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000900 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000901 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000902 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000903 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000904
Ted Kremenek42730c52008-01-07 19:49:32 +0000905 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
906 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000907
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000908 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
909 return RewriteObjCSynchronizedStmt(StmtTry);
910
Ted Kremenek42730c52008-01-07 19:49:32 +0000911 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
912 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000913
914 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
915 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000916
917 if (ObjCForCollectionStmt *StmtForCollection =
918 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000919 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000920 if (BreakStmt *StmtBreakStmt =
921 dyn_cast<BreakStmt>(S))
922 return RewriteBreakStmt(StmtBreakStmt);
923 if (ContinueStmt *StmtContinueStmt =
924 dyn_cast<ContinueStmt>(S))
925 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000926
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000927 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
928 isa<DoStmt>(S) || isa<ForStmt>(S)) {
929 assert(!Stmts.empty() && "Statement stack is empty");
930 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
931 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
932 && "Statement stack mismatch");
933 Stmts.pop_back();
934 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000935#if 0
936 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
937 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
938 // Get the new text.
939 std::ostringstream Buf;
940 Replacement->printPretty(Buf);
941 const std::string &Str = Buf.str();
942
943 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000944 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000945 delete S;
946 return Replacement;
947 }
948#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000949 // Return this stmt unmodified.
950 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000951}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000952
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000953/// SynthCountByEnumWithState - To print:
954/// ((unsigned int (*)
955/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
956/// (void *)objc_msgSend)((id)l_collection,
957/// sel_registerName(
958/// "countByEnumeratingWithState:objects:count:"),
959/// &enumState,
960/// (id *)items, (unsigned int)16)
961///
962void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
963 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
964 "id *, unsigned int))(void *)objc_msgSend)";
965 buf += "\n\t\t";
966 buf += "((id)l_collection,\n\t\t";
967 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
968 buf += "\n\t\t";
969 buf += "&enumState, "
970 "(id *)items, (unsigned int)16)";
971}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000972
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000973/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
974/// statement to exit to its outer synthesized loop.
975///
976Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
977 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
978 return S;
979 // replace break with goto __break_label
980 std::string buf;
981
982 SourceLocation startLoc = S->getLocStart();
983 buf = "goto __break_label_";
984 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000985 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000986
987 return 0;
988}
989
990/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
991/// statement to continue with its inner synthesized loop.
992///
993Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
994 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
995 return S;
996 // replace continue with goto __continue_label
997 std::string buf;
998
999 SourceLocation startLoc = S->getLocStart();
1000 buf = "goto __continue_label_";
1001 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001002 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001003
1004 return 0;
1005}
1006
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001007/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001008/// It rewrites:
1009/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001010
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001011/// Into:
1012/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001013/// type elem;
1014/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001015/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001016/// id l_collection = (id)collection;
1017/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1018/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001019/// if (limit) {
1020/// unsigned long startMutations = *enumState.mutationsPtr;
1021/// do {
1022/// unsigned long counter = 0;
1023/// do {
1024/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001025/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001026/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001027/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001028/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001029/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001030/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1031/// objects:items count:16]);
1032/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001033/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001034/// }
1035/// else
1036/// elem = nil;
1037/// }
1038///
Chris Lattner2c022162008-01-31 05:10:40 +00001039Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1040 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001041 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1042 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1043 "ObjCForCollectionStmt Statement stack mismatch");
1044 assert(!ObjCBcLabelNo.empty() &&
1045 "ObjCForCollectionStmt - Label No stack empty");
1046
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001047 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001048 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001049 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001050 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001051 std::string buf;
1052 buf = "\n{\n\t";
1053 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1054 // type elem;
1055 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001056 elementTypeAsString = ElementType.getAsString();
1057 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001058 buf += " ";
1059 elementName = DS->getDecl()->getName();
1060 buf += elementName;
1061 buf += ";\n\t";
1062 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001063 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001064 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001065 elementTypeAsString = DR->getDecl()->getType().getAsString();
1066 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001067 else
1068 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1069
1070 // struct __objcFastEnumerationState enumState = { 0 };
1071 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1072 // id items[16];
1073 buf += "id items[16];\n\t";
1074 // id l_collection = (id)
1075 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001076 // Find start location of 'collection' the hard way!
1077 const char *startCollectionBuf = startBuf;
1078 startCollectionBuf += 3; // skip 'for'
1079 startCollectionBuf = strchr(startCollectionBuf, '(');
1080 startCollectionBuf++; // skip '('
1081 // find 'in' and skip it.
1082 while (*startCollectionBuf != ' ' ||
1083 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1084 (*(startCollectionBuf+3) != ' ' &&
1085 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1086 startCollectionBuf++;
1087 startCollectionBuf += 3;
1088
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001089 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001090 ReplaceText(startLoc, startCollectionBuf - startBuf,
1091 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001092 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001093 SourceLocation rightParenLoc = S->getRParenLoc();
1094 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1095 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001096 buf = ";\n\t";
1097
1098 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1099 // objects:items count:16];
1100 // which is synthesized into:
1101 // unsigned int limit =
1102 // ((unsigned int (*)
1103 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1104 // (void *)objc_msgSend)((id)l_collection,
1105 // sel_registerName(
1106 // "countByEnumeratingWithState:objects:count:"),
1107 // (struct __objcFastEnumerationState *)&state,
1108 // (id *)items, (unsigned int)16);
1109 buf += "unsigned long limit =\n\t\t";
1110 SynthCountByEnumWithState(buf);
1111 buf += ";\n\t";
1112 /// if (limit) {
1113 /// unsigned long startMutations = *enumState.mutationsPtr;
1114 /// do {
1115 /// unsigned long counter = 0;
1116 /// do {
1117 /// if (startMutations != *enumState.mutationsPtr)
1118 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001119 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001120 buf += "if (limit) {\n\t";
1121 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1122 buf += "do {\n\t\t";
1123 buf += "unsigned long counter = 0;\n\t\t";
1124 buf += "do {\n\t\t\t";
1125 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1126 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1127 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001128 buf += " = (";
1129 buf += elementTypeAsString;
1130 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001131 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001132 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001133
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001134 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001135 /// } while (counter < limit);
1136 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1137 /// objects:items count:16]);
1138 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001139 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001140 /// }
1141 /// else
1142 /// elem = nil;
1143 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001144 ///
1145 buf = ";\n\t";
1146 buf += "__continue_label_";
1147 buf += utostr(ObjCBcLabelNo.back());
1148 buf += ": ;";
1149 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001150 buf += "} while (counter < limit);\n\t";
1151 buf += "} while (limit = ";
1152 SynthCountByEnumWithState(buf);
1153 buf += ");\n\t";
1154 buf += elementName;
1155 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001156 buf += "__break_label_";
1157 buf += utostr(ObjCBcLabelNo.back());
1158 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001159 buf += "}\n\t";
1160 buf += "else\n\t\t";
1161 buf += elementName;
1162 buf += " = nil;\n";
1163 buf += "}\n";
1164 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001165 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001166 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001167 Stmts.pop_back();
1168 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001169 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001170}
1171
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001172/// RewriteObjCSynchronizedStmt -
1173/// This routine rewrites @synchronized(expr) stmt;
1174/// into:
1175/// objc_sync_enter(expr);
1176/// @try stmt @finally { objc_sync_exit(expr); }
1177///
1178Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1179 // Get the start location and compute the semi location.
1180 SourceLocation startLoc = S->getLocStart();
1181 const char *startBuf = SM->getCharacterData(startLoc);
1182
1183 assert((*startBuf == '@') && "bogus @synchronized location");
1184
1185 std::string buf;
1186 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001187 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001188 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1189 const char *endBuf = SM->getCharacterData(endLoc);
1190 endBuf++;
1191 const char *rparenBuf = strchr(endBuf, ')');
1192 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1193 buf = ");\n";
1194 // declare a new scope with two variables, _stack and _rethrow.
1195 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1196 buf += "int buf[18/*32-bit i386*/];\n";
1197 buf += "char *pointers[4];} _stack;\n";
1198 buf += "id volatile _rethrow = 0;\n";
1199 buf += "objc_exception_try_enter(&_stack);\n";
1200 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001201 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001202 startLoc = S->getSynchBody()->getLocEnd();
1203 startBuf = SM->getCharacterData(startLoc);
1204
1205 assert((*startBuf == '}') && "bogus @try block");
1206 SourceLocation lastCurlyLoc = startLoc;
1207 buf = "}\nelse {\n";
1208 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1209 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1210 // FIXME: This must be objc_sync_exit(syncExpr);
1211 buf += " objc_sync_exit();\n";
1212 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1213 buf += "}\n";
1214 buf += "}";
1215
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001216 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001217 return 0;
1218}
1219
Ted Kremenek42730c52008-01-07 19:49:32 +00001220Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001221 // Get the start location and compute the semi location.
1222 SourceLocation startLoc = S->getLocStart();
1223 const char *startBuf = SM->getCharacterData(startLoc);
1224
1225 assert((*startBuf == '@') && "bogus @try location");
1226
1227 std::string buf;
1228 // declare a new scope with two variables, _stack and _rethrow.
1229 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1230 buf += "int buf[18/*32-bit i386*/];\n";
1231 buf += "char *pointers[4];} _stack;\n";
1232 buf += "id volatile _rethrow = 0;\n";
1233 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001234 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001235
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001236 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001237
1238 startLoc = S->getTryBody()->getLocEnd();
1239 startBuf = SM->getCharacterData(startLoc);
1240
1241 assert((*startBuf == '}') && "bogus @try block");
1242
1243 SourceLocation lastCurlyLoc = startLoc;
1244
1245 startLoc = startLoc.getFileLocWithOffset(1);
1246 buf = " /* @catch begin */ else {\n";
1247 buf += " id _caught = objc_exception_extract(&_stack);\n";
1248 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001249 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001250 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1251 buf += " else { /* @catch continue */";
1252
Chris Lattner6216f292008-01-31 19:42:41 +00001253 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001254
1255 bool sawIdTypedCatch = false;
1256 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001257 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001258 while (catchList) {
1259 Stmt *catchStmt = catchList->getCatchParamStmt();
1260
1261 if (catchList == S->getCatchStmts())
1262 buf = "if ("; // we are generating code for the first catch clause
1263 else
1264 buf = "else if (";
1265 startLoc = catchList->getLocStart();
1266 startBuf = SM->getCharacterData(startLoc);
1267
1268 assert((*startBuf == '@') && "bogus @catch location");
1269
1270 const char *lParenLoc = strchr(startBuf, '(');
1271
Steve Naroff397c4ce2008-02-01 22:08:12 +00001272 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001273 // Now rewrite the body...
1274 lastCatchBody = catchList->getCatchBody();
1275 SourceLocation rParenLoc = catchList->getRParenLoc();
1276 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1277 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1278 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1279 assert((*rParenBuf == ')') && "bogus @catch paren location");
1280 assert((*bodyBuf == '{') && "bogus @catch body location");
1281
1282 buf += "1) { id _tmp = _caught;";
1283 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1284 buf.c_str(), buf.size());
1285 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001286 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001287 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001288 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001289 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001290 sawIdTypedCatch = true;
1291 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001292 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001293
Ted Kremenek42730c52008-01-07 19:49:32 +00001294 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001295 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001296 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001297 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001298 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001299 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001300 }
1301 }
1302 // Now rewrite the body...
1303 lastCatchBody = catchList->getCatchBody();
1304 SourceLocation rParenLoc = catchList->getRParenLoc();
1305 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1306 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1307 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1308 assert((*rParenBuf == ')') && "bogus @catch paren location");
1309 assert((*bodyBuf == '{') && "bogus @catch body location");
1310
1311 buf = " = _caught;";
1312 // Here we replace ") {" with "= _caught;" (which initializes and
1313 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001314 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001315 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001316 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001317 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001318 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001319 catchList = catchList->getNextCatchStmt();
1320 }
1321 // Complete the catch list...
1322 if (lastCatchBody) {
1323 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1324 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1325 assert((*bodyBuf == '}') && "bogus @catch body location");
1326 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1327 buf = " } } /* @catch end */\n";
1328
Chris Lattner6216f292008-01-31 19:42:41 +00001329 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001330
1331 // Set lastCurlyLoc
1332 lastCurlyLoc = lastCatchBody->getLocEnd();
1333 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001334 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001335 startLoc = finalStmt->getLocStart();
1336 startBuf = SM->getCharacterData(startLoc);
1337 assert((*startBuf == '@') && "bogus @finally start");
1338
1339 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001340 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001341
1342 Stmt *body = finalStmt->getFinallyBody();
1343 SourceLocation startLoc = body->getLocStart();
1344 SourceLocation endLoc = body->getLocEnd();
1345 const char *startBuf = SM->getCharacterData(startLoc);
1346 const char *endBuf = SM->getCharacterData(endLoc);
1347 assert((*startBuf == '{') && "bogus @finally body location");
1348 assert((*endBuf == '}') && "bogus @finally body location");
1349
1350 startLoc = startLoc.getFileLocWithOffset(1);
1351 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001352 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001353 endLoc = endLoc.getFileLocWithOffset(-1);
1354 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001355 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001356
1357 // Set lastCurlyLoc
1358 lastCurlyLoc = body->getLocEnd();
1359 }
1360 // Now emit the final closing curly brace...
1361 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1362 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001363 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001364 return 0;
1365}
1366
Ted Kremenek42730c52008-01-07 19:49:32 +00001367Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001368 return 0;
1369}
1370
Ted Kremenek42730c52008-01-07 19:49:32 +00001371Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001372 return 0;
1373}
1374
Chris Lattnerb1548372008-01-31 19:37:57 +00001375// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001376// the throw expression is typically a message expression that's already
1377// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001378Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001379 // Get the start location and compute the semi location.
1380 SourceLocation startLoc = S->getLocStart();
1381 const char *startBuf = SM->getCharacterData(startLoc);
1382
1383 assert((*startBuf == '@') && "bogus @throw location");
1384
1385 std::string buf;
1386 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001387 if (S->getThrowExpr())
1388 buf = "objc_exception_throw(";
1389 else // add an implicit argument
1390 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001391 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001392 const char *semiBuf = strchr(startBuf, ';');
1393 assert((*semiBuf == ';') && "@throw: can't find ';'");
1394 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1395 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001396 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001397 return 0;
1398}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001399
Chris Lattner0021f452007-10-24 16:57:36 +00001400Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001401 // Create a new string expression.
1402 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001403 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001404 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1405 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001406 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1407 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001408 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001409 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001410
Chris Lattner4478db92007-11-30 22:53:43 +00001411 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001412 delete Exp;
1413 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001414}
1415
Steve Naroff296b74f2007-11-05 14:50:49 +00001416Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1417 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1418 // Create a call to sel_registerName("selName").
1419 llvm::SmallVector<Expr*, 8> SelExprs;
1420 QualType argType = Context->getPointerType(Context->CharTy);
1421 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1422 Exp->getSelector().getName().size(),
1423 false, argType, SourceLocation(),
1424 SourceLocation()));
1425 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1426 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001427 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001428 delete Exp;
1429 return SelExp;
1430}
1431
Steve Naroff71226032007-10-24 22:48:43 +00001432CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1433 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001434 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001435 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001436
1437 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001438 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001439
1440 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001441 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001442 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1443
1444 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001445
Steve Naroff71226032007-10-24 22:48:43 +00001446 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1447}
1448
Steve Naroffc8a92d12007-11-01 13:24:47 +00001449static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1450 const char *&startRef, const char *&endRef) {
1451 while (startBuf < endBuf) {
1452 if (*startBuf == '<')
1453 startRef = startBuf; // mark the start.
1454 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001455 if (startRef && *startRef == '<') {
1456 endRef = startBuf; // mark the end.
1457 return true;
1458 }
1459 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001460 }
1461 startBuf++;
1462 }
1463 return false;
1464}
1465
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001466static void scanToNextArgument(const char *&argRef) {
1467 int angle = 0;
1468 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1469 if (*argRef == '<')
1470 angle++;
1471 else if (*argRef == '>')
1472 angle--;
1473 argRef++;
1474 }
1475 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1476}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001477
Steve Naroffc8a92d12007-11-01 13:24:47 +00001478bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001479
Ted Kremenek42730c52008-01-07 19:49:32 +00001480 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001481 return true;
1482
Ted Kremenek42730c52008-01-07 19:49:32 +00001483 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001484 return true;
1485
Steve Naroffc8a92d12007-11-01 13:24:47 +00001486 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001487 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001488 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001489 return true; // we have "Class <Protocol> *".
1490 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001491 return false;
1492}
1493
Ted Kremenek42730c52008-01-07 19:49:32 +00001494void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001495 SourceLocation Loc;
1496 QualType Type;
1497 const FunctionTypeProto *proto = 0;
1498 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1499 Loc = VD->getLocation();
1500 Type = VD->getType();
1501 }
1502 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1503 Loc = FD->getLocation();
1504 // Check for ObjC 'id' and class types that have been adorned with protocol
1505 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1506 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1507 assert(funcType && "missing function type");
1508 proto = dyn_cast<FunctionTypeProto>(funcType);
1509 if (!proto)
1510 return;
1511 Type = proto->getResultType();
1512 }
1513 else
1514 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001515
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001516 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001517 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001518
1519 const char *endBuf = SM->getCharacterData(Loc);
1520 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001521 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001522 startBuf--; // scan backward (from the decl location) for return type.
1523 const char *startRef = 0, *endRef = 0;
1524 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1525 // Get the locations of the startRef, endRef.
1526 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1527 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1528 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001529 InsertText(LessLoc, "/*", 2);
1530 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001531 }
1532 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001533 if (!proto)
1534 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001535 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001536 const char *startBuf = SM->getCharacterData(Loc);
1537 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001538 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1539 if (needToScanForQualifiers(proto->getArgType(i))) {
1540 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001541
Steve Naroffc8a92d12007-11-01 13:24:47 +00001542 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001543 // scan forward (from the decl location) for argument types.
1544 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001545 const char *startRef = 0, *endRef = 0;
1546 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1547 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001548 SourceLocation LessLoc =
1549 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1550 SourceLocation GreaterLoc =
1551 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001552 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001553 InsertText(LessLoc, "/*", 2);
1554 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001555 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001556 startBuf = ++endBuf;
1557 }
1558 else {
1559 while (*startBuf != ')' && *startBuf != ',')
1560 startBuf++; // scan forward (from the decl location) for argument types.
1561 startBuf++;
1562 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001563 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001564}
1565
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001566// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1567void RewriteTest::SynthSelGetUidFunctionDecl() {
1568 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1569 llvm::SmallVector<QualType, 16> ArgTys;
1570 ArgTys.push_back(Context->getPointerType(
1571 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001572 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001573 &ArgTys[0], ArgTys.size(),
1574 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001575 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001576 SelGetUidIdent, getFuncType,
1577 FunctionDecl::Extern, false, 0);
1578}
1579
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001580// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1581void RewriteTest::SynthGetProtocolFunctionDecl() {
1582 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1583 llvm::SmallVector<QualType, 16> ArgTys;
1584 ArgTys.push_back(Context->getPointerType(
1585 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001586 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001587 &ArgTys[0], ArgTys.size(),
1588 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001589 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001590 SelGetProtoIdent, getFuncType,
1591 FunctionDecl::Extern, false, 0);
1592}
1593
Steve Naroff02a82aa2007-10-30 23:14:51 +00001594void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1595 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001596 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001597 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001598 return;
1599 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001600 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001601}
1602
Steve Naroffbec4bf52008-03-11 17:37:02 +00001603// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1604void RewriteTest::SynthSuperContructorFunctionDecl() {
1605 if (SuperContructorFunctionDecl)
1606 return;
1607 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1608 llvm::SmallVector<QualType, 16> ArgTys;
1609 QualType argT = Context->getObjCIdType();
1610 assert(!argT.isNull() && "Can't find 'id' type");
1611 ArgTys.push_back(argT);
1612 ArgTys.push_back(argT);
1613 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1614 &ArgTys[0], ArgTys.size(),
1615 false);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001616 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001617 msgSendIdent, msgSendType,
1618 FunctionDecl::Extern, false, 0);
1619}
1620
Steve Naroff02a82aa2007-10-30 23:14:51 +00001621// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1622void RewriteTest::SynthMsgSendFunctionDecl() {
1623 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1624 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001625 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001626 assert(!argT.isNull() && "Can't find 'id' type");
1627 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001628 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001629 assert(!argT.isNull() && "Can't find 'SEL' type");
1630 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001631 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001632 &ArgTys[0], ArgTys.size(),
1633 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001634 MsgSendFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001635 msgSendIdent, msgSendType,
1636 FunctionDecl::Extern, false, 0);
1637}
1638
Steve Naroff764c1ae2007-11-15 10:28:18 +00001639// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1640void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1641 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1642 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner58114f02008-03-15 21:32:50 +00001643 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1644 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001645 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1646 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1647 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001648 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +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(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001652 &ArgTys[0], ArgTys.size(),
1653 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001654 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001655 msgSendIdent, msgSendType,
1656 FunctionDecl::Extern, false, 0);
1657}
1658
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001659// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1660void RewriteTest::SynthMsgSendStretFunctionDecl() {
1661 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1662 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001663 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001664 assert(!argT.isNull() && "Can't find 'id' type");
1665 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001666 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001667 assert(!argT.isNull() && "Can't find 'SEL' type");
1668 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001669 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001670 &ArgTys[0], ArgTys.size(),
1671 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001672 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001673 msgSendIdent, msgSendType,
1674 FunctionDecl::Extern, false, 0);
1675}
1676
1677// SynthMsgSendSuperStretFunctionDecl -
1678// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1679void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1680 IdentifierInfo *msgSendIdent =
1681 &Context->Idents.get("objc_msgSendSuper_stret");
1682 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner58114f02008-03-15 21:32:50 +00001683 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1684 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001685 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1686 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1687 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001688 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +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 Jahanianc26b2502007-12-03 19:17:29 +00001692 &ArgTys[0], ArgTys.size(),
1693 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001694 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context,
1695 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001696 msgSendIdent, msgSendType,
1697 FunctionDecl::Extern, false, 0);
1698}
1699
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001700// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1701void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1702 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1703 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001704 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001705 assert(!argT.isNull() && "Can't find 'id' type");
1706 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001707 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001708 assert(!argT.isNull() && "Can't find 'SEL' type");
1709 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001710 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001711 &ArgTys[0], ArgTys.size(),
1712 true /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001713 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001714 msgSendIdent, msgSendType,
1715 FunctionDecl::Extern, false, 0);
1716}
1717
Steve Naroff02a82aa2007-10-30 23:14:51 +00001718// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1719void RewriteTest::SynthGetClassFunctionDecl() {
1720 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1721 llvm::SmallVector<QualType, 16> ArgTys;
1722 ArgTys.push_back(Context->getPointerType(
1723 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001724 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001725 &ArgTys[0], ArgTys.size(),
1726 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001727 GetClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001728 getClassIdent, getClassType,
1729 FunctionDecl::Extern, false, 0);
1730}
1731
Steve Naroff3b1caac2007-12-07 03:50:46 +00001732// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1733void RewriteTest::SynthGetMetaClassFunctionDecl() {
1734 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1735 llvm::SmallVector<QualType, 16> ArgTys;
1736 ArgTys.push_back(Context->getPointerType(
1737 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001738 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001739 &ArgTys[0], ArgTys.size(),
1740 false /*isVariadic*/);
Chris Lattner4c7802b2008-03-15 21:24:04 +00001741 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001742 getClassIdent, getClassType,
1743 FunctionDecl::Extern, false, 0);
1744}
1745
Steve Naroff0add5d22007-11-03 11:27:19 +00001746Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001747 QualType strType = getConstantStringStructType();
1748
1749 std::string S = "__NSConstantStringImpl_";
1750 S += utostr(NumObjCStringLiterals++);
1751
Steve Narofffef037c2008-03-27 22:29:16 +00001752 Preamble += "static __NSConstantStringImpl " + S;
1753 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1754 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00001755 // The pretty printer for StringLiteral handles escape characters properly.
1756 std::ostringstream prettyBuf;
1757 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00001758 Preamble += prettyBuf.str();
1759 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00001760 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00001761 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00001762
Chris Lattner58114f02008-03-15 21:32:50 +00001763 FileVarDecl *NewVD = FileVarDecl::Create(*Context, SourceLocation(),
Steve Naroff47e7fa22008-03-15 00:55:56 +00001764 &Context->Idents.get(S.c_str()), strType,
Chris Lattner58114f02008-03-15 21:32:50 +00001765 VarDecl::Static, NULL);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001766 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1767 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1768 Context->getPointerType(DRE->getType()),
1769 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001770 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001771 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001772 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001773 delete Exp;
1774 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001775}
1776
Ted Kremenek42730c52008-01-07 19:49:32 +00001777ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001778 // check if we are sending a message to 'super'
Chris Lattnere4650482008-03-15 06:12:44 +00001779 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1780
1781 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1782 if (!CE) return 0;
1783
1784 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1785 if (!DRE) return 0;
1786
1787 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1788 if (!PVD) return 0;
1789
1790 if (strcmp(PVD->getName(), "self") != 0)
1791 return 0;
1792
1793 // is this id<P1..> type?
1794 if (CE->getType()->isObjCQualifiedIdType())
1795 return 0;
1796 const PointerType *PT = CE->getType()->getAsPointerType();
1797 if (!PT) return 0;
1798
1799 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1800 if (!IT) return 0;
1801
1802 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1803 return 0;
1804
1805 return IT->getDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001806}
1807
1808// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1809QualType RewriteTest::getSuperStructType() {
1810 if (!SuperStructDecl) {
Chris Lattner58114f02008-03-15 21:32:50 +00001811 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct,
1812 SourceLocation(),
1813 &Context->Idents.get("objc_super"), 0);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001814 QualType FieldTypes[2];
1815
1816 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001817 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001818 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001819 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001820 // Create fields
1821 FieldDecl *FieldDecls[2];
1822
1823 for (unsigned i = 0; i < 2; ++i)
Chris Lattner81db64a2008-03-16 00:16:02 +00001824 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1825 FieldTypes[i]);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001826
1827 SuperStructDecl->defineBody(FieldDecls, 4);
1828 }
1829 return Context->getTagDeclType(SuperStructDecl);
1830}
1831
Steve Naroff47e7fa22008-03-15 00:55:56 +00001832QualType RewriteTest::getConstantStringStructType() {
1833 if (!ConstantStringDecl) {
Chris Lattner58114f02008-03-15 21:32:50 +00001834 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct,
1835 SourceLocation(),
1836 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001837 QualType FieldTypes[4];
1838
1839 // struct objc_object *receiver;
1840 FieldTypes[0] = Context->getObjCIdType();
1841 // int flags;
1842 FieldTypes[1] = Context->IntTy;
1843 // char *str;
1844 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1845 // long length;
1846 FieldTypes[3] = Context->LongTy;
1847 // Create fields
Steve Naroff053ae3f2008-03-27 22:59:54 +00001848 FieldDecl *FieldDecls[4];
Steve Naroff47e7fa22008-03-15 00:55:56 +00001849
1850 for (unsigned i = 0; i < 4; ++i)
Chris Lattner81db64a2008-03-16 00:16:02 +00001851 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1852 FieldTypes[i]);
Steve Naroff47e7fa22008-03-15 00:55:56 +00001853
1854 ConstantStringDecl->defineBody(FieldDecls, 4);
1855 }
1856 return Context->getTagDeclType(ConstantStringDecl);
1857}
1858
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001859Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001860 if (!SelGetUidFunctionDecl)
1861 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001862 if (!MsgSendFunctionDecl)
1863 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001864 if (!MsgSendSuperFunctionDecl)
1865 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001866 if (!MsgSendStretFunctionDecl)
1867 SynthMsgSendStretFunctionDecl();
1868 if (!MsgSendSuperStretFunctionDecl)
1869 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001870 if (!MsgSendFpretFunctionDecl)
1871 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001872 if (!GetClassFunctionDecl)
1873 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001874 if (!GetMetaClassFunctionDecl)
1875 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001876
Steve Naroff764c1ae2007-11-15 10:28:18 +00001877 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001878 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1879 // May need to use objc_msgSend_stret() as well.
1880 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001881 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001882 QualType resultType = mDecl->getResultType();
1883 if (resultType.getCanonicalType()->isStructureType()
1884 || resultType.getCanonicalType()->isUnionType())
1885 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001886 else if (resultType.getCanonicalType()->isRealFloatingType())
1887 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001888 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001889
Steve Naroff71226032007-10-24 22:48:43 +00001890 // Synthesize a call to objc_msgSend().
1891 llvm::SmallVector<Expr*, 8> MsgExprs;
1892 IdentifierInfo *clsName = Exp->getClassName();
1893
1894 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1895 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001896 if (!strcmp(clsName->getName(), "super")) {
1897 MsgSendFlavor = MsgSendSuperFunctionDecl;
1898 if (MsgSendStretFlavor)
1899 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1900 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1901
Ted Kremenek42730c52008-01-07 19:49:32 +00001902 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001903 CurMethodDecl->getClassInterface()->getSuperClass();
1904
1905 llvm::SmallVector<Expr*, 4> InitExprs;
1906
1907 // set the receiver to self, the first argument to all methods.
1908 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001909 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001910 SourceLocation()));
1911 llvm::SmallVector<Expr*, 8> ClsExprs;
1912 QualType argType = Context->getPointerType(Context->CharTy);
1913 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1914 SuperDecl->getIdentifier()->getLength(),
1915 false, argType, SourceLocation(),
1916 SourceLocation()));
1917 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1918 &ClsExprs[0],
1919 ClsExprs.size());
1920 // To turn off a warning, type-cast to 'id'
1921 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001922 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001923 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1924 // struct objc_super
1925 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001926 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001927
Steve Naroffdee066b2008-03-11 18:14:26 +00001928 if (LangOpts.Microsoft) {
1929 SynthSuperContructorFunctionDecl();
1930 // Simulate a contructor call...
1931 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1932 superType, SourceLocation());
1933 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1934 superType, SourceLocation());
1935 } else {
1936 // (struct objc_super) { <exprs from above> }
1937 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1938 &InitExprs[0], InitExprs.size(),
1939 SourceLocation());
1940 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1941 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001942 // struct objc_super *
1943 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1944 Context->getPointerType(SuperRep->getType()),
1945 SourceLocation());
1946 MsgExprs.push_back(Unop);
1947 } else {
1948 llvm::SmallVector<Expr*, 8> ClsExprs;
1949 QualType argType = Context->getPointerType(Context->CharTy);
1950 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1951 clsName->getLength(),
1952 false, argType, SourceLocation(),
1953 SourceLocation()));
1954 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1955 &ClsExprs[0],
1956 ClsExprs.size());
1957 MsgExprs.push_back(Cls);
1958 }
Steve Naroff885e2122007-11-14 23:54:14 +00001959 } else { // instance message.
1960 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001961
Ted Kremenek42730c52008-01-07 19:49:32 +00001962 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001963 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001964 if (MsgSendStretFlavor)
1965 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001966 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1967
1968 llvm::SmallVector<Expr*, 4> InitExprs;
1969
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001970 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001971 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001972 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001973
1974 llvm::SmallVector<Expr*, 8> ClsExprs;
1975 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001976 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1977 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001978 false, argType, SourceLocation(),
1979 SourceLocation()));
1980 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001981 &ClsExprs[0],
1982 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001983 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001984 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001985 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001986 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001987 // struct objc_super
1988 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001989 Expr *SuperRep;
1990
1991 if (LangOpts.Microsoft) {
1992 SynthSuperContructorFunctionDecl();
1993 // Simulate a contructor call...
1994 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1995 superType, SourceLocation());
1996 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1997 superType, SourceLocation());
1998 } else {
1999 // (struct objc_super) { <exprs from above> }
2000 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2001 &InitExprs[0], InitExprs.size(),
2002 SourceLocation());
2003 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2004 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002005 // struct objc_super *
2006 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2007 Context->getPointerType(SuperRep->getType()),
2008 SourceLocation());
2009 MsgExprs.push_back(Unop);
2010 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002011 // Remove all type-casts because it may contain objc-style types; e.g.
2012 // Foo<Proto> *.
2013 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2014 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002015 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002016 MsgExprs.push_back(recExpr);
2017 }
Steve Naroff885e2122007-11-14 23:54:14 +00002018 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002019 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002020 llvm::SmallVector<Expr*, 8> SelExprs;
2021 QualType argType = Context->getPointerType(Context->CharTy);
2022 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2023 Exp->getSelector().getName().size(),
2024 false, argType, SourceLocation(),
2025 SourceLocation()));
2026 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2027 &SelExprs[0], SelExprs.size());
2028 MsgExprs.push_back(SelExp);
2029
2030 // Now push any user supplied arguments.
2031 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002032 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002033 // Make all implicit casts explicit...ICE comes in handy:-)
2034 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2035 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002036 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2037 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002038 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002039 }
2040 // Make id<P...> cast into an 'id' cast.
2041 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002042 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002043 while ((CE = dyn_cast<CastExpr>(userExpr)))
2044 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002045 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002046 userExpr, SourceLocation());
2047 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002048 }
Steve Naroff885e2122007-11-14 23:54:14 +00002049 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002050 // We've transferred the ownership to MsgExprs. Null out the argument in
2051 // the original expression, since we will delete it below.
2052 Exp->setArg(i, 0);
2053 }
Steve Naroff0744c472007-11-04 22:37:50 +00002054 // Generate the funky cast.
2055 CastExpr *cast;
2056 llvm::SmallVector<QualType, 8> ArgTypes;
2057 QualType returnType;
2058
2059 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002060 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2061 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2062 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002063 ArgTypes.push_back(Context->getObjCIdType());
2064 ArgTypes.push_back(Context->getObjCSelType());
2065 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002066 // Push any user argument types.
Chris Lattner685d7922008-03-16 01:07:14 +00002067 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002068 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2069 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002070 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002071 ArgTypes.push_back(t);
2072 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002073 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2074 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002075 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002076 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002077 }
2078 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002079 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002080
2081 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002082 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2083 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002084
2085 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2086 // If we don't do this cast, we get the following bizarre warning/note:
2087 // xx.m:13: warning: function called through a non-compatible type
2088 // xx.m:13: note: if this code is reached, the program will abort
2089 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2090 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002091
Steve Naroff0744c472007-11-04 22:37:50 +00002092 // Now do the "normal" pointer to function cast.
2093 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002094 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002095 // If we don't have a method decl, force a variadic cast.
2096 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroff0744c472007-11-04 22:37:50 +00002097 castType = Context->getPointerType(castType);
2098 cast = new CastExpr(castType, cast, SourceLocation());
2099
2100 // Don't forget the parens to enforce the proper binding.
2101 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2102
2103 const FunctionType *FT = msgSendType->getAsFunctionType();
2104 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2105 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002106 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002107 if (MsgSendStretFlavor) {
2108 // We have the method which returns a struct/union. Must also generate
2109 // call to objc_msgSend_stret and hang both varieties on a conditional
2110 // expression which dictate which one to envoke depending on size of
2111 // method's return type.
2112
2113 // Create a reference to the objc_msgSend_stret() declaration.
2114 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2115 SourceLocation());
2116 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2117 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2118 SourceLocation());
2119 // Now do the "normal" pointer to function cast.
2120 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002121 &ArgTypes[0], ArgTypes.size(),
2122 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002123 castType = Context->getPointerType(castType);
2124 cast = new CastExpr(castType, cast, SourceLocation());
2125
2126 // Don't forget the parens to enforce the proper binding.
2127 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2128
2129 FT = msgSendType->getAsFunctionType();
2130 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2131 FT->getResultType(), SourceLocation());
2132
2133 // Build sizeof(returnType)
2134 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2135 returnType, Context->getSizeType(),
2136 SourceLocation(), SourceLocation());
2137 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2138 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2139 // For X86 it is more complicated and some kind of target specific routine
2140 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002141 unsigned IntSize =
2142 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002143 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2144 Context->IntTy,
2145 SourceLocation());
2146 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2147 BinaryOperator::LE,
2148 Context->IntTy,
2149 SourceLocation());
2150 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2151 ConditionalOperator *CondExpr =
2152 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002153 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002154 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002155 return ReplacingStmt;
2156}
2157
2158Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2159 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002160 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002161 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002162
Chris Lattner0021f452007-10-24 16:57:36 +00002163 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002164 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002165}
2166
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002167/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2168/// call to objc_getProtocol("proto-name").
2169Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2170 if (!GetProtocolFunctionDecl)
2171 SynthGetProtocolFunctionDecl();
2172 // Create a call to objc_getProtocol("ProtocolName").
2173 llvm::SmallVector<Expr*, 8> ProtoExprs;
2174 QualType argType = Context->getPointerType(Context->CharTy);
2175 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2176 strlen(Exp->getProtocol()->getName()),
2177 false, argType, SourceLocation(),
2178 SourceLocation()));
2179 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2180 &ProtoExprs[0],
2181 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002182 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002183 delete Exp;
2184 return ProtoExp;
2185
2186}
2187
Ted Kremenek42730c52008-01-07 19:49:32 +00002188/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002189/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002190void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002191 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002192 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2193 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002194 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002195 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002196 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002197 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002198 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002199 SourceLocation LocStart = CDecl->getLocStart();
2200 SourceLocation LocEnd = CDecl->getLocEnd();
2201
2202 const char *startBuf = SM->getCharacterData(LocStart);
2203 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002204 // If no ivars and no root or if its root, directly or indirectly,
2205 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002206 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2207 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002208 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002209 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002210 return;
2211 }
2212
2213 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002214 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002215 Result += "\nstruct ";
2216 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002217 if (LangOpts.Microsoft)
2218 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002219
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002220 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002221 const char *cursor = strchr(startBuf, '{');
2222 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002223 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002224
2225 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002226 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002227 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002228 Result = "\n struct ";
2229 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002230 Result += "_IMPL ";
2231 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002232 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002233
2234 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002235 SourceLocation OnePastCurly =
2236 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2237 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002238 }
2239 cursor++; // past '{'
2240
2241 // Now comment out any visibility specifiers.
2242 while (cursor < endBuf) {
2243 if (*cursor == '@') {
2244 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002245 // Skip whitespace.
2246 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2247 /*scan*/;
2248
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002249 // FIXME: presence of @public, etc. inside comment results in
2250 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002251 if (!strncmp(cursor, "public", strlen("public")) ||
2252 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002253 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002254 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002255 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002256 // FIXME: If there are cases where '<' is used in ivar declaration part
2257 // of user code, then scan the ivar list and use needToScanForQualifiers
2258 // for type checking.
2259 else if (*cursor == '<') {
2260 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002261 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002262 cursor = strchr(cursor, '>');
2263 cursor++;
2264 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002265 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002266 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002267 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002268 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002269 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002270 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002271 } else { // we don't have any instance variables - insert super struct.
2272 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2273 Result += " {\n struct ";
2274 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002275 Result += "_IMPL ";
2276 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002277 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002278 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002279 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002280 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002281 if (!ObjCSynthesizedStructs.insert(CDecl))
2282 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002283}
2284
Ted Kremenek42730c52008-01-07 19:49:32 +00002285// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002286/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002287void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002288 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002289 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002290 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002291 const char *ClassName,
2292 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002293 if (MethodBegin == MethodEnd) return;
2294
Fariborz Jahanian04455192007-10-22 21:41:37 +00002295 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002296 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002297 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002298 SEL _cmd;
2299 char *method_types;
2300 void *_imp;
2301 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002302 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002303 Result += "\nstruct _objc_method {\n";
2304 Result += "\tSEL _cmd;\n";
2305 Result += "\tchar *method_types;\n";
2306 Result += "\tvoid *_imp;\n";
2307 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002308
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002309 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002310 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002311
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002312 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002313
2314 /* struct {
2315 struct _objc_method_list *next_method;
2316 int method_count;
2317 struct _objc_method method_list[];
2318 }
2319 */
2320 Result += "\nstatic struct {\n";
2321 Result += "\tstruct _objc_method_list *next_method;\n";
2322 Result += "\tint method_count;\n";
2323 Result += "\tstruct _objc_method method_list[";
2324 Result += utostr(MethodEnd-MethodBegin);
2325 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002326 Result += prefix;
2327 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2328 Result += "_METHODS_";
2329 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002330 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002331 Result += IsInstanceMethod ? "inst" : "cls";
2332 Result += "_meth\")))= ";
2333 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002334
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002335 Result += "\t,{{(SEL)\"";
2336 Result += (*MethodBegin)->getSelector().getName().c_str();
2337 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002338 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002339 Result += "\", \"";
2340 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002341 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002342 Result += MethodInternalNames[*MethodBegin];
2343 Result += "}\n";
2344 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2345 Result += "\t ,{(SEL)\"";
2346 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002347 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002348 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002349 Result += "\", \"";
2350 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002351 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002352 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002353 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002354 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002355 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002356}
2357
Ted Kremenek42730c52008-01-07 19:49:32 +00002358/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2359void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002360 int NumProtocols,
2361 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002362 const char *ClassName,
2363 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002364 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002365 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002366 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002367 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002368 // Output struct protocol_methods holder of method selector and type.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002369 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002370 /* struct protocol_methods {
2371 SEL _cmd;
2372 char *method_types;
2373 }
2374 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002375 Result += "\nstruct protocol_methods {\n";
2376 Result += "\tSEL _cmd;\n";
2377 Result += "\tchar *method_types;\n";
2378 Result += "};\n";
2379
Steve Naroff27429432008-03-12 01:06:30 +00002380 objc_protocol_methods = true;
2381 }
Chris Lattner7afba9c2008-03-16 20:19:15 +00002382 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2383 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002384 /* struct _objc_protocol_method_list {
2385 int protocol_method_count;
2386 struct protocol_methods protocols[];
2387 }
2388 */
Steve Naroff27429432008-03-12 01:06:30 +00002389 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002390 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002391 Result += "\tstruct protocol_methods protocols[";
2392 Result += utostr(NumMethods);
2393 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002394 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002395 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002396 "{\n\t" + utostr(NumMethods) + "\n";
2397
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002398 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002399 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002400 E = PDecl->instmeth_end(); I != E; ++I) {
2401 if (I == PDecl->instmeth_begin())
2402 Result += "\t ,{{(SEL)\"";
2403 else
2404 Result += "\t ,{(SEL)\"";
2405 Result += (*I)->getSelector().getName().c_str();
2406 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002407 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002408 Result += "\", \"";
2409 Result += MethodTypeString;
2410 Result += "\"}\n";
2411 }
2412 Result += "\t }\n};\n";
2413 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002414
2415 // Output class methods declared in this protocol.
Chris Lattner7afba9c2008-03-16 20:19:15 +00002416 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahanian04455192007-10-22 21:41:37 +00002417 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002418 /* struct _objc_protocol_method_list {
2419 int protocol_method_count;
2420 struct protocol_methods protocols[];
2421 }
2422 */
2423 Result += "\nstatic struct {\n";
2424 Result += "\tint protocol_method_count;\n";
2425 Result += "\tstruct protocol_methods protocols[";
2426 Result += utostr(NumMethods);
2427 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002428 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002429 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002430 "{\n\t";
2431 Result += utostr(NumMethods);
2432 Result += "\n";
2433
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002434 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002435 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002436 E = PDecl->classmeth_end(); I != E; ++I) {
2437 if (I == PDecl->classmeth_begin())
2438 Result += "\t ,{{(SEL)\"";
2439 else
2440 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002441 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002442 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002443 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002444 Result += "\", \"";
2445 Result += MethodTypeString;
2446 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002447 }
2448 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002449 }
2450 // Output:
2451 /* struct _objc_protocol {
2452 // Objective-C 1.0 extensions
2453 struct _objc_protocol_extension *isa;
2454 char *protocol_name;
2455 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002456 struct _objc_protocol_method_list *instance_methods;
2457 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002458 };
2459 */
2460 static bool objc_protocol = false;
2461 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002462 Result += "\nstruct _objc_protocol {\n";
2463 Result += "\tstruct _objc_protocol_extension *isa;\n";
2464 Result += "\tchar *protocol_name;\n";
2465 Result += "\tstruct _objc_protocol **protocol_list;\n";
2466 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2467 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2468 Result += "};\n";
2469
Fariborz Jahanian04455192007-10-22 21:41:37 +00002470 objc_protocol = true;
2471 }
2472
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002473 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2474 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002475 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002476 "{\n\t0, \"";
2477 Result += PDecl->getName();
2478 Result += "\", 0, ";
Chris Lattner7afba9c2008-03-16 20:19:15 +00002479 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00002480 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002481 Result += PDecl->getName();
2482 Result += ", ";
2483 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002484 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002485 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002486 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002487 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002488 Result += PDecl->getName();
2489 Result += "\n";
2490 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002491 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002492 Result += "0\n";
2493 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002494 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002495 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002496 /* struct _objc_protocol_list {
2497 struct _objc_protocol_list *next;
2498 int protocol_count;
2499 struct _objc_protocol *class_protocols[];
2500 }
2501 */
2502 Result += "\nstatic struct {\n";
2503 Result += "\tstruct _objc_protocol_list *next;\n";
2504 Result += "\tint protocol_count;\n";
2505 Result += "\tstruct _objc_protocol *class_protocols[";
2506 Result += utostr(NumProtocols);
2507 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002508 Result += prefix;
2509 Result += "_PROTOCOLS_";
2510 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002511 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002512 "{\n\t0, ";
2513 Result += utostr(NumProtocols);
2514 Result += "\n";
2515
2516 Result += "\t,{&_OBJC_PROTOCOL_";
2517 Result += Protocols[0]->getName();
2518 Result += " \n";
2519
2520 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002521 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff27429432008-03-12 01:06:30 +00002522 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002523 Result += PDecl->getName();
2524 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002525 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002526 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002527 }
2528}
2529
Ted Kremenek42730c52008-01-07 19:49:32 +00002530/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002531/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002532void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002533 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002534 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002535 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002536 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002537 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2538 CDecl = CDecl->getNextClassCategory())
2539 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2540 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002541
Chris Lattnera661a4d2007-12-23 01:40:15 +00002542 std::string FullCategoryName = ClassDecl->getName();
2543 FullCategoryName += '_';
2544 FullCategoryName += IDecl->getName();
2545
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002546 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002547 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002548 true, "CATEGORY_", FullCategoryName.c_str(),
2549 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002550
2551 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002552 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002553 false, "CATEGORY_", FullCategoryName.c_str(),
2554 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002555
2556 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002557 // Null CDecl is case of a category implementation with no category interface
2558 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002559 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002560 CDecl->getNumReferencedProtocols(),
2561 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002562 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002563
2564 /* struct _objc_category {
2565 char *category_name;
2566 char *class_name;
2567 struct _objc_method_list *instance_methods;
2568 struct _objc_method_list *class_methods;
2569 struct _objc_protocol_list *protocols;
2570 // Objective-C 1.0 extensions
2571 uint32_t size; // sizeof (struct _objc_category)
2572 struct _objc_property_list *instance_properties; // category's own
2573 // @property decl.
2574 };
2575 */
2576
2577 static bool objc_category = false;
2578 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002579 Result += "\nstruct _objc_category {\n";
2580 Result += "\tchar *category_name;\n";
2581 Result += "\tchar *class_name;\n";
2582 Result += "\tstruct _objc_method_list *instance_methods;\n";
2583 Result += "\tstruct _objc_method_list *class_methods;\n";
2584 Result += "\tstruct _objc_protocol_list *protocols;\n";
2585 Result += "\tunsigned int size;\n";
2586 Result += "\tstruct _objc_property_list *instance_properties;\n";
2587 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002588 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002589 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002590 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2591 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002592 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002593 Result += IDecl->getName();
2594 Result += "\"\n\t, \"";
2595 Result += ClassDecl->getName();
2596 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002597
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002598 if (IDecl->getNumInstanceMethods() > 0) {
2599 Result += "\t, (struct _objc_method_list *)"
2600 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2601 Result += FullCategoryName;
2602 Result += "\n";
2603 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002604 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002605 Result += "\t, 0\n";
2606 if (IDecl->getNumClassMethods() > 0) {
2607 Result += "\t, (struct _objc_method_list *)"
2608 "&_OBJC_CATEGORY_CLASS_METHODS_";
2609 Result += FullCategoryName;
2610 Result += "\n";
2611 }
2612 else
2613 Result += "\t, 0\n";
2614
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002615 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002616 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2617 Result += FullCategoryName;
2618 Result += "\n";
2619 }
2620 else
2621 Result += "\t, 0\n";
2622 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002623}
2624
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002625/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2626/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002627void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2628 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002629 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002630 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002631 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002632 if (LangOpts.Microsoft)
2633 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002634 Result += ", ";
2635 Result += ivar->getName();
2636 Result += ")";
2637}
2638
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002639//===----------------------------------------------------------------------===//
2640// Meta Data Emission
2641//===----------------------------------------------------------------------===//
2642
Ted Kremenek42730c52008-01-07 19:49:32 +00002643void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002644 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002645 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002646
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002647 // Explictly declared @interface's are already synthesized.
2648 if (CDecl->ImplicitInterfaceDecl()) {
2649 // FIXME: Implementation of a class with no @interface (legacy) doese not
2650 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002651 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002652 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002653
Chris Lattnerc7b06752007-12-12 07:56:42 +00002654 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00002655 unsigned NumIvars = !IDecl->ivar_empty()
2656 ? IDecl->ivar_size()
2657 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002658 if (NumIvars > 0) {
2659 static bool objc_ivar = false;
2660 if (!objc_ivar) {
2661 /* struct _objc_ivar {
2662 char *ivar_name;
2663 char *ivar_type;
2664 int ivar_offset;
2665 };
2666 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002667 Result += "\nstruct _objc_ivar {\n";
2668 Result += "\tchar *ivar_name;\n";
2669 Result += "\tchar *ivar_type;\n";
2670 Result += "\tint ivar_offset;\n";
2671 Result += "};\n";
2672
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002673 objc_ivar = true;
2674 }
2675
Steve Naroffc723eec2008-03-11 00:12:29 +00002676 /* struct {
2677 int ivar_count;
2678 struct _objc_ivar ivar_list[nIvars];
2679 };
2680 */
2681 Result += "\nstatic struct {\n";
2682 Result += "\tint ivar_count;\n";
2683 Result += "\tstruct _objc_ivar ivar_list[";
2684 Result += utostr(NumIvars);
2685 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002686 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002687 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002688 "{\n\t";
2689 Result += utostr(NumIvars);
2690 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002691
Ted Kremenek42730c52008-01-07 19:49:32 +00002692 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00002693 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00002694 IVI = IDecl->ivar_begin();
2695 IVE = IDecl->ivar_end();
2696 } else {
2697 IVI = CDecl->ivar_begin();
2698 IVE = CDecl->ivar_end();
2699 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002700 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002701 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002702 Result += "\", \"";
2703 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002704 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2705 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002706 Result += StrEncoding;
2707 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002708 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002709 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002710 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002711 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002712 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002713 Result += "\", \"";
2714 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002715 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2716 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002717 Result += StrEncoding;
2718 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002719 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002720 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002721 }
2722
2723 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002724 }
2725
2726 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002727 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002728 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002729
2730 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002731 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002732 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002733
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002734 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002735 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002736 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002737 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002738
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002739
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002740 // Declaration of class/meta-class metadata
2741 /* struct _objc_class {
2742 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002743 const char *super_class_name;
2744 char *name;
2745 long version;
2746 long info;
2747 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002748 struct _objc_ivar_list *ivars;
2749 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002750 struct objc_cache *cache;
2751 struct objc_protocol_list *protocols;
2752 const char *ivar_layout;
2753 struct _objc_class_ext *ext;
2754 };
2755 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002756 static bool objc_class = false;
2757 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002758 Result += "\nstruct _objc_class {\n";
2759 Result += "\tstruct _objc_class *isa;\n";
2760 Result += "\tconst char *super_class_name;\n";
2761 Result += "\tchar *name;\n";
2762 Result += "\tlong version;\n";
2763 Result += "\tlong info;\n";
2764 Result += "\tlong instance_size;\n";
2765 Result += "\tstruct _objc_ivar_list *ivars;\n";
2766 Result += "\tstruct _objc_method_list *methods;\n";
2767 Result += "\tstruct objc_cache *cache;\n";
2768 Result += "\tstruct _objc_protocol_list *protocols;\n";
2769 Result += "\tconst char *ivar_layout;\n";
2770 Result += "\tstruct _objc_class_ext *ext;\n";
2771 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002772 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002773 }
2774
2775 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002776 ObjCInterfaceDecl *RootClass = 0;
2777 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002778 while (SuperClass) {
2779 RootClass = SuperClass;
2780 SuperClass = SuperClass->getSuperClass();
2781 }
2782 SuperClass = CDecl->getSuperClass();
2783
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002784 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2785 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002786 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002787 "{\n\t(struct _objc_class *)\"";
2788 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2789 Result += "\"";
2790
2791 if (SuperClass) {
2792 Result += ", \"";
2793 Result += SuperClass->getName();
2794 Result += "\", \"";
2795 Result += CDecl->getName();
2796 Result += "\"";
2797 }
2798 else {
2799 Result += ", 0, \"";
2800 Result += CDecl->getName();
2801 Result += "\"";
2802 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002803 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002804 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002805 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002806 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002807 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002808 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002809 Result += "\n";
2810 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002811 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002812 Result += ", 0\n";
2813 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002814 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002815 Result += CDecl->getName();
2816 Result += ",0,0\n";
2817 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002818 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002819 Result += "\t,0,0,0,0\n";
2820 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002821
2822 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002823 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2824 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002825 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002826 "{\n\t&_OBJC_METACLASS_";
2827 Result += CDecl->getName();
2828 if (SuperClass) {
2829 Result += ", \"";
2830 Result += SuperClass->getName();
2831 Result += "\", \"";
2832 Result += CDecl->getName();
2833 Result += "\"";
2834 }
2835 else {
2836 Result += ", 0, \"";
2837 Result += CDecl->getName();
2838 Result += "\"";
2839 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002840 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002841 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002842 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002843 Result += ",0";
2844 else {
2845 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002846 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002847 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002848 if (LangOpts.Microsoft)
2849 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002850 Result += ")";
2851 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002852 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002853 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002854 Result += CDecl->getName();
2855 Result += "\n\t";
2856 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002857 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002858 Result += ",0";
2859 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002860 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002861 Result += CDecl->getName();
2862 Result += ", 0\n\t";
2863 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002864 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002865 Result += ",0,0";
2866 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002867 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002868 Result += CDecl->getName();
2869 Result += ", 0,0\n";
2870 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002871 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002872 Result += ",0,0,0\n";
2873 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002874}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002875
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002876/// RewriteImplementations - This routine rewrites all method implementations
2877/// and emits meta-data.
2878
2879void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002880 int ClsDefCount = ClassImplementation.size();
2881 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002882
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002883 if (ClsDefCount == 0 && CatDefCount == 0)
2884 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002885 // Rewrite implemented methods
2886 for (int i = 0; i < ClsDefCount; i++)
2887 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002888
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002889 for (int i = 0; i < CatDefCount; i++)
2890 RewriteImplementationDecl(CategoryImplementation[i]);
2891
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002892 // This is needed for use of offsetof
2893 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002894
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002895 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002896 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002897 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002898
2899 // For each implemented category, write out all its meta data.
2900 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002901 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002902
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002903 // Write objc_symtab metadata
2904 /*
2905 struct _objc_symtab
2906 {
2907 long sel_ref_cnt;
2908 SEL *refs;
2909 short cls_def_cnt;
2910 short cat_def_cnt;
2911 void *defs[cls_def_cnt + cat_def_cnt];
2912 };
2913 */
2914
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002915 Result += "\nstruct _objc_symtab {\n";
2916 Result += "\tlong sel_ref_cnt;\n";
2917 Result += "\tSEL *refs;\n";
2918 Result += "\tshort cls_def_cnt;\n";
2919 Result += "\tshort cat_def_cnt;\n";
2920 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2921 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002922
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002923 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002924 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002925 Result += "\t0, 0, " + utostr(ClsDefCount)
2926 + ", " + utostr(CatDefCount) + "\n";
2927 for (int i = 0; i < ClsDefCount; i++) {
2928 Result += "\t,&_OBJC_CLASS_";
2929 Result += ClassImplementation[i]->getName();
2930 Result += "\n";
2931 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002932
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002933 for (int i = 0; i < CatDefCount; i++) {
2934 Result += "\t,&_OBJC_CATEGORY_";
2935 Result += CategoryImplementation[i]->getClassInterface()->getName();
2936 Result += "_";
2937 Result += CategoryImplementation[i]->getName();
2938 Result += "\n";
2939 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002940
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002941 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002942
2943 // Write objc_module metadata
2944
2945 /*
2946 struct _objc_module {
2947 long version;
2948 long size;
2949 const char *name;
2950 struct _objc_symtab *symtab;
2951 }
2952 */
2953
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002954 Result += "\nstruct _objc_module {\n";
2955 Result += "\tlong version;\n";
2956 Result += "\tlong size;\n";
2957 Result += "\tconst char *name;\n";
2958 Result += "\tstruct _objc_symtab *symtab;\n";
2959 Result += "};\n\n";
2960 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002961 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002962 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2963 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002964 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002965
2966 if (LangOpts.Microsoft) {
2967 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2968 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2969 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2970 Result += "&_OBJC_MODULES;\n";
2971 Result += "#pragma data_seg(pop)\n\n";
2972 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002973}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002974