blob: 26bfa01b26868069db7f32c9d566e9d66894aa87 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-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 Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000026#include "llvm/System/Path.h"
Steve Naroff874e2322007-11-15 10:28:18 +000027#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000028#include <fstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000036namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000037 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000038 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000039 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000040 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000041 unsigned RewriteFailedDiag;
42
Chris Lattner01c57482007-10-17 22:35:30 +000043 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000044 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000045 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000046 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000047 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000048
Ted Kremeneka526c5c2008-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 Jahaniane8d1c052008-01-15 23:58:23 +000054 llvm::SmallVector<Stmt *, 32> Stmts;
55 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000056 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000057
Steve Naroffd82a9ab2008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000069 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000070 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000071
Steve Naroffbeaf2992007-11-03 11:27:19 +000072 // ObjC string constant support.
73 FileVarDecl *ConstantStringClassReference;
74 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000075
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000076 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000077 int BcLabelCount;
78
Steve Naroff874e2322007-11-15 10:28:18 +000079 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000080 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000081 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000083
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000084 // Needed for header files being rewritten
85 bool IsHeader;
86
Steve Naroffa7b402d2008-03-28 22:26:09 +000087 std::string InFileName;
88 std::string OutFileName;
89
Steve Naroffba92b2e2008-03-27 22:29:16 +000090 std::string Preamble;
91
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000092 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000093 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000094 void Initialize(ASTContext &context);
95
Chris Lattner8a12c272007-10-11 18:38:32 +000096
Chris Lattnerf04da132007-10-24 17:06:59 +000097 // Top Level Driver code.
98 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000099 void HandleDeclInMainFile(Decl *D);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000100 RewriteTest(std::string inFile, std::string outFile,
101 Diagnostic &D, const LangOptions &LOpts);
Chris Lattnerf04da132007-10-24 17:06:59 +0000102 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000103
104 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000105 // If replacement succeeded or warning disabled return with no warning.
106 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000107 return;
108
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000109 SourceRange Range = Old->getSourceRange();
110 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
111 0, 0, &Range, 1);
112 }
113
Steve Naroffba92b2e2008-03-27 22:29:16 +0000114 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
115 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000116 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000117 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000118 SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000123
Chris Lattneraadaf782008-01-31 19:51:04 +0000124 void RemoveText(SourceLocation Loc, unsigned StrLen) {
125 // If removal succeeded or warning disabled return with no warning.
126 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
127 return;
128
129 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
130 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000131
Chris Lattneraadaf782008-01-31 19:51:04 +0000132 void ReplaceText(SourceLocation Start, unsigned OrigLength,
133 const char *NewStr, unsigned NewLength) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
136 SilenceRewriteMacroWarning)
137 return;
138
139 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
140 }
141
Chris Lattnerf04da132007-10-24 17:06:59 +0000142 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000143 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000144 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000145 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000146 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
147 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000148 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
150 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
151 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
152 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
153 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000154 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000155 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000156 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000157 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000159 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000160 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000163 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000164 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000165 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000166 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000167 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000168 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000169 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000171 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
173 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
174 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000175 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
176 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000177 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
178 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000179 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000180 Stmt *RewriteBreakStmt(BreakStmt *S);
181 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000182 void SynthCountByEnumWithState(std::string &buf);
183
Steve Naroff09b266e2007-10-30 23:14:51 +0000184 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000185 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000186 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000187 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000188 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000189 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000190 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000191 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000192 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000193 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000194
Chris Lattnerf04da132007-10-24 17:06:59 +0000195 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000197 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000198
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
203 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000204 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000205 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000206 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000207 const char *ClassName,
208 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000209
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211 int NumProtocols,
212 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000213 const char *ClassName,
214 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000216 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
218 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000219 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000220 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000221 };
222}
223
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000224static bool IsHeaderFile(const std::string &Filename) {
225 std::string::size_type DotPos = Filename.rfind('.');
226
227 if (DotPos == std::string::npos) {
228 // no file extension
229 return false;
230 }
231
232 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
233 // C header: .h
234 // C++ header: .hh or .H;
235 return Ext == "h" || Ext == "hh" || Ext == "H";
236}
237
Steve Naroffa7b402d2008-03-28 22:26:09 +0000238RewriteTest::RewriteTest(std::string inFile, std::string outFile,
239 Diagnostic &D, const LangOptions &LOpts)
240 : Diags(D), LangOpts(LOpts) {
241 IsHeader = IsHeaderFile(inFile);
242 InFileName = inFile;
243 OutFileName = outFile;
244 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
245 "rewriting sub-expression within a macro (may not be correct)");
246}
247
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000248ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000249 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000250 Diagnostic &Diags,
251 const LangOptions &LOpts) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000252 return new RewriteTest(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000253}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000254
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000255void RewriteTest::Initialize(ASTContext &context) {
256 Context = &context;
257 SM = &Context->getSourceManager();
258 MsgSendFunctionDecl = 0;
259 MsgSendSuperFunctionDecl = 0;
260 MsgSendStretFunctionDecl = 0;
261 MsgSendSuperStretFunctionDecl = 0;
262 MsgSendFpretFunctionDecl = 0;
263 GetClassFunctionDecl = 0;
264 GetMetaClassFunctionDecl = 0;
265 SelGetUidFunctionDecl = 0;
266 CFStringFunctionDecl = 0;
267 GetProtocolFunctionDecl = 0;
268 ConstantStringClassReference = 0;
269 NSStringRecord = 0;
270 CurMethodDecl = 0;
271 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000272 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000273 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000274 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000275 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000276
277 // Get the ID and start/end of the main file.
278 MainFileID = SM->getMainFileID();
279 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
280 MainFileStart = MainBuf->getBufferStart();
281 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000282
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000283 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000284
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000285 // declaring objc_selector outside the parameter list removes a silly
286 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000287 if (IsHeader)
288 Preamble = "#pragma once\n";
289 Preamble += "struct objc_selector; struct objc_class;\n";
290 Preamble += "#ifndef OBJC_SUPER\n";
291 Preamble += "struct objc_super { struct objc_object *object; ";
292 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000293 if (LangOpts.Microsoft) {
294 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000295 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
296 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000297 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 Preamble += "};\n";
299 Preamble += "#define OBJC_SUPER\n";
300 Preamble += "#endif\n";
301 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
302 Preamble += "typedef struct objc_object Protocol;\n";
303 Preamble += "#define _REWRITER_typedef_Protocol\n";
304 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000305 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000306 Preamble += "extern \"C\" {\n";
307 Preamble += "struct objc_object *objc_msgSend";
308 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
309 Preamble += "extern struct objc_object *objc_msgSendSuper";
310 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
311 Preamble += "extern struct objc_object *objc_msgSend_stret";
312 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
313 Preamble += "extern struct objc_object *objc_msgSendSuper_stret";
314 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
315 Preamble += "extern struct objc_object *objc_msgSend_fpret";
316 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
317 Preamble += "struct objc_object *objc_getClass";
318 Preamble += "(const char *);\n";
319 Preamble += "extern struct objc_object *objc_getMetaClass";
320 Preamble += "(const char *);\n";
321 Preamble += "extern void objc_exception_throw(struct objc_object *);\n";
322 Preamble += "extern void objc_exception_try_enter(void *);\n";
323 Preamble += "extern void objc_exception_try_exit(void *);\n";
324 Preamble += "extern struct objc_object *objc_exception_extract(void *);\n";
325 Preamble += "extern int objc_exception_match";
326 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
327 Preamble += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000328 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000329 Preamble += "} // end extern \"C\"\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000330 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
331 Preamble += "struct __objcFastEnumerationState {\n\t";
332 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000333 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "unsigned long *mutationsPtr;\n\t";
335 Preamble += "unsigned long extra[5];\n};\n";
336 Preamble += "#define __FASTENUMERATIONSTATE\n";
337 Preamble += "#endif\n";
338 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
339 Preamble += "struct __NSConstantStringImpl {\n";
340 Preamble += " int *isa;\n";
341 Preamble += " int flags;\n";
342 Preamble += " char *str;\n";
343 Preamble += " long length;\n";
344 Preamble += "};\n";
345 Preamble += "extern int __CFConstantStringClassReference[];\n";
346 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
347 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000348 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000349 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000350}
351
352
Chris Lattnerf04da132007-10-24 17:06:59 +0000353//===----------------------------------------------------------------------===//
354// Top Level Driver Code
355//===----------------------------------------------------------------------===//
356
Chris Lattner8a12c272007-10-11 18:38:32 +0000357void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000358 // Two cases: either the decl could be in the main file, or it could be in a
359 // #included file. If the former, rewrite it now. If the later, check to see
360 // if we rewrote the #include/#import.
361 SourceLocation Loc = D->getLocation();
362 Loc = SM->getLogicalLoc(Loc);
363
364 // If this is for a builtin, ignore it.
365 if (Loc.isInvalid()) return;
366
Steve Naroffebf2b562007-10-23 23:50:29 +0000367 // Look for built-in declarations that we need to refer during the rewrite.
368 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000369 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000370 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
371 // declared in <Foundation/NSString.h>
372 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
373 ConstantStringClassReference = FVD;
374 return;
375 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000377 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000379 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000380 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000381 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000382 } else if (ObjCForwardProtocolDecl *FP =
383 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000384 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000385 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000386 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000387 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
388 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000389}
390
Chris Lattnerf04da132007-10-24 17:06:59 +0000391/// HandleDeclInMainFile - This is called for each top-level decl defined in the
392/// main file of the input.
393void RewriteTest::HandleDeclInMainFile(Decl *D) {
394 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
395 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000396 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000397
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000398 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000399 if (Stmt *Body = MD->getBody()) {
400 //Body->dump();
401 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000402 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000403 CurMethodDecl = 0;
404 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000405 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000406 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000407 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000408 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000409 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000411 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000412 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000413 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000414 if (VD->getInit())
415 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
416 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000417 // Nothing yet.
418}
419
420RewriteTest::~RewriteTest() {
421 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000422
423 // Rewrite tabs if we care.
424 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000425
Steve Naroffa7b402d2008-03-28 22:26:09 +0000426 if (Diags.hasErrorOccurred())
427 return;
428
429 // Create the output file.
430
431 std::ostream *OutFile;
432 if (OutFileName == "-") {
433 OutFile = llvm::cout.stream();
434 } else if (!OutFileName.empty()) {
435 OutFile = new std::ofstream(OutFileName.c_str(),
436 std::ios_base::binary|std::ios_base::out);
437 } else if (InFileName == "-") {
438 OutFile = llvm::cout.stream();
439 } else {
440 llvm::sys::Path Path(InFileName);
441 Path.eraseSuffix();
442 Path.appendSuffix("cpp");
443 OutFile = new std::ofstream(Path.toString().c_str(),
444 std::ios_base::binary|std::ios_base::out);
445 }
446
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000447 RewriteInclude();
448
Steve Naroffba92b2e2008-03-27 22:29:16 +0000449 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
450 Preamble.c_str(), Preamble.size(), false);
451
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000452 // Rewrite Objective-c meta data*
453 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000454 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000455
Chris Lattnerf04da132007-10-24 17:06:59 +0000456 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
457 // we are done.
458 if (const RewriteBuffer *RewriteBuf =
459 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000460 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000461 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000462 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000463 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000464 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000465 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000466 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000467}
468
Chris Lattnerf04da132007-10-24 17:06:59 +0000469//===----------------------------------------------------------------------===//
470// Syntactic (non-AST) Rewriting Code
471//===----------------------------------------------------------------------===//
472
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000473void RewriteTest::RewriteInclude() {
474 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
475 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
476 const char *MainBufStart = MainBuf.first;
477 const char *MainBufEnd = MainBuf.second;
478 size_t ImportLen = strlen("import");
479 size_t IncludeLen = strlen("include");
480
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000481 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000482 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
483 if (*BufPtr == '#') {
484 if (++BufPtr == MainBufEnd)
485 return;
486 while (*BufPtr == ' ' || *BufPtr == '\t')
487 if (++BufPtr == MainBufEnd)
488 return;
489 if (!strncmp(BufPtr, "import", ImportLen)) {
490 // replace import with include
491 SourceLocation ImportLoc =
492 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000493 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000494 BufPtr += ImportLen;
495 }
496 }
497 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000498}
499
Chris Lattnerf04da132007-10-24 17:06:59 +0000500void RewriteTest::RewriteTabs() {
501 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
502 const char *MainBufStart = MainBuf.first;
503 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000504
Chris Lattnerf04da132007-10-24 17:06:59 +0000505 // Loop over the whole file, looking for tabs.
506 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
507 if (*BufPtr != '\t')
508 continue;
509
510 // Okay, we found a tab. This tab will turn into at least one character,
511 // but it depends on which 'virtual column' it is in. Compute that now.
512 unsigned VCol = 0;
513 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
514 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
515 ++VCol;
516
517 // Okay, now that we know the virtual column, we know how many spaces to
518 // insert. We assume 8-character tab-stops.
519 unsigned Spaces = 8-(VCol & 7);
520
521 // Get the location of the tab.
522 SourceLocation TabLoc =
523 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
524
525 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000526 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000527 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000528}
529
530
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000531void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000532 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000533 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000534
535 // Get the start location and compute the semi location.
536 SourceLocation startLoc = ClassDecl->getLocation();
537 const char *startBuf = SM->getCharacterData(startLoc);
538 const char *semiPtr = strchr(startBuf, ';');
539
540 // Translate to typedef's that forward reference structs with the same name
541 // as the class. As a convenience, we include the original declaration
542 // as a comment.
543 std::string typedefString;
544 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000545 typedefString.append(startBuf, semiPtr-startBuf+1);
546 typedefString += "\n";
547 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000549 typedefString += "#ifndef _REWRITER_typedef_";
550 typedefString += ForwardDecl->getName();
551 typedefString += "\n";
552 typedefString += "#define _REWRITER_typedef_";
553 typedefString += ForwardDecl->getName();
554 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000555 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000556 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000557 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000558 }
559
560 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000561 ReplaceText(startLoc, semiPtr-startBuf+1,
562 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000563}
564
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000565void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000566 SourceLocation LocStart = Method->getLocStart();
567 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000568
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000569 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000570 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000571 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000572 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000573 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000574 }
575}
576
Chris Lattner55d13b42008-03-16 21:23:50 +0000577void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000578{
Chris Lattner55d13b42008-03-16 21:23:50 +0000579 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000581 SourceLocation Loc = Property->getLocation();
582
Chris Lattneraadaf782008-01-31 19:51:04 +0000583 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000584
585 // FIXME: handle properties that are declared across multiple lines.
586 }
587}
588
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000590 SourceLocation LocStart = CatDecl->getLocStart();
591
592 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000593 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000594
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000596 E = CatDecl->instmeth_end(); I != E; ++I)
597 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000598 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000599 E = CatDecl->classmeth_end(); I != E; ++I)
600 RewriteMethodDeclaration(*I);
601
Steve Naroff423cb562007-10-30 13:30:57 +0000602 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000603 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000604}
605
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000606void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000607 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000608
Steve Naroff752d6ef2007-10-30 16:42:30 +0000609 SourceLocation LocStart = PDecl->getLocStart();
610
611 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000612 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000613
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000614 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000615 E = PDecl->instmeth_end(); I != E; ++I)
616 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000617 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000618 E = PDecl->classmeth_end(); I != E; ++I)
619 RewriteMethodDeclaration(*I);
620
Steve Naroff752d6ef2007-10-30 16:42:30 +0000621 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000622 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000623 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000624
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000625 // Must comment out @optional/@required
626 const char *startBuf = SM->getCharacterData(LocStart);
627 const char *endBuf = SM->getCharacterData(LocEnd);
628 for (const char *p = startBuf; p < endBuf; p++) {
629 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
630 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000631 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000632 ReplaceText(OptionalLoc, strlen("@optional"),
633 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000634
635 }
636 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
637 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000638 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000639 ReplaceText(OptionalLoc, strlen("@required"),
640 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000641
642 }
643 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000644}
645
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000646void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000647 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000648 if (LocStart.isInvalid())
649 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000650 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000652}
653
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000654void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000655 std::string &ResultStr) {
656 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000658 ResultStr += "id";
659 else
660 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000661 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000662
663 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000664 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000665
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000666 if (OMD->isInstance())
667 NameStr += "_I_";
668 else
669 NameStr += "_C_";
670
671 NameStr += OMD->getClassInterface()->getName();
672 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000673
674 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 if (ObjCCategoryImplDecl *CID =
676 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000677 NameStr += CID->getName();
678 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 }
Steve Naroff563b8282008-04-04 22:23:44 +0000680 // Append selector names, replacing ':' with '_'
681 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000682 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000683 else {
684 std::string selString = OMD->getSelector().getName();
685 int len = selString.size();
686 for (int i = 0; i < len; i++)
687 if (selString[i] == ':')
688 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000689 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000691 // Remember this name for metadata emission
692 MethodInternalNames[OMD] = NameStr;
693 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000694
695 // Rewrite arguments
696 ResultStr += "(";
697
698 // invisible arguments
699 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000701 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000702 if (!LangOpts.Microsoft) {
703 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
704 ResultStr += "struct ";
705 }
706 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000707 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000708 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000709 }
710 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000712
713 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 ResultStr += " _cmd";
716
717 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000718 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 ParmVarDecl *PDecl = OMD->getParamDecl(i);
720 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000721 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000722 ResultStr += "id";
723 else
724 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000725 ResultStr += " ";
726 ResultStr += PDecl->getName();
727 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000728 if (OMD->isVariadic())
729 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000730 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000731
732}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000733void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
735 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000736
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000737 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000738 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000739 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000740 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000743 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
744 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000745 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCMethodDecl *OMD = *I;
747 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000748 SourceLocation LocStart = OMD->getLocStart();
749 SourceLocation LocEnd = OMD->getBody()->getLocStart();
750
751 const char *startBuf = SM->getCharacterData(LocStart);
752 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000753 ReplaceText(LocStart, endBuf-startBuf,
754 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 }
756
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000757 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000758 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
759 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000760 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000761 ObjCMethodDecl *OMD = *I;
762 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000763 SourceLocation LocStart = OMD->getLocStart();
764 SourceLocation LocEnd = OMD->getBody()->getLocStart();
765
766 const char *startBuf = SM->getCharacterData(LocStart);
767 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000768 ReplaceText(LocStart, endBuf-startBuf,
769 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000771 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000773 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000774 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000775}
776
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000777void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000778 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000780 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000781 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000782 ResultStr += ClassDecl->getName();
783 ResultStr += "\n";
784 ResultStr += "#define _REWRITER_typedef_";
785 ResultStr += ClassDecl->getName();
786 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000787 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000788 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000789 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000790 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000791 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000792 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000794
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000795 RewriteProperties(ClassDecl->getNumPropertyDecl(),
796 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = ClassDecl->instmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000801 E = ClassDecl->classmeth_end(); I != E; ++I)
802 RewriteMethodDeclaration(*I);
803
Steve Naroff2feac5e2007-10-30 03:43:13 +0000804 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000806}
807
Steve Naroff7e3411b2007-11-15 02:58:25 +0000808Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000809 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000810 if (CurMethodDecl) {
811 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
812 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
813 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000814 // lookup which class implements the instance variable.
815 ObjCInterfaceDecl *clsDeclared = 0;
816 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
817 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000818
819 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000820 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000821 RecName += "_IMPL";
822 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattner0ed844b2008-04-04 06:12:32 +0000823 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000824 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000825 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
826 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
827 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
828 // Don't forget the parens to enforce the proper binding.
829 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
830 if (IV->isFreeIvar()) {
831 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
832 ReplaceStmt(IV, ME);
833 delete IV;
834 return ME;
835 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000836 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000837 // Cannot delete IV->getBase(), since PE points to it.
838 // Replace the old base with the cast. This is important when doing
839 // embedded rewrites. For example, [newInv->_container addObject:0].
840 IV->setBase(PE);
841 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000842 }
843 }
844 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000845 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000846 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000847 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
848 IV->getLocation(), D->getType());
849 ReplaceStmt(IV, Replacement);
850 delete IV;
851 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000852}
853
Chris Lattnerf04da132007-10-24 17:06:59 +0000854//===----------------------------------------------------------------------===//
855// Function Body / Expression rewriting
856//===----------------------------------------------------------------------===//
857
Steve Narofff3473a72007-11-09 15:20:18 +0000858Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000859 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
860 isa<DoStmt>(S) || isa<ForStmt>(S))
861 Stmts.push_back(S);
862 else if (isa<ObjCForCollectionStmt>(S)) {
863 Stmts.push_back(S);
864 ObjCBcLabelNo.push_back(++BcLabelCount);
865 }
866
Chris Lattner338d1e22008-01-31 05:10:40 +0000867 SourceLocation OrigStmtEnd = S->getLocEnd();
868
869 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000870 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
871 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000872 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000873 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000874 if (newStmt)
875 *CI = newStmt;
876 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000877
878 // Handle specific things.
879 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
880 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000881
882 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
883 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000884
885 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
886 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000887
Steve Naroffbeaf2992007-11-03 11:27:19 +0000888 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
889 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000890
Steve Naroff934f2762007-10-24 22:48:43 +0000891 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
892 // Before we rewrite it, put the original message expression in a comment.
893 SourceLocation startLoc = MessExpr->getLocStart();
894 SourceLocation endLoc = MessExpr->getLocEnd();
895
896 const char *startBuf = SM->getCharacterData(startLoc);
897 const char *endBuf = SM->getCharacterData(endLoc);
898
899 std::string messString;
900 messString += "// ";
901 messString.append(startBuf, endBuf-startBuf+1);
902 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000903
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000904 // FIXME: Missing definition of
905 // InsertText(clang::SourceLocation, char const*, unsigned int).
906 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000907 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000908 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000909 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000910 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000911
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000912 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
913 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000914
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000915 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
916 return RewriteObjCSynchronizedStmt(StmtTry);
917
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000918 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
919 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000920
921 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
922 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000923
924 if (ObjCForCollectionStmt *StmtForCollection =
925 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000926 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000927 if (BreakStmt *StmtBreakStmt =
928 dyn_cast<BreakStmt>(S))
929 return RewriteBreakStmt(StmtBreakStmt);
930 if (ContinueStmt *StmtContinueStmt =
931 dyn_cast<ContinueStmt>(S))
932 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000933
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000934 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
935 isa<DoStmt>(S) || isa<ForStmt>(S)) {
936 assert(!Stmts.empty() && "Statement stack is empty");
937 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
938 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
939 && "Statement stack mismatch");
940 Stmts.pop_back();
941 }
Steve Naroff874e2322007-11-15 10:28:18 +0000942#if 0
943 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
944 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
945 // Get the new text.
946 std::ostringstream Buf;
947 Replacement->printPretty(Buf);
948 const std::string &Str = Buf.str();
949
950 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000951 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000952 delete S;
953 return Replacement;
954 }
955#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000956 // Return this stmt unmodified.
957 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000958}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000959
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000960/// SynthCountByEnumWithState - To print:
961/// ((unsigned int (*)
962/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
963/// (void *)objc_msgSend)((id)l_collection,
964/// sel_registerName(
965/// "countByEnumeratingWithState:objects:count:"),
966/// &enumState,
967/// (id *)items, (unsigned int)16)
968///
969void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
970 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
971 "id *, unsigned int))(void *)objc_msgSend)";
972 buf += "\n\t\t";
973 buf += "((id)l_collection,\n\t\t";
974 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
975 buf += "\n\t\t";
976 buf += "&enumState, "
977 "(id *)items, (unsigned int)16)";
978}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000979
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000980/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
981/// statement to exit to its outer synthesized loop.
982///
983Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
984 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
985 return S;
986 // replace break with goto __break_label
987 std::string buf;
988
989 SourceLocation startLoc = S->getLocStart();
990 buf = "goto __break_label_";
991 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000992 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000993
994 return 0;
995}
996
997/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
998/// statement to continue with its inner synthesized loop.
999///
1000Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
1001 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1002 return S;
1003 // replace continue with goto __continue_label
1004 std::string buf;
1005
1006 SourceLocation startLoc = S->getLocStart();
1007 buf = "goto __continue_label_";
1008 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001009 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001010
1011 return 0;
1012}
1013
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001014/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001015/// It rewrites:
1016/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001017
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001018/// Into:
1019/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001020/// type elem;
1021/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001022/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023/// id l_collection = (id)collection;
1024/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1025/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001026/// if (limit) {
1027/// unsigned long startMutations = *enumState.mutationsPtr;
1028/// do {
1029/// unsigned long counter = 0;
1030/// do {
1031/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001032/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001033/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001034/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001035/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001036/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001037/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1038/// objects:items count:16]);
1039/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001040/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001041/// }
1042/// else
1043/// elem = nil;
1044/// }
1045///
Chris Lattner338d1e22008-01-31 05:10:40 +00001046Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1047 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001048 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1049 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1050 "ObjCForCollectionStmt Statement stack mismatch");
1051 assert(!ObjCBcLabelNo.empty() &&
1052 "ObjCForCollectionStmt - Label No stack empty");
1053
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001056 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001057 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058 std::string buf;
1059 buf = "\n{\n\t";
1060 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1061 // type elem;
1062 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001063 elementTypeAsString = ElementType.getAsString();
1064 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001065 buf += " ";
1066 elementName = DS->getDecl()->getName();
1067 buf += elementName;
1068 buf += ";\n\t";
1069 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001070 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001071 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001072 elementTypeAsString = DR->getDecl()->getType().getAsString();
1073 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001074 else
1075 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1076
1077 // struct __objcFastEnumerationState enumState = { 0 };
1078 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1079 // id items[16];
1080 buf += "id items[16];\n\t";
1081 // id l_collection = (id)
1082 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001083 // Find start location of 'collection' the hard way!
1084 const char *startCollectionBuf = startBuf;
1085 startCollectionBuf += 3; // skip 'for'
1086 startCollectionBuf = strchr(startCollectionBuf, '(');
1087 startCollectionBuf++; // skip '('
1088 // find 'in' and skip it.
1089 while (*startCollectionBuf != ' ' ||
1090 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1091 (*(startCollectionBuf+3) != ' ' &&
1092 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1093 startCollectionBuf++;
1094 startCollectionBuf += 3;
1095
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001096 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001097 ReplaceText(startLoc, startCollectionBuf - startBuf,
1098 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001099 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001100 SourceLocation rightParenLoc = S->getRParenLoc();
1101 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1102 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 buf = ";\n\t";
1104
1105 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1106 // objects:items count:16];
1107 // which is synthesized into:
1108 // unsigned int limit =
1109 // ((unsigned int (*)
1110 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1111 // (void *)objc_msgSend)((id)l_collection,
1112 // sel_registerName(
1113 // "countByEnumeratingWithState:objects:count:"),
1114 // (struct __objcFastEnumerationState *)&state,
1115 // (id *)items, (unsigned int)16);
1116 buf += "unsigned long limit =\n\t\t";
1117 SynthCountByEnumWithState(buf);
1118 buf += ";\n\t";
1119 /// if (limit) {
1120 /// unsigned long startMutations = *enumState.mutationsPtr;
1121 /// do {
1122 /// unsigned long counter = 0;
1123 /// do {
1124 /// if (startMutations != *enumState.mutationsPtr)
1125 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001126 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127 buf += "if (limit) {\n\t";
1128 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1129 buf += "do {\n\t\t";
1130 buf += "unsigned long counter = 0;\n\t\t";
1131 buf += "do {\n\t\t\t";
1132 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1133 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1134 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001135 buf += " = (";
1136 buf += elementTypeAsString;
1137 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001138 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001139 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001140
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001141 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001142 /// } while (counter < limit);
1143 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1144 /// objects:items count:16]);
1145 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001146 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001147 /// }
1148 /// else
1149 /// elem = nil;
1150 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001151 ///
1152 buf = ";\n\t";
1153 buf += "__continue_label_";
1154 buf += utostr(ObjCBcLabelNo.back());
1155 buf += ": ;";
1156 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001157 buf += "} while (counter < limit);\n\t";
1158 buf += "} while (limit = ";
1159 SynthCountByEnumWithState(buf);
1160 buf += ");\n\t";
1161 buf += elementName;
1162 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001163 buf += "__break_label_";
1164 buf += utostr(ObjCBcLabelNo.back());
1165 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001166 buf += "}\n\t";
1167 buf += "else\n\t\t";
1168 buf += elementName;
1169 buf += " = nil;\n";
1170 buf += "}\n";
1171 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001172 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001173 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001174 Stmts.pop_back();
1175 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001176 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001177}
1178
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001179/// RewriteObjCSynchronizedStmt -
1180/// This routine rewrites @synchronized(expr) stmt;
1181/// into:
1182/// objc_sync_enter(expr);
1183/// @try stmt @finally { objc_sync_exit(expr); }
1184///
1185Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1186 // Get the start location and compute the semi location.
1187 SourceLocation startLoc = S->getLocStart();
1188 const char *startBuf = SM->getCharacterData(startLoc);
1189
1190 assert((*startBuf == '@') && "bogus @synchronized location");
1191
1192 std::string buf;
1193 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001194 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001195 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1196 const char *endBuf = SM->getCharacterData(endLoc);
1197 endBuf++;
1198 const char *rparenBuf = strchr(endBuf, ')');
1199 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1200 buf = ");\n";
1201 // declare a new scope with two variables, _stack and _rethrow.
1202 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1203 buf += "int buf[18/*32-bit i386*/];\n";
1204 buf += "char *pointers[4];} _stack;\n";
1205 buf += "id volatile _rethrow = 0;\n";
1206 buf += "objc_exception_try_enter(&_stack);\n";
1207 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001208 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001209 startLoc = S->getSynchBody()->getLocEnd();
1210 startBuf = SM->getCharacterData(startLoc);
1211
1212 assert((*startBuf == '}') && "bogus @try block");
1213 SourceLocation lastCurlyLoc = startLoc;
1214 buf = "}\nelse {\n";
1215 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1216 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1217 // FIXME: This must be objc_sync_exit(syncExpr);
1218 buf += " objc_sync_exit();\n";
1219 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1220 buf += "}\n";
1221 buf += "}";
1222
Chris Lattneraadaf782008-01-31 19:51:04 +00001223 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001224 return 0;
1225}
1226
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001227Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001228 // Get the start location and compute the semi location.
1229 SourceLocation startLoc = S->getLocStart();
1230 const char *startBuf = SM->getCharacterData(startLoc);
1231
1232 assert((*startBuf == '@') && "bogus @try location");
1233
1234 std::string buf;
1235 // declare a new scope with two variables, _stack and _rethrow.
1236 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1237 buf += "int buf[18/*32-bit i386*/];\n";
1238 buf += "char *pointers[4];} _stack;\n";
1239 buf += "id volatile _rethrow = 0;\n";
1240 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001241 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001242
Chris Lattneraadaf782008-01-31 19:51:04 +00001243 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001244
1245 startLoc = S->getTryBody()->getLocEnd();
1246 startBuf = SM->getCharacterData(startLoc);
1247
1248 assert((*startBuf == '}') && "bogus @try block");
1249
1250 SourceLocation lastCurlyLoc = startLoc;
1251
1252 startLoc = startLoc.getFileLocWithOffset(1);
1253 buf = " /* @catch begin */ else {\n";
1254 buf += " id _caught = objc_exception_extract(&_stack);\n";
1255 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001256 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001257 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1258 buf += " else { /* @catch continue */";
1259
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001260 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001261
1262 bool sawIdTypedCatch = false;
1263 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001264 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001265 while (catchList) {
1266 Stmt *catchStmt = catchList->getCatchParamStmt();
1267
1268 if (catchList == S->getCatchStmts())
1269 buf = "if ("; // we are generating code for the first catch clause
1270 else
1271 buf = "else if (";
1272 startLoc = catchList->getLocStart();
1273 startBuf = SM->getCharacterData(startLoc);
1274
1275 assert((*startBuf == '@') && "bogus @catch location");
1276
1277 const char *lParenLoc = strchr(startBuf, '(');
1278
Steve Naroffbe4b3332008-02-01 22:08:12 +00001279 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001280 // Now rewrite the body...
1281 lastCatchBody = catchList->getCatchBody();
1282 SourceLocation rParenLoc = catchList->getRParenLoc();
1283 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1284 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1285 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1286 assert((*rParenBuf == ')') && "bogus @catch paren location");
1287 assert((*bodyBuf == '{') && "bogus @catch body location");
1288
1289 buf += "1) { id _tmp = _caught;";
1290 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1291 buf.c_str(), buf.size());
1292 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001293 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001294 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001295 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001296 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001297 sawIdTypedCatch = true;
1298 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001299 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001300
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001301 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001302 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001303 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001304 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001305 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001306 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001307 }
1308 }
1309 // Now rewrite the body...
1310 lastCatchBody = catchList->getCatchBody();
1311 SourceLocation rParenLoc = catchList->getRParenLoc();
1312 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1313 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1314 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1315 assert((*rParenBuf == ')') && "bogus @catch paren location");
1316 assert((*bodyBuf == '{') && "bogus @catch body location");
1317
1318 buf = " = _caught;";
1319 // Here we replace ") {" with "= _caught;" (which initializes and
1320 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001321 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001322 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001323 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001324 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001325 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001326 catchList = catchList->getNextCatchStmt();
1327 }
1328 // Complete the catch list...
1329 if (lastCatchBody) {
1330 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1331 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1332 assert((*bodyBuf == '}') && "bogus @catch body location");
1333 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1334 buf = " } } /* @catch end */\n";
1335
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001336 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001337
1338 // Set lastCurlyLoc
1339 lastCurlyLoc = lastCatchBody->getLocEnd();
1340 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001341 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001342 startLoc = finalStmt->getLocStart();
1343 startBuf = SM->getCharacterData(startLoc);
1344 assert((*startBuf == '@') && "bogus @finally start");
1345
1346 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001347 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001348
1349 Stmt *body = finalStmt->getFinallyBody();
1350 SourceLocation startLoc = body->getLocStart();
1351 SourceLocation endLoc = body->getLocEnd();
1352 const char *startBuf = SM->getCharacterData(startLoc);
1353 const char *endBuf = SM->getCharacterData(endLoc);
1354 assert((*startBuf == '{') && "bogus @finally body location");
1355 assert((*endBuf == '}') && "bogus @finally body location");
1356
1357 startLoc = startLoc.getFileLocWithOffset(1);
1358 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001359 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001360 endLoc = endLoc.getFileLocWithOffset(-1);
1361 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001362 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001363
1364 // Set lastCurlyLoc
1365 lastCurlyLoc = body->getLocEnd();
1366 }
1367 // Now emit the final closing curly brace...
1368 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1369 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001370 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001371 return 0;
1372}
1373
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001374Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001375 return 0;
1376}
1377
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001378Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001379 return 0;
1380}
1381
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001382// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001383// the throw expression is typically a message expression that's already
1384// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001385Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001386 // Get the start location and compute the semi location.
1387 SourceLocation startLoc = S->getLocStart();
1388 const char *startBuf = SM->getCharacterData(startLoc);
1389
1390 assert((*startBuf == '@') && "bogus @throw location");
1391
1392 std::string buf;
1393 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001394 if (S->getThrowExpr())
1395 buf = "objc_exception_throw(";
1396 else // add an implicit argument
1397 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001398 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001399 const char *semiBuf = strchr(startBuf, ';');
1400 assert((*semiBuf == ';') && "@throw: can't find ';'");
1401 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1402 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001403 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001404 return 0;
1405}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001406
Chris Lattnere64b7772007-10-24 16:57:36 +00001407Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001408 // Create a new string expression.
1409 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001410 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001411 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1412 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001413 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1414 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001415 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001416 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001417
Chris Lattner07506182007-11-30 22:53:43 +00001418 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001419 delete Exp;
1420 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001421}
1422
Steve Naroffb42f8412007-11-05 14:50:49 +00001423Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1424 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1425 // Create a call to sel_registerName("selName").
1426 llvm::SmallVector<Expr*, 8> SelExprs;
1427 QualType argType = Context->getPointerType(Context->CharTy);
1428 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1429 Exp->getSelector().getName().size(),
1430 false, argType, SourceLocation(),
1431 SourceLocation()));
1432 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1433 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001434 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001435 delete Exp;
1436 return SelExp;
1437}
1438
Steve Naroff934f2762007-10-24 22:48:43 +00001439CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1440 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001441 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001442 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001443
1444 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001445 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001446
1447 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001448 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001449 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1450
1451 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001452
Steve Naroff934f2762007-10-24 22:48:43 +00001453 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1454}
1455
Steve Naroffd5255f52007-11-01 13:24:47 +00001456static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1457 const char *&startRef, const char *&endRef) {
1458 while (startBuf < endBuf) {
1459 if (*startBuf == '<')
1460 startRef = startBuf; // mark the start.
1461 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001462 if (startRef && *startRef == '<') {
1463 endRef = startBuf; // mark the end.
1464 return true;
1465 }
1466 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001467 }
1468 startBuf++;
1469 }
1470 return false;
1471}
1472
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001473static void scanToNextArgument(const char *&argRef) {
1474 int angle = 0;
1475 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1476 if (*argRef == '<')
1477 angle++;
1478 else if (*argRef == '>')
1479 angle--;
1480 argRef++;
1481 }
1482 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1483}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001484
Steve Naroffd5255f52007-11-01 13:24:47 +00001485bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001486
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001487 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001488 return true;
1489
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001490 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001491 return true;
1492
Steve Naroffd5255f52007-11-01 13:24:47 +00001493 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001494 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001495 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001496 return true; // we have "Class <Protocol> *".
1497 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001498 return false;
1499}
1500
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001501void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001502 SourceLocation Loc;
1503 QualType Type;
1504 const FunctionTypeProto *proto = 0;
1505 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1506 Loc = VD->getLocation();
1507 Type = VD->getType();
1508 }
1509 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1510 Loc = FD->getLocation();
1511 // Check for ObjC 'id' and class types that have been adorned with protocol
1512 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1513 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1514 assert(funcType && "missing function type");
1515 proto = dyn_cast<FunctionTypeProto>(funcType);
1516 if (!proto)
1517 return;
1518 Type = proto->getResultType();
1519 }
1520 else
1521 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001522
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001523 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001524 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001525
1526 const char *endBuf = SM->getCharacterData(Loc);
1527 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001528 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001529 startBuf--; // scan backward (from the decl location) for return type.
1530 const char *startRef = 0, *endRef = 0;
1531 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1532 // Get the locations of the startRef, endRef.
1533 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1534 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1535 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001536 InsertText(LessLoc, "/*", 2);
1537 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001538 }
1539 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001540 if (!proto)
1541 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001542 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001543 const char *startBuf = SM->getCharacterData(Loc);
1544 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001545 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1546 if (needToScanForQualifiers(proto->getArgType(i))) {
1547 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001548
Steve Naroffd5255f52007-11-01 13:24:47 +00001549 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001550 // scan forward (from the decl location) for argument types.
1551 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001552 const char *startRef = 0, *endRef = 0;
1553 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1554 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001555 SourceLocation LessLoc =
1556 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1557 SourceLocation GreaterLoc =
1558 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001559 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001560 InsertText(LessLoc, "/*", 2);
1561 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001562 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001563 startBuf = ++endBuf;
1564 }
1565 else {
1566 while (*startBuf != ')' && *startBuf != ',')
1567 startBuf++; // scan forward (from the decl location) for argument types.
1568 startBuf++;
1569 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001570 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001571}
1572
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001573// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1574void RewriteTest::SynthSelGetUidFunctionDecl() {
1575 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1576 llvm::SmallVector<QualType, 16> ArgTys;
1577 ArgTys.push_back(Context->getPointerType(
1578 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001579 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001580 &ArgTys[0], ArgTys.size(),
1581 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001582 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, NULL,
1583 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001584 SelGetUidIdent, getFuncType,
1585 FunctionDecl::Extern, false, 0);
1586}
1587
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001588// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1589void RewriteTest::SynthGetProtocolFunctionDecl() {
1590 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1591 llvm::SmallVector<QualType, 16> ArgTys;
1592 ArgTys.push_back(Context->getPointerType(
1593 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001594 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001595 &ArgTys[0], ArgTys.size(),
1596 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001597 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, NULL,
1598 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001599 SelGetProtoIdent, getFuncType,
1600 FunctionDecl::Extern, false, 0);
1601}
1602
Steve Naroff09b266e2007-10-30 23:14:51 +00001603void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1604 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001605 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001606 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001607 return;
1608 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001609 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001610}
1611
Steve Naroffc0a123c2008-03-11 17:37:02 +00001612// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1613void RewriteTest::SynthSuperContructorFunctionDecl() {
1614 if (SuperContructorFunctionDecl)
1615 return;
1616 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1617 llvm::SmallVector<QualType, 16> ArgTys;
1618 QualType argT = Context->getObjCIdType();
1619 assert(!argT.isNull() && "Can't find 'id' type");
1620 ArgTys.push_back(argT);
1621 ArgTys.push_back(argT);
1622 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1623 &ArgTys[0], ArgTys.size(),
1624 false);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001625 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, NULL,
1626 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001627 msgSendIdent, msgSendType,
1628 FunctionDecl::Extern, false, 0);
1629}
1630
Steve Naroff09b266e2007-10-30 23:14:51 +00001631// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1632void RewriteTest::SynthMsgSendFunctionDecl() {
1633 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1634 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001635 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001636 assert(!argT.isNull() && "Can't find 'id' type");
1637 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001638 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001639 assert(!argT.isNull() && "Can't find 'SEL' type");
1640 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001641 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001642 &ArgTys[0], ArgTys.size(),
1643 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001644 MsgSendFunctionDecl = FunctionDecl::Create(*Context, NULL,
1645 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001646 msgSendIdent, msgSendType,
1647 FunctionDecl::Extern, false, 0);
1648}
1649
Steve Naroff874e2322007-11-15 10:28:18 +00001650// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1651void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1652 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1653 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001654 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1655 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001656 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001657 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1658 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1659 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001660 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001661 assert(!argT.isNull() && "Can't find 'SEL' type");
1662 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001663 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001664 &ArgTys[0], ArgTys.size(),
1665 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001666 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, NULL,
1667 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001668 msgSendIdent, msgSendType,
1669 FunctionDecl::Extern, false, 0);
1670}
1671
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001672// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1673void RewriteTest::SynthMsgSendStretFunctionDecl() {
1674 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1675 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001676 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001677 assert(!argT.isNull() && "Can't find 'id' type");
1678 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001679 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001680 assert(!argT.isNull() && "Can't find 'SEL' type");
1681 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001682 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001683 &ArgTys[0], ArgTys.size(),
1684 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001685 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1686 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001687 msgSendIdent, msgSendType,
1688 FunctionDecl::Extern, false, 0);
1689}
1690
1691// SynthMsgSendSuperStretFunctionDecl -
1692// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1693void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1694 IdentifierInfo *msgSendIdent =
1695 &Context->Idents.get("objc_msgSendSuper_stret");
1696 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001697 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1698 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001699 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001700 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1701 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1702 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001703 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001704 assert(!argT.isNull() && "Can't find 'SEL' type");
1705 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001707 &ArgTys[0], ArgTys.size(),
1708 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001709 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001710 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001711 msgSendIdent, msgSendType,
1712 FunctionDecl::Extern, false, 0);
1713}
1714
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001715// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1716void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1717 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1718 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001719 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001720 assert(!argT.isNull() && "Can't find 'id' type");
1721 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001722 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001723 assert(!argT.isNull() && "Can't find 'SEL' type");
1724 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001725 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001726 &ArgTys[0], ArgTys.size(),
1727 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001728 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1729 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001730 msgSendIdent, msgSendType,
1731 FunctionDecl::Extern, false, 0);
1732}
1733
Steve Naroff09b266e2007-10-30 23:14:51 +00001734// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1735void RewriteTest::SynthGetClassFunctionDecl() {
1736 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1737 llvm::SmallVector<QualType, 16> ArgTys;
1738 ArgTys.push_back(Context->getPointerType(
1739 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001740 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001741 &ArgTys[0], ArgTys.size(),
1742 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001743 GetClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1744 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001745 getClassIdent, getClassType,
1746 FunctionDecl::Extern, false, 0);
1747}
1748
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001749// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1750void RewriteTest::SynthGetMetaClassFunctionDecl() {
1751 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1752 llvm::SmallVector<QualType, 16> ArgTys;
1753 ArgTys.push_back(Context->getPointerType(
1754 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001755 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001756 &ArgTys[0], ArgTys.size(),
1757 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001758 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1759 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001760 getClassIdent, getClassType,
1761 FunctionDecl::Extern, false, 0);
1762}
1763
Steve Naroffbeaf2992007-11-03 11:27:19 +00001764Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001765 QualType strType = getConstantStringStructType();
1766
1767 std::string S = "__NSConstantStringImpl_";
1768 S += utostr(NumObjCStringLiterals++);
1769
Steve Naroffba92b2e2008-03-27 22:29:16 +00001770 Preamble += "static __NSConstantStringImpl " + S;
1771 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1772 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001773 // The pretty printer for StringLiteral handles escape characters properly.
1774 std::ostringstream prettyBuf;
1775 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001776 Preamble += prettyBuf.str();
1777 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001778 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001779 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001780
Chris Lattner0ed844b2008-04-04 06:12:32 +00001781 FileVarDecl *NewVD = FileVarDecl::Create(*Context, NULL, SourceLocation(),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001782 &Context->Idents.get(S.c_str()), strType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001783 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001784 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1785 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1786 Context->getPointerType(DRE->getType()),
1787 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001788 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001789 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001790 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001791 delete Exp;
1792 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001793}
1794
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001795ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001796 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001797 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1798
1799 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1800 if (!CE) return 0;
1801
1802 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1803 if (!DRE) return 0;
1804
1805 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1806 if (!PVD) return 0;
1807
1808 if (strcmp(PVD->getName(), "self") != 0)
1809 return 0;
1810
1811 // is this id<P1..> type?
1812 if (CE->getType()->isObjCQualifiedIdType())
1813 return 0;
1814 const PointerType *PT = CE->getType()->getAsPointerType();
1815 if (!PT) return 0;
1816
1817 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1818 if (!IT) return 0;
1819
1820 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1821 return 0;
1822
1823 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001824}
1825
1826// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1827QualType RewriteTest::getSuperStructType() {
1828 if (!SuperStructDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001829 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001830 SourceLocation(),
1831 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001832 QualType FieldTypes[2];
1833
1834 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001835 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001836 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001837 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001838 // Create fields
1839 FieldDecl *FieldDecls[2];
1840
1841 for (unsigned i = 0; i < 2; ++i)
Chris Lattner0ed844b2008-04-04 06:12:32 +00001842 FieldDecls[i] = FieldDecl::Create(*Context, SuperStructDecl,
1843 SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001844 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001845
1846 SuperStructDecl->defineBody(FieldDecls, 4);
1847 }
1848 return Context->getTagDeclType(SuperStructDecl);
1849}
1850
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001851QualType RewriteTest::getConstantStringStructType() {
1852 if (!ConstantStringDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001853 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001854 SourceLocation(),
1855 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001856 QualType FieldTypes[4];
1857
1858 // struct objc_object *receiver;
1859 FieldTypes[0] = Context->getObjCIdType();
1860 // int flags;
1861 FieldTypes[1] = Context->IntTy;
1862 // char *str;
1863 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1864 // long length;
1865 FieldTypes[3] = Context->LongTy;
1866 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001867 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001868
1869 for (unsigned i = 0; i < 4; ++i)
Chris Lattner0ed844b2008-04-04 06:12:32 +00001870 FieldDecls[i] = FieldDecl::Create(*Context, ConstantStringDecl,
1871 SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001872 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001873
1874 ConstantStringDecl->defineBody(FieldDecls, 4);
1875 }
1876 return Context->getTagDeclType(ConstantStringDecl);
1877}
1878
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001879Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001880 if (!SelGetUidFunctionDecl)
1881 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001882 if (!MsgSendFunctionDecl)
1883 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001884 if (!MsgSendSuperFunctionDecl)
1885 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001886 if (!MsgSendStretFunctionDecl)
1887 SynthMsgSendStretFunctionDecl();
1888 if (!MsgSendSuperStretFunctionDecl)
1889 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001890 if (!MsgSendFpretFunctionDecl)
1891 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001892 if (!GetClassFunctionDecl)
1893 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001894 if (!GetMetaClassFunctionDecl)
1895 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001896
Steve Naroff874e2322007-11-15 10:28:18 +00001897 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001898 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1899 // May need to use objc_msgSend_stret() as well.
1900 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001901 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001902 QualType resultType = mDecl->getResultType();
1903 if (resultType.getCanonicalType()->isStructureType()
1904 || resultType.getCanonicalType()->isUnionType())
1905 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001906 else if (resultType.getCanonicalType()->isRealFloatingType())
1907 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001908 }
Steve Naroff874e2322007-11-15 10:28:18 +00001909
Steve Naroff934f2762007-10-24 22:48:43 +00001910 // Synthesize a call to objc_msgSend().
1911 llvm::SmallVector<Expr*, 8> MsgExprs;
1912 IdentifierInfo *clsName = Exp->getClassName();
1913
1914 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1915 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001916 if (!strcmp(clsName->getName(), "super")) {
1917 MsgSendFlavor = MsgSendSuperFunctionDecl;
1918 if (MsgSendStretFlavor)
1919 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1920 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1921
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001922 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001923 CurMethodDecl->getClassInterface()->getSuperClass();
1924
1925 llvm::SmallVector<Expr*, 4> InitExprs;
1926
1927 // set the receiver to self, the first argument to all methods.
1928 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001930 SourceLocation()));
1931 llvm::SmallVector<Expr*, 8> ClsExprs;
1932 QualType argType = Context->getPointerType(Context->CharTy);
1933 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1934 SuperDecl->getIdentifier()->getLength(),
1935 false, argType, SourceLocation(),
1936 SourceLocation()));
1937 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1938 &ClsExprs[0],
1939 ClsExprs.size());
1940 // To turn off a warning, type-cast to 'id'
1941 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001942 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001943 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1944 // struct objc_super
1945 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001946 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001947
Steve Naroff23f41272008-03-11 18:14:26 +00001948 if (LangOpts.Microsoft) {
1949 SynthSuperContructorFunctionDecl();
1950 // Simulate a contructor call...
1951 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1952 superType, SourceLocation());
1953 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1954 superType, SourceLocation());
1955 } else {
1956 // (struct objc_super) { <exprs from above> }
1957 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1958 &InitExprs[0], InitExprs.size(),
1959 SourceLocation());
1960 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1961 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001962 // struct objc_super *
1963 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1964 Context->getPointerType(SuperRep->getType()),
1965 SourceLocation());
1966 MsgExprs.push_back(Unop);
1967 } else {
1968 llvm::SmallVector<Expr*, 8> ClsExprs;
1969 QualType argType = Context->getPointerType(Context->CharTy);
1970 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1971 clsName->getLength(),
1972 false, argType, SourceLocation(),
1973 SourceLocation()));
1974 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1975 &ClsExprs[0],
1976 ClsExprs.size());
1977 MsgExprs.push_back(Cls);
1978 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001979 } else { // instance message.
1980 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001981
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001982 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001983 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001984 if (MsgSendStretFlavor)
1985 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001986 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1987
1988 llvm::SmallVector<Expr*, 4> InitExprs;
1989
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001990 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001991 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001992 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001993
1994 llvm::SmallVector<Expr*, 8> ClsExprs;
1995 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001996 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1997 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001998 false, argType, SourceLocation(),
1999 SourceLocation()));
2000 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002001 &ClsExprs[0],
2002 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002003 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002004 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002005 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002006 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002007 // struct objc_super
2008 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002009 Expr *SuperRep;
2010
2011 if (LangOpts.Microsoft) {
2012 SynthSuperContructorFunctionDecl();
2013 // Simulate a contructor call...
2014 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2015 superType, SourceLocation());
2016 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2017 superType, SourceLocation());
2018 } else {
2019 // (struct objc_super) { <exprs from above> }
2020 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2021 &InitExprs[0], InitExprs.size(),
2022 SourceLocation());
2023 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2024 }
Steve Naroff874e2322007-11-15 10:28:18 +00002025 // struct objc_super *
2026 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2027 Context->getPointerType(SuperRep->getType()),
2028 SourceLocation());
2029 MsgExprs.push_back(Unop);
2030 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002031 // Remove all type-casts because it may contain objc-style types; e.g.
2032 // Foo<Proto> *.
2033 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2034 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002036 MsgExprs.push_back(recExpr);
2037 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002038 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002039 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002040 llvm::SmallVector<Expr*, 8> SelExprs;
2041 QualType argType = Context->getPointerType(Context->CharTy);
2042 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2043 Exp->getSelector().getName().size(),
2044 false, argType, SourceLocation(),
2045 SourceLocation()));
2046 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2047 &SelExprs[0], SelExprs.size());
2048 MsgExprs.push_back(SelExp);
2049
2050 // Now push any user supplied arguments.
2051 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002052 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002053 // Make all implicit casts explicit...ICE comes in handy:-)
2054 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2055 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002056 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2057 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002058 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002059 }
2060 // Make id<P...> cast into an 'id' cast.
2061 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002063 while ((CE = dyn_cast<CastExpr>(userExpr)))
2064 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002065 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002066 userExpr, SourceLocation());
2067 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002068 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002069 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002070 // We've transferred the ownership to MsgExprs. Null out the argument in
2071 // the original expression, since we will delete it below.
2072 Exp->setArg(i, 0);
2073 }
Steve Naroffab972d32007-11-04 22:37:50 +00002074 // Generate the funky cast.
2075 CastExpr *cast;
2076 llvm::SmallVector<QualType, 8> ArgTypes;
2077 QualType returnType;
2078
2079 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002080 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2081 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2082 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083 ArgTypes.push_back(Context->getObjCIdType());
2084 ArgTypes.push_back(Context->getObjCSelType());
2085 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002086 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002087 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2089 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002090 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002091 ArgTypes.push_back(t);
2092 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2094 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002095 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002096 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002097 }
2098 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002099 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002100
2101 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002102 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2103 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002104
2105 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2106 // If we don't do this cast, we get the following bizarre warning/note:
2107 // xx.m:13: warning: function called through a non-compatible type
2108 // xx.m:13: note: if this code is reached, the program will abort
2109 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2110 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002111
Steve Naroffab972d32007-11-04 22:37:50 +00002112 // Now do the "normal" pointer to function cast.
2113 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002114 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002115 // If we don't have a method decl, force a variadic cast.
2116 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002117 castType = Context->getPointerType(castType);
2118 cast = new CastExpr(castType, cast, SourceLocation());
2119
2120 // Don't forget the parens to enforce the proper binding.
2121 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2122
2123 const FunctionType *FT = msgSendType->getAsFunctionType();
2124 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2125 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002126 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002127 if (MsgSendStretFlavor) {
2128 // We have the method which returns a struct/union. Must also generate
2129 // call to objc_msgSend_stret and hang both varieties on a conditional
2130 // expression which dictate which one to envoke depending on size of
2131 // method's return type.
2132
2133 // Create a reference to the objc_msgSend_stret() declaration.
2134 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2135 SourceLocation());
2136 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2137 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2138 SourceLocation());
2139 // Now do the "normal" pointer to function cast.
2140 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002141 &ArgTypes[0], ArgTypes.size(),
2142 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002143 castType = Context->getPointerType(castType);
2144 cast = new CastExpr(castType, cast, SourceLocation());
2145
2146 // Don't forget the parens to enforce the proper binding.
2147 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2148
2149 FT = msgSendType->getAsFunctionType();
2150 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2151 FT->getResultType(), SourceLocation());
2152
2153 // Build sizeof(returnType)
2154 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2155 returnType, Context->getSizeType(),
2156 SourceLocation(), SourceLocation());
2157 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2158 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2159 // For X86 it is more complicated and some kind of target specific routine
2160 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002161 unsigned IntSize =
2162 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002163 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2164 Context->IntTy,
2165 SourceLocation());
2166 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2167 BinaryOperator::LE,
2168 Context->IntTy,
2169 SourceLocation());
2170 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2171 ConditionalOperator *CondExpr =
2172 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002173 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002174 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002175 return ReplacingStmt;
2176}
2177
2178Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2179 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002180 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002181 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002182
Chris Lattnere64b7772007-10-24 16:57:36 +00002183 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002184 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002185}
2186
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002187/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2188/// call to objc_getProtocol("proto-name").
2189Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2190 if (!GetProtocolFunctionDecl)
2191 SynthGetProtocolFunctionDecl();
2192 // Create a call to objc_getProtocol("ProtocolName").
2193 llvm::SmallVector<Expr*, 8> ProtoExprs;
2194 QualType argType = Context->getPointerType(Context->CharTy);
2195 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2196 strlen(Exp->getProtocol()->getName()),
2197 false, argType, SourceLocation(),
2198 SourceLocation()));
2199 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2200 &ProtoExprs[0],
2201 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002202 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002203 delete Exp;
2204 return ProtoExp;
2205
2206}
2207
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002208/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002209/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002211 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002212 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2213 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002214 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002215 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002216 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002218 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002219 SourceLocation LocStart = CDecl->getLocStart();
2220 SourceLocation LocEnd = CDecl->getLocEnd();
2221
2222 const char *startBuf = SM->getCharacterData(LocStart);
2223 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002224 // If no ivars and no root or if its root, directly or indirectly,
2225 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002226 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2227 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002228 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002229 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002230 return;
2231 }
2232
2233 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002234 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002235 Result += "\nstruct ";
2236 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002237 if (LangOpts.Microsoft)
2238 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002239
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002240 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002241 const char *cursor = strchr(startBuf, '{');
2242 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002244
2245 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002246 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002247 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002248 Result = "\n struct ";
2249 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002250 Result += "_IMPL ";
2251 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002252 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002253
2254 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002255 SourceLocation OnePastCurly =
2256 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2257 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002258 }
2259 cursor++; // past '{'
2260
2261 // Now comment out any visibility specifiers.
2262 while (cursor < endBuf) {
2263 if (*cursor == '@') {
2264 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002265 // Skip whitespace.
2266 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2267 /*scan*/;
2268
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002269 // FIXME: presence of @public, etc. inside comment results in
2270 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002271 if (!strncmp(cursor, "public", strlen("public")) ||
2272 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002273 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002274 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002275 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002276 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002277 // FIXME: If there are cases where '<' is used in ivar declaration part
2278 // of user code, then scan the ivar list and use needToScanForQualifiers
2279 // for type checking.
2280 else if (*cursor == '<') {
2281 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002282 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002283 cursor = strchr(cursor, '>');
2284 cursor++;
2285 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002286 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002287 }
Steve Narofffea763e82007-11-14 19:25:57 +00002288 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002289 }
Steve Narofffea763e82007-11-14 19:25:57 +00002290 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002291 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002292 } else { // we don't have any instance variables - insert super struct.
2293 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2294 Result += " {\n struct ";
2295 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002296 Result += "_IMPL ";
2297 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002298 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002299 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002300 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002301 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002302 if (!ObjCSynthesizedStructs.insert(CDecl))
2303 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002304}
2305
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002306// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002307/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002308void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002309 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002310 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002311 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002312 const char *ClassName,
2313 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002314 if (MethodBegin == MethodEnd) return;
2315
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002316 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002317 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002318 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002319 SEL _cmd;
2320 char *method_types;
2321 void *_imp;
2322 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002323 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002324 Result += "\nstruct _objc_method {\n";
2325 Result += "\tSEL _cmd;\n";
2326 Result += "\tchar *method_types;\n";
2327 Result += "\tvoid *_imp;\n";
2328 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002329
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002330 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002331 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002332
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002333 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002334
2335 /* struct {
2336 struct _objc_method_list *next_method;
2337 int method_count;
2338 struct _objc_method method_list[];
2339 }
2340 */
2341 Result += "\nstatic struct {\n";
2342 Result += "\tstruct _objc_method_list *next_method;\n";
2343 Result += "\tint method_count;\n";
2344 Result += "\tstruct _objc_method method_list[";
2345 Result += utostr(MethodEnd-MethodBegin);
2346 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002347 Result += prefix;
2348 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2349 Result += "_METHODS_";
2350 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002351 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002352 Result += IsInstanceMethod ? "inst" : "cls";
2353 Result += "_meth\")))= ";
2354 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002355
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002356 Result += "\t,{{(SEL)\"";
2357 Result += (*MethodBegin)->getSelector().getName().c_str();
2358 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002359 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002360 Result += "\", \"";
2361 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002362 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002363 Result += MethodInternalNames[*MethodBegin];
2364 Result += "}\n";
2365 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2366 Result += "\t ,{(SEL)\"";
2367 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002368 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002370 Result += "\", \"";
2371 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002372 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002373 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002374 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002375 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002376 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002377}
2378
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002379/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2380void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002381 int NumProtocols,
2382 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383 const char *ClassName,
2384 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002385 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002386 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002387 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002388 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002389 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002390 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002391 /* struct protocol_methods {
2392 SEL _cmd;
2393 char *method_types;
2394 }
2395 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002396 Result += "\nstruct protocol_methods {\n";
2397 Result += "\tSEL _cmd;\n";
2398 Result += "\tchar *method_types;\n";
2399 Result += "};\n";
2400
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002401 objc_protocol_methods = true;
2402 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002403 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2404 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002405 /* struct _objc_protocol_method_list {
2406 int protocol_method_count;
2407 struct protocol_methods protocols[];
2408 }
2409 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002410 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002411 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002412 Result += "\tstruct protocol_methods protocols[";
2413 Result += utostr(NumMethods);
2414 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002415 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002416 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002417 "{\n\t" + utostr(NumMethods) + "\n";
2418
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002419 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002420 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002421 E = PDecl->instmeth_end(); I != E; ++I) {
2422 if (I == PDecl->instmeth_begin())
2423 Result += "\t ,{{(SEL)\"";
2424 else
2425 Result += "\t ,{(SEL)\"";
2426 Result += (*I)->getSelector().getName().c_str();
2427 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002429 Result += "\", \"";
2430 Result += MethodTypeString;
2431 Result += "\"}\n";
2432 }
2433 Result += "\t }\n};\n";
2434 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002435
2436 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002437 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002438 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002439 /* struct _objc_protocol_method_list {
2440 int protocol_method_count;
2441 struct protocol_methods protocols[];
2442 }
2443 */
2444 Result += "\nstatic struct {\n";
2445 Result += "\tint protocol_method_count;\n";
2446 Result += "\tstruct protocol_methods protocols[";
2447 Result += utostr(NumMethods);
2448 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002449 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002450 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002451 "{\n\t";
2452 Result += utostr(NumMethods);
2453 Result += "\n";
2454
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002455 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002456 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002457 E = PDecl->classmeth_end(); I != E; ++I) {
2458 if (I == PDecl->classmeth_begin())
2459 Result += "\t ,{{(SEL)\"";
2460 else
2461 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002462 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002463 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002464 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002465 Result += "\", \"";
2466 Result += MethodTypeString;
2467 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002468 }
2469 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002470 }
2471 // Output:
2472 /* struct _objc_protocol {
2473 // Objective-C 1.0 extensions
2474 struct _objc_protocol_extension *isa;
2475 char *protocol_name;
2476 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002477 struct _objc_protocol_method_list *instance_methods;
2478 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002479 };
2480 */
2481 static bool objc_protocol = false;
2482 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002483 Result += "\nstruct _objc_protocol {\n";
2484 Result += "\tstruct _objc_protocol_extension *isa;\n";
2485 Result += "\tchar *protocol_name;\n";
2486 Result += "\tstruct _objc_protocol **protocol_list;\n";
2487 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2488 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2489 Result += "};\n";
2490
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002491 objc_protocol = true;
2492 }
2493
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002494 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2495 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002496 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002497 "{\n\t0, \"";
2498 Result += PDecl->getName();
2499 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002500 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002501 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002502 Result += PDecl->getName();
2503 Result += ", ";
2504 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002505 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002506 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002507 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002508 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 Result += PDecl->getName();
2510 Result += "\n";
2511 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002512 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513 Result += "0\n";
2514 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002515 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002516 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002517 /* struct _objc_protocol_list {
2518 struct _objc_protocol_list *next;
2519 int protocol_count;
2520 struct _objc_protocol *class_protocols[];
2521 }
2522 */
2523 Result += "\nstatic struct {\n";
2524 Result += "\tstruct _objc_protocol_list *next;\n";
2525 Result += "\tint protocol_count;\n";
2526 Result += "\tstruct _objc_protocol *class_protocols[";
2527 Result += utostr(NumProtocols);
2528 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002529 Result += prefix;
2530 Result += "_PROTOCOLS_";
2531 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002532 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002533 "{\n\t0, ";
2534 Result += utostr(NumProtocols);
2535 Result += "\n";
2536
2537 Result += "\t,{&_OBJC_PROTOCOL_";
2538 Result += Protocols[0]->getName();
2539 Result += " \n";
2540
2541 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002543 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544 Result += PDecl->getName();
2545 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002546 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002547 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002548 }
2549}
2550
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002552/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002554 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002556 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002558 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2559 CDecl = CDecl->getNextClassCategory())
2560 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2561 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002562
Chris Lattnereb44eee2007-12-23 01:40:15 +00002563 std::string FullCategoryName = ClassDecl->getName();
2564 FullCategoryName += '_';
2565 FullCategoryName += IDecl->getName();
2566
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002567 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002569 true, "CATEGORY_", FullCategoryName.c_str(),
2570 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002571
2572 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002573 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002574 false, "CATEGORY_", FullCategoryName.c_str(),
2575 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002576
2577 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002578 // Null CDecl is case of a category implementation with no category interface
2579 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002580 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002581 CDecl->getNumReferencedProtocols(),
2582 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002583 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002584
2585 /* struct _objc_category {
2586 char *category_name;
2587 char *class_name;
2588 struct _objc_method_list *instance_methods;
2589 struct _objc_method_list *class_methods;
2590 struct _objc_protocol_list *protocols;
2591 // Objective-C 1.0 extensions
2592 uint32_t size; // sizeof (struct _objc_category)
2593 struct _objc_property_list *instance_properties; // category's own
2594 // @property decl.
2595 };
2596 */
2597
2598 static bool objc_category = false;
2599 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002600 Result += "\nstruct _objc_category {\n";
2601 Result += "\tchar *category_name;\n";
2602 Result += "\tchar *class_name;\n";
2603 Result += "\tstruct _objc_method_list *instance_methods;\n";
2604 Result += "\tstruct _objc_method_list *class_methods;\n";
2605 Result += "\tstruct _objc_protocol_list *protocols;\n";
2606 Result += "\tunsigned int size;\n";
2607 Result += "\tstruct _objc_property_list *instance_properties;\n";
2608 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002609 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002610 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002611 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2612 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002613 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002614 Result += IDecl->getName();
2615 Result += "\"\n\t, \"";
2616 Result += ClassDecl->getName();
2617 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002618
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002619 if (IDecl->getNumInstanceMethods() > 0) {
2620 Result += "\t, (struct _objc_method_list *)"
2621 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2622 Result += FullCategoryName;
2623 Result += "\n";
2624 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002625 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002626 Result += "\t, 0\n";
2627 if (IDecl->getNumClassMethods() > 0) {
2628 Result += "\t, (struct _objc_method_list *)"
2629 "&_OBJC_CATEGORY_CLASS_METHODS_";
2630 Result += FullCategoryName;
2631 Result += "\n";
2632 }
2633 else
2634 Result += "\t, 0\n";
2635
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002636 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002637 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2638 Result += FullCategoryName;
2639 Result += "\n";
2640 }
2641 else
2642 Result += "\t, 0\n";
2643 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002644}
2645
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002646/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2647/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002648void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2649 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002650 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002651 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002652 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002653 if (LangOpts.Microsoft)
2654 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002655 Result += ", ";
2656 Result += ivar->getName();
2657 Result += ")";
2658}
2659
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002660//===----------------------------------------------------------------------===//
2661// Meta Data Emission
2662//===----------------------------------------------------------------------===//
2663
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002664void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002665 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002666 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002667
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002668 // Explictly declared @interface's are already synthesized.
2669 if (CDecl->ImplicitInterfaceDecl()) {
2670 // FIXME: Implementation of a class with no @interface (legacy) doese not
2671 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002673 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002674
Chris Lattnerbe6df082007-12-12 07:56:42 +00002675 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002676 unsigned NumIvars = !IDecl->ivar_empty()
2677 ? IDecl->ivar_size()
2678 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002679 if (NumIvars > 0) {
2680 static bool objc_ivar = false;
2681 if (!objc_ivar) {
2682 /* struct _objc_ivar {
2683 char *ivar_name;
2684 char *ivar_type;
2685 int ivar_offset;
2686 };
2687 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002688 Result += "\nstruct _objc_ivar {\n";
2689 Result += "\tchar *ivar_name;\n";
2690 Result += "\tchar *ivar_type;\n";
2691 Result += "\tint ivar_offset;\n";
2692 Result += "};\n";
2693
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002694 objc_ivar = true;
2695 }
2696
Steve Naroff946a6932008-03-11 00:12:29 +00002697 /* struct {
2698 int ivar_count;
2699 struct _objc_ivar ivar_list[nIvars];
2700 };
2701 */
2702 Result += "\nstatic struct {\n";
2703 Result += "\tint ivar_count;\n";
2704 Result += "\tstruct _objc_ivar ivar_list[";
2705 Result += utostr(NumIvars);
2706 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002707 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002708 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002709 "{\n\t";
2710 Result += utostr(NumIvars);
2711 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002712
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002713 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002714 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002715 IVI = IDecl->ivar_begin();
2716 IVE = IDecl->ivar_end();
2717 } else {
2718 IVI = CDecl->ivar_begin();
2719 IVE = CDecl->ivar_end();
2720 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002721 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002722 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002723 Result += "\", \"";
2724 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002725 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2726 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002727 Result += StrEncoding;
2728 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002729 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002730 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002731 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002733 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002734 Result += "\", \"";
2735 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002736 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2737 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002738 Result += StrEncoding;
2739 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002740 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002741 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 }
2743
2744 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002745 }
2746
2747 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002748 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002749 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002750
2751 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002753 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002754
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002755 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002756 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002758 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002759
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002760
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002761 // Declaration of class/meta-class metadata
2762 /* struct _objc_class {
2763 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002764 const char *super_class_name;
2765 char *name;
2766 long version;
2767 long info;
2768 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002769 struct _objc_ivar_list *ivars;
2770 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002771 struct objc_cache *cache;
2772 struct objc_protocol_list *protocols;
2773 const char *ivar_layout;
2774 struct _objc_class_ext *ext;
2775 };
2776 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002777 static bool objc_class = false;
2778 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002779 Result += "\nstruct _objc_class {\n";
2780 Result += "\tstruct _objc_class *isa;\n";
2781 Result += "\tconst char *super_class_name;\n";
2782 Result += "\tchar *name;\n";
2783 Result += "\tlong version;\n";
2784 Result += "\tlong info;\n";
2785 Result += "\tlong instance_size;\n";
2786 Result += "\tstruct _objc_ivar_list *ivars;\n";
2787 Result += "\tstruct _objc_method_list *methods;\n";
2788 Result += "\tstruct objc_cache *cache;\n";
2789 Result += "\tstruct _objc_protocol_list *protocols;\n";
2790 Result += "\tconst char *ivar_layout;\n";
2791 Result += "\tstruct _objc_class_ext *ext;\n";
2792 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002793 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002794 }
2795
2796 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002797 ObjCInterfaceDecl *RootClass = 0;
2798 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002799 while (SuperClass) {
2800 RootClass = SuperClass;
2801 SuperClass = SuperClass->getSuperClass();
2802 }
2803 SuperClass = CDecl->getSuperClass();
2804
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002805 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2806 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002807 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808 "{\n\t(struct _objc_class *)\"";
2809 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2810 Result += "\"";
2811
2812 if (SuperClass) {
2813 Result += ", \"";
2814 Result += SuperClass->getName();
2815 Result += "\", \"";
2816 Result += CDecl->getName();
2817 Result += "\"";
2818 }
2819 else {
2820 Result += ", 0, \"";
2821 Result += CDecl->getName();
2822 Result += "\"";
2823 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002825 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002826 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002827 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002828 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002829 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 Result += "\n";
2831 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002832 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002833 Result += ", 0\n";
2834 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002835 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002836 Result += CDecl->getName();
2837 Result += ",0,0\n";
2838 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002839 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002840 Result += "\t,0,0,0,0\n";
2841 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002842
2843 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2845 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002846 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002847 "{\n\t&_OBJC_METACLASS_";
2848 Result += CDecl->getName();
2849 if (SuperClass) {
2850 Result += ", \"";
2851 Result += SuperClass->getName();
2852 Result += "\", \"";
2853 Result += CDecl->getName();
2854 Result += "\"";
2855 }
2856 else {
2857 Result += ", 0, \"";
2858 Result += CDecl->getName();
2859 Result += "\"";
2860 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002861 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002862 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002863 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002864 Result += ",0";
2865 else {
2866 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002867 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002868 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002869 if (LangOpts.Microsoft)
2870 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002871 Result += ")";
2872 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002873 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002874 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002875 Result += CDecl->getName();
2876 Result += "\n\t";
2877 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002878 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002879 Result += ",0";
2880 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002881 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002882 Result += CDecl->getName();
2883 Result += ", 0\n\t";
2884 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002885 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += ",0,0";
2887 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002888 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002889 Result += CDecl->getName();
2890 Result += ", 0,0\n";
2891 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002892 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002893 Result += ",0,0,0\n";
2894 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002895}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002896
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002897/// RewriteImplementations - This routine rewrites all method implementations
2898/// and emits meta-data.
2899
2900void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002901 int ClsDefCount = ClassImplementation.size();
2902 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002903
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002904 if (ClsDefCount == 0 && CatDefCount == 0)
2905 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002906 // Rewrite implemented methods
2907 for (int i = 0; i < ClsDefCount; i++)
2908 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002909
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002910 for (int i = 0; i < CatDefCount; i++)
2911 RewriteImplementationDecl(CategoryImplementation[i]);
2912
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002913 // This is needed for use of offsetof
Steve Naroffb10f2732008-04-04 22:58:22 +00002914 Result += "#define offsetof(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002915 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002916 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002917 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002918
2919 // For each implemented category, write out all its meta data.
2920 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002921 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002922
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002923 // Write objc_symtab metadata
2924 /*
2925 struct _objc_symtab
2926 {
2927 long sel_ref_cnt;
2928 SEL *refs;
2929 short cls_def_cnt;
2930 short cat_def_cnt;
2931 void *defs[cls_def_cnt + cat_def_cnt];
2932 };
2933 */
2934
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002935 Result += "\nstruct _objc_symtab {\n";
2936 Result += "\tlong sel_ref_cnt;\n";
2937 Result += "\tSEL *refs;\n";
2938 Result += "\tshort cls_def_cnt;\n";
2939 Result += "\tshort cat_def_cnt;\n";
2940 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2941 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002942
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002944 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002945 Result += "\t0, 0, " + utostr(ClsDefCount)
2946 + ", " + utostr(CatDefCount) + "\n";
2947 for (int i = 0; i < ClsDefCount; i++) {
2948 Result += "\t,&_OBJC_CLASS_";
2949 Result += ClassImplementation[i]->getName();
2950 Result += "\n";
2951 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002952
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002953 for (int i = 0; i < CatDefCount; i++) {
2954 Result += "\t,&_OBJC_CATEGORY_";
2955 Result += CategoryImplementation[i]->getClassInterface()->getName();
2956 Result += "_";
2957 Result += CategoryImplementation[i]->getName();
2958 Result += "\n";
2959 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002960
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002961 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002962
2963 // Write objc_module metadata
2964
2965 /*
2966 struct _objc_module {
2967 long version;
2968 long size;
2969 const char *name;
2970 struct _objc_symtab *symtab;
2971 }
2972 */
2973
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002974 Result += "\nstruct _objc_module {\n";
2975 Result += "\tlong version;\n";
2976 Result += "\tlong size;\n";
2977 Result += "\tconst char *name;\n";
2978 Result += "\tstruct _objc_symtab *symtab;\n";
2979 Result += "};\n\n";
2980 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002981 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002982 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2983 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002984 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002985
2986 if (LangOpts.Microsoft) {
2987 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2988 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2989 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2990 Result += "&_OBJC_MODULES;\n";
2991 Result += "#pragma data_seg(pop)\n\n";
2992 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002993}
Chris Lattner311ff022007-10-16 22:36:42 +00002994