blob: b7c65a5e2bf68239f242564436885a9f5ddd2ce8 [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";
330 Preamble += "#include <objc/objc.h>\n";
331 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
332 Preamble += "struct __objcFastEnumerationState {\n\t";
333 Preamble += "unsigned long state;\n\t";
334 Preamble += "id *itemsPtr;\n\t";
335 Preamble += "unsigned long *mutationsPtr;\n\t";
336 Preamble += "unsigned long extra[5];\n};\n";
337 Preamble += "#define __FASTENUMERATIONSTATE\n";
338 Preamble += "#endif\n";
339 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
340 Preamble += "struct __NSConstantStringImpl {\n";
341 Preamble += " int *isa;\n";
342 Preamble += " int flags;\n";
343 Preamble += " char *str;\n";
344 Preamble += " long length;\n";
345 Preamble += "};\n";
346 Preamble += "extern int __CFConstantStringClassReference[];\n";
347 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
348 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000349 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000350 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000351}
352
353
Chris Lattnerf04da132007-10-24 17:06:59 +0000354//===----------------------------------------------------------------------===//
355// Top Level Driver Code
356//===----------------------------------------------------------------------===//
357
Chris Lattner8a12c272007-10-11 18:38:32 +0000358void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000359 // Two cases: either the decl could be in the main file, or it could be in a
360 // #included file. If the former, rewrite it now. If the later, check to see
361 // if we rewrote the #include/#import.
362 SourceLocation Loc = D->getLocation();
363 Loc = SM->getLogicalLoc(Loc);
364
365 // If this is for a builtin, ignore it.
366 if (Loc.isInvalid()) return;
367
Steve Naroffebf2b562007-10-23 23:50:29 +0000368 // Look for built-in declarations that we need to refer during the rewrite.
369 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000370 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000371 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
372 // declared in <Foundation/NSString.h>
373 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
374 ConstantStringClassReference = FVD;
375 return;
376 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000377 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000378 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000379 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000380 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000381 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000382 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000383 } else if (ObjCForwardProtocolDecl *FP =
384 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000385 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000386 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000387 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000388 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
389 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000390}
391
Chris Lattnerf04da132007-10-24 17:06:59 +0000392/// HandleDeclInMainFile - This is called for each top-level decl defined in the
393/// main file of the input.
394void RewriteTest::HandleDeclInMainFile(Decl *D) {
395 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
396 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000397 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000398
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000400 if (Stmt *Body = MD->getBody()) {
401 //Body->dump();
402 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000403 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000404 CurMethodDecl = 0;
405 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000406 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000407 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000408 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000409 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000410 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000411 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000412 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000413 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000414 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000415 if (VD->getInit())
416 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
417 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000418 // Nothing yet.
419}
420
421RewriteTest::~RewriteTest() {
422 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000423
424 // Rewrite tabs if we care.
425 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000426
Steve Naroffa7b402d2008-03-28 22:26:09 +0000427 if (Diags.hasErrorOccurred())
428 return;
429
430 // Create the output file.
431
432 std::ostream *OutFile;
433 if (OutFileName == "-") {
434 OutFile = llvm::cout.stream();
435 } else if (!OutFileName.empty()) {
436 OutFile = new std::ofstream(OutFileName.c_str(),
437 std::ios_base::binary|std::ios_base::out);
438 } else if (InFileName == "-") {
439 OutFile = llvm::cout.stream();
440 } else {
441 llvm::sys::Path Path(InFileName);
442 Path.eraseSuffix();
443 Path.appendSuffix("cpp");
444 OutFile = new std::ofstream(Path.toString().c_str(),
445 std::ios_base::binary|std::ios_base::out);
446 }
447
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000448 RewriteInclude();
449
Steve Naroffba92b2e2008-03-27 22:29:16 +0000450 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
451 Preamble.c_str(), Preamble.size(), false);
452
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000453 // Rewrite Objective-c meta data*
454 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000455 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000456
Chris Lattnerf04da132007-10-24 17:06:59 +0000457 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
458 // we are done.
459 if (const RewriteBuffer *RewriteBuf =
460 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000461 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000462 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000463 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000464 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000465 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000466 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000467 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000468}
469
Chris Lattnerf04da132007-10-24 17:06:59 +0000470//===----------------------------------------------------------------------===//
471// Syntactic (non-AST) Rewriting Code
472//===----------------------------------------------------------------------===//
473
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000474void RewriteTest::RewriteInclude() {
475 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
476 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
477 const char *MainBufStart = MainBuf.first;
478 const char *MainBufEnd = MainBuf.second;
479 size_t ImportLen = strlen("import");
480 size_t IncludeLen = strlen("include");
481
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000482 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000483 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
484 if (*BufPtr == '#') {
485 if (++BufPtr == MainBufEnd)
486 return;
487 while (*BufPtr == ' ' || *BufPtr == '\t')
488 if (++BufPtr == MainBufEnd)
489 return;
490 if (!strncmp(BufPtr, "import", ImportLen)) {
491 // replace import with include
492 SourceLocation ImportLoc =
493 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000494 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000495 BufPtr += ImportLen;
496 }
497 }
498 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000499}
500
Chris Lattnerf04da132007-10-24 17:06:59 +0000501void RewriteTest::RewriteTabs() {
502 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
503 const char *MainBufStart = MainBuf.first;
504 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000505
Chris Lattnerf04da132007-10-24 17:06:59 +0000506 // Loop over the whole file, looking for tabs.
507 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
508 if (*BufPtr != '\t')
509 continue;
510
511 // Okay, we found a tab. This tab will turn into at least one character,
512 // but it depends on which 'virtual column' it is in. Compute that now.
513 unsigned VCol = 0;
514 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
515 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
516 ++VCol;
517
518 // Okay, now that we know the virtual column, we know how many spaces to
519 // insert. We assume 8-character tab-stops.
520 unsigned Spaces = 8-(VCol & 7);
521
522 // Get the location of the tab.
523 SourceLocation TabLoc =
524 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
525
526 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000527 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000528 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000529}
530
531
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000532void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000533 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000534 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000535
536 // Get the start location and compute the semi location.
537 SourceLocation startLoc = ClassDecl->getLocation();
538 const char *startBuf = SM->getCharacterData(startLoc);
539 const char *semiPtr = strchr(startBuf, ';');
540
541 // Translate to typedef's that forward reference structs with the same name
542 // as the class. As a convenience, we include the original declaration
543 // as a comment.
544 std::string typedefString;
545 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000546 typedefString.append(startBuf, semiPtr-startBuf+1);
547 typedefString += "\n";
548 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000549 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000550 typedefString += "#ifndef _REWRITER_typedef_";
551 typedefString += ForwardDecl->getName();
552 typedefString += "\n";
553 typedefString += "#define _REWRITER_typedef_";
554 typedefString += ForwardDecl->getName();
555 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000556 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000557 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000558 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000559 }
560
561 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000562 ReplaceText(startLoc, semiPtr-startBuf+1,
563 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000564}
565
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000566void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000567 SourceLocation LocStart = Method->getLocStart();
568 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000569
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000570 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000571 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000572 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000573 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000574 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000575 }
576}
577
Chris Lattner55d13b42008-03-16 21:23:50 +0000578void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000579{
Chris Lattner55d13b42008-03-16 21:23:50 +0000580 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000581 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000582 SourceLocation Loc = Property->getLocation();
583
Chris Lattneraadaf782008-01-31 19:51:04 +0000584 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000585
586 // FIXME: handle properties that are declared across multiple lines.
587 }
588}
589
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000590void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000591 SourceLocation LocStart = CatDecl->getLocStart();
592
593 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000594 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000595
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000596 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000597 E = CatDecl->instmeth_end(); I != E; ++I)
598 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000599 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000600 E = CatDecl->classmeth_end(); I != E; ++I)
601 RewriteMethodDeclaration(*I);
602
Steve Naroff423cb562007-10-30 13:30:57 +0000603 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000604 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000605}
606
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000607void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000608 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000609
Steve Naroff752d6ef2007-10-30 16:42:30 +0000610 SourceLocation LocStart = PDecl->getLocStart();
611
612 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000613 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000614
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000615 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000616 E = PDecl->instmeth_end(); I != E; ++I)
617 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000618 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000619 E = PDecl->classmeth_end(); I != E; ++I)
620 RewriteMethodDeclaration(*I);
621
Steve Naroff752d6ef2007-10-30 16:42:30 +0000622 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000623 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000624 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000625
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000626 // Must comment out @optional/@required
627 const char *startBuf = SM->getCharacterData(LocStart);
628 const char *endBuf = SM->getCharacterData(LocEnd);
629 for (const char *p = startBuf; p < endBuf; p++) {
630 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
631 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000632 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000633 ReplaceText(OptionalLoc, strlen("@optional"),
634 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000635
636 }
637 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
638 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000639 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000640 ReplaceText(OptionalLoc, strlen("@required"),
641 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000642
643 }
644 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000645}
646
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000647void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000648 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000649 if (LocStart.isInvalid())
650 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000651 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000652 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000653}
654
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000656 std::string &ResultStr) {
657 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000658 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000659 ResultStr += "id";
660 else
661 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000662 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000663
664 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000665 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000666
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000667 if (OMD->isInstance())
668 NameStr += "_I_";
669 else
670 NameStr += "_C_";
671
672 NameStr += OMD->getClassInterface()->getName();
673 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000674
675 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 if (ObjCCategoryImplDecl *CID =
677 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000678 NameStr += CID->getName();
679 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000680 }
681 // Append selector names, replacing ':' with '_'
682 const char *selName = OMD->getSelector().getName().c_str();
683 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000684 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 else {
686 std::string selString = OMD->getSelector().getName();
687 int len = selString.size();
688 for (int i = 0; i < len; i++)
689 if (selString[i] == ':')
690 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000691 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000692 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000693 // Remember this name for metadata emission
694 MethodInternalNames[OMD] = NameStr;
695 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000696
697 // Rewrite arguments
698 ResultStr += "(";
699
700 // invisible arguments
701 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000702 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000703 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000704 if (!LangOpts.Microsoft) {
705 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
706 ResultStr += "struct ";
707 }
708 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000709 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000710 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000711 }
712 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714
715 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717 ResultStr += " _cmd";
718
719 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000720 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ParmVarDecl *PDecl = OMD->getParamDecl(i);
722 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000723 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000724 ResultStr += "id";
725 else
726 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000727 ResultStr += " ";
728 ResultStr += PDecl->getName();
729 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000730 if (OMD->isVariadic())
731 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000732 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000733
734}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000735void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
737 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000738
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000739 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000740 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000741 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000742 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000743
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000744 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000745 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
746 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000747 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 ObjCMethodDecl *OMD = *I;
749 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000750 SourceLocation LocStart = OMD->getLocStart();
751 SourceLocation LocEnd = OMD->getBody()->getLocStart();
752
753 const char *startBuf = SM->getCharacterData(LocStart);
754 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000755 ReplaceText(LocStart, endBuf-startBuf,
756 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000757 }
758
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000759 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000760 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
761 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000763 ObjCMethodDecl *OMD = *I;
764 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000765 SourceLocation LocStart = OMD->getLocStart();
766 SourceLocation LocEnd = OMD->getBody()->getLocStart();
767
768 const char *startBuf = SM->getCharacterData(LocStart);
769 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000770 ReplaceText(LocStart, endBuf-startBuf,
771 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000772 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000773 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000774 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000775 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000776 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000777}
778
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000780 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000781 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000782 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000783 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000784 ResultStr += ClassDecl->getName();
785 ResultStr += "\n";
786 ResultStr += "#define _REWRITER_typedef_";
787 ResultStr += ClassDecl->getName();
788 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000789 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000790 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000791 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000792 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000794 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000795 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000796
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000797 RewriteProperties(ClassDecl->getNumPropertyDecl(),
798 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000799 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000800 E = ClassDecl->instmeth_end(); I != E; ++I)
801 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000802 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000803 E = ClassDecl->classmeth_end(); I != E; ++I)
804 RewriteMethodDeclaration(*I);
805
Steve Naroff2feac5e2007-10-30 03:43:13 +0000806 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000807 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000808}
809
Steve Naroff7e3411b2007-11-15 02:58:25 +0000810Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000811 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000812 if (CurMethodDecl) {
813 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
814 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
815 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000816 // lookup which class implements the instance variable.
817 ObjCInterfaceDecl *clsDeclared = 0;
818 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
819 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000820
821 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000822 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000823 RecName += "_IMPL";
824 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattner0ed844b2008-04-04 06:12:32 +0000825 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000826 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000827 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
828 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
829 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
830 // Don't forget the parens to enforce the proper binding.
831 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
832 if (IV->isFreeIvar()) {
833 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
834 ReplaceStmt(IV, ME);
835 delete IV;
836 return ME;
837 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000838 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000839 // Cannot delete IV->getBase(), since PE points to it.
840 // Replace the old base with the cast. This is important when doing
841 // embedded rewrites. For example, [newInv->_container addObject:0].
842 IV->setBase(PE);
843 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000844 }
845 }
846 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000847 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000848 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000849 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
850 IV->getLocation(), D->getType());
851 ReplaceStmt(IV, Replacement);
852 delete IV;
853 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000854}
855
Chris Lattnerf04da132007-10-24 17:06:59 +0000856//===----------------------------------------------------------------------===//
857// Function Body / Expression rewriting
858//===----------------------------------------------------------------------===//
859
Steve Narofff3473a72007-11-09 15:20:18 +0000860Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000861 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
862 isa<DoStmt>(S) || isa<ForStmt>(S))
863 Stmts.push_back(S);
864 else if (isa<ObjCForCollectionStmt>(S)) {
865 Stmts.push_back(S);
866 ObjCBcLabelNo.push_back(++BcLabelCount);
867 }
868
Chris Lattner338d1e22008-01-31 05:10:40 +0000869 SourceLocation OrigStmtEnd = S->getLocEnd();
870
871 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000872 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
873 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000874 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000875 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000876 if (newStmt)
877 *CI = newStmt;
878 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000879
880 // Handle specific things.
881 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
882 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000883
884 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
885 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000886
887 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
888 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000889
Steve Naroffbeaf2992007-11-03 11:27:19 +0000890 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
891 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000892
Steve Naroff934f2762007-10-24 22:48:43 +0000893 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
894 // Before we rewrite it, put the original message expression in a comment.
895 SourceLocation startLoc = MessExpr->getLocStart();
896 SourceLocation endLoc = MessExpr->getLocEnd();
897
898 const char *startBuf = SM->getCharacterData(startLoc);
899 const char *endBuf = SM->getCharacterData(endLoc);
900
901 std::string messString;
902 messString += "// ";
903 messString.append(startBuf, endBuf-startBuf+1);
904 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000905
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000906 // FIXME: Missing definition of
907 // InsertText(clang::SourceLocation, char const*, unsigned int).
908 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000909 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000910 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000911 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000912 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000913
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000914 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
915 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000916
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000917 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
918 return RewriteObjCSynchronizedStmt(StmtTry);
919
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000920 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
921 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000922
923 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
924 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000925
926 if (ObjCForCollectionStmt *StmtForCollection =
927 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000928 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000929 if (BreakStmt *StmtBreakStmt =
930 dyn_cast<BreakStmt>(S))
931 return RewriteBreakStmt(StmtBreakStmt);
932 if (ContinueStmt *StmtContinueStmt =
933 dyn_cast<ContinueStmt>(S))
934 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000935
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000936 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
937 isa<DoStmt>(S) || isa<ForStmt>(S)) {
938 assert(!Stmts.empty() && "Statement stack is empty");
939 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
940 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
941 && "Statement stack mismatch");
942 Stmts.pop_back();
943 }
Steve Naroff874e2322007-11-15 10:28:18 +0000944#if 0
945 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
946 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
947 // Get the new text.
948 std::ostringstream Buf;
949 Replacement->printPretty(Buf);
950 const std::string &Str = Buf.str();
951
952 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000953 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000954 delete S;
955 return Replacement;
956 }
957#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000958 // Return this stmt unmodified.
959 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000960}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000961
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000962/// SynthCountByEnumWithState - To print:
963/// ((unsigned int (*)
964/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
965/// (void *)objc_msgSend)((id)l_collection,
966/// sel_registerName(
967/// "countByEnumeratingWithState:objects:count:"),
968/// &enumState,
969/// (id *)items, (unsigned int)16)
970///
971void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
972 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
973 "id *, unsigned int))(void *)objc_msgSend)";
974 buf += "\n\t\t";
975 buf += "((id)l_collection,\n\t\t";
976 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
977 buf += "\n\t\t";
978 buf += "&enumState, "
979 "(id *)items, (unsigned int)16)";
980}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000981
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000982/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
983/// statement to exit to its outer synthesized loop.
984///
985Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
986 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
987 return S;
988 // replace break with goto __break_label
989 std::string buf;
990
991 SourceLocation startLoc = S->getLocStart();
992 buf = "goto __break_label_";
993 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000994 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000995
996 return 0;
997}
998
999/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1000/// statement to continue with its inner synthesized loop.
1001///
1002Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
1003 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1004 return S;
1005 // replace continue with goto __continue_label
1006 std::string buf;
1007
1008 SourceLocation startLoc = S->getLocStart();
1009 buf = "goto __continue_label_";
1010 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001011 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001012
1013 return 0;
1014}
1015
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001016/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001017/// It rewrites:
1018/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001019
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001020/// Into:
1021/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001022/// type elem;
1023/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001024/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001025/// id l_collection = (id)collection;
1026/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1027/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001028/// if (limit) {
1029/// unsigned long startMutations = *enumState.mutationsPtr;
1030/// do {
1031/// unsigned long counter = 0;
1032/// do {
1033/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001034/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001035/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001036/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001037/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001038/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001039/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1040/// objects:items count:16]);
1041/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001042/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001043/// }
1044/// else
1045/// elem = nil;
1046/// }
1047///
Chris Lattner338d1e22008-01-31 05:10:40 +00001048Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1049 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001050 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1051 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1052 "ObjCForCollectionStmt Statement stack mismatch");
1053 assert(!ObjCBcLabelNo.empty() &&
1054 "ObjCForCollectionStmt - Label No stack empty");
1055
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001056 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001059 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001060 std::string buf;
1061 buf = "\n{\n\t";
1062 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1063 // type elem;
1064 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001065 elementTypeAsString = ElementType.getAsString();
1066 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067 buf += " ";
1068 elementName = DS->getDecl()->getName();
1069 buf += elementName;
1070 buf += ";\n\t";
1071 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001072 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001073 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001074 elementTypeAsString = DR->getDecl()->getType().getAsString();
1075 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001076 else
1077 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1078
1079 // struct __objcFastEnumerationState enumState = { 0 };
1080 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1081 // id items[16];
1082 buf += "id items[16];\n\t";
1083 // id l_collection = (id)
1084 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001085 // Find start location of 'collection' the hard way!
1086 const char *startCollectionBuf = startBuf;
1087 startCollectionBuf += 3; // skip 'for'
1088 startCollectionBuf = strchr(startCollectionBuf, '(');
1089 startCollectionBuf++; // skip '('
1090 // find 'in' and skip it.
1091 while (*startCollectionBuf != ' ' ||
1092 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1093 (*(startCollectionBuf+3) != ' ' &&
1094 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1095 startCollectionBuf++;
1096 startCollectionBuf += 3;
1097
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001099 ReplaceText(startLoc, startCollectionBuf - startBuf,
1100 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001102 SourceLocation rightParenLoc = S->getRParenLoc();
1103 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1104 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001105 buf = ";\n\t";
1106
1107 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1108 // objects:items count:16];
1109 // which is synthesized into:
1110 // unsigned int limit =
1111 // ((unsigned int (*)
1112 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1113 // (void *)objc_msgSend)((id)l_collection,
1114 // sel_registerName(
1115 // "countByEnumeratingWithState:objects:count:"),
1116 // (struct __objcFastEnumerationState *)&state,
1117 // (id *)items, (unsigned int)16);
1118 buf += "unsigned long limit =\n\t\t";
1119 SynthCountByEnumWithState(buf);
1120 buf += ";\n\t";
1121 /// if (limit) {
1122 /// unsigned long startMutations = *enumState.mutationsPtr;
1123 /// do {
1124 /// unsigned long counter = 0;
1125 /// do {
1126 /// if (startMutations != *enumState.mutationsPtr)
1127 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001128 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001129 buf += "if (limit) {\n\t";
1130 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1131 buf += "do {\n\t\t";
1132 buf += "unsigned long counter = 0;\n\t\t";
1133 buf += "do {\n\t\t\t";
1134 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1135 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1136 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001137 buf += " = (";
1138 buf += elementTypeAsString;
1139 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001140 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001141 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001142
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001143 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001144 /// } while (counter < limit);
1145 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1146 /// objects:items count:16]);
1147 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001148 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001149 /// }
1150 /// else
1151 /// elem = nil;
1152 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001153 ///
1154 buf = ";\n\t";
1155 buf += "__continue_label_";
1156 buf += utostr(ObjCBcLabelNo.back());
1157 buf += ": ;";
1158 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001159 buf += "} while (counter < limit);\n\t";
1160 buf += "} while (limit = ";
1161 SynthCountByEnumWithState(buf);
1162 buf += ");\n\t";
1163 buf += elementName;
1164 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001165 buf += "__break_label_";
1166 buf += utostr(ObjCBcLabelNo.back());
1167 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001168 buf += "}\n\t";
1169 buf += "else\n\t\t";
1170 buf += elementName;
1171 buf += " = nil;\n";
1172 buf += "}\n";
1173 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001174 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001175 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001176 Stmts.pop_back();
1177 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001178 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001179}
1180
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001181/// RewriteObjCSynchronizedStmt -
1182/// This routine rewrites @synchronized(expr) stmt;
1183/// into:
1184/// objc_sync_enter(expr);
1185/// @try stmt @finally { objc_sync_exit(expr); }
1186///
1187Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1188 // Get the start location and compute the semi location.
1189 SourceLocation startLoc = S->getLocStart();
1190 const char *startBuf = SM->getCharacterData(startLoc);
1191
1192 assert((*startBuf == '@') && "bogus @synchronized location");
1193
1194 std::string buf;
1195 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001196 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001197 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1198 const char *endBuf = SM->getCharacterData(endLoc);
1199 endBuf++;
1200 const char *rparenBuf = strchr(endBuf, ')');
1201 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1202 buf = ");\n";
1203 // declare a new scope with two variables, _stack and _rethrow.
1204 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1205 buf += "int buf[18/*32-bit i386*/];\n";
1206 buf += "char *pointers[4];} _stack;\n";
1207 buf += "id volatile _rethrow = 0;\n";
1208 buf += "objc_exception_try_enter(&_stack);\n";
1209 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001210 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001211 startLoc = S->getSynchBody()->getLocEnd();
1212 startBuf = SM->getCharacterData(startLoc);
1213
1214 assert((*startBuf == '}') && "bogus @try block");
1215 SourceLocation lastCurlyLoc = startLoc;
1216 buf = "}\nelse {\n";
1217 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1218 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1219 // FIXME: This must be objc_sync_exit(syncExpr);
1220 buf += " objc_sync_exit();\n";
1221 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1222 buf += "}\n";
1223 buf += "}";
1224
Chris Lattneraadaf782008-01-31 19:51:04 +00001225 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001226 return 0;
1227}
1228
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001229Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001230 // Get the start location and compute the semi location.
1231 SourceLocation startLoc = S->getLocStart();
1232 const char *startBuf = SM->getCharacterData(startLoc);
1233
1234 assert((*startBuf == '@') && "bogus @try location");
1235
1236 std::string buf;
1237 // declare a new scope with two variables, _stack and _rethrow.
1238 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1239 buf += "int buf[18/*32-bit i386*/];\n";
1240 buf += "char *pointers[4];} _stack;\n";
1241 buf += "id volatile _rethrow = 0;\n";
1242 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001243 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001244
Chris Lattneraadaf782008-01-31 19:51:04 +00001245 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001246
1247 startLoc = S->getTryBody()->getLocEnd();
1248 startBuf = SM->getCharacterData(startLoc);
1249
1250 assert((*startBuf == '}') && "bogus @try block");
1251
1252 SourceLocation lastCurlyLoc = startLoc;
1253
1254 startLoc = startLoc.getFileLocWithOffset(1);
1255 buf = " /* @catch begin */ else {\n";
1256 buf += " id _caught = objc_exception_extract(&_stack);\n";
1257 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001258 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001259 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1260 buf += " else { /* @catch continue */";
1261
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001262 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001263
1264 bool sawIdTypedCatch = false;
1265 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001266 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001267 while (catchList) {
1268 Stmt *catchStmt = catchList->getCatchParamStmt();
1269
1270 if (catchList == S->getCatchStmts())
1271 buf = "if ("; // we are generating code for the first catch clause
1272 else
1273 buf = "else if (";
1274 startLoc = catchList->getLocStart();
1275 startBuf = SM->getCharacterData(startLoc);
1276
1277 assert((*startBuf == '@') && "bogus @catch location");
1278
1279 const char *lParenLoc = strchr(startBuf, '(');
1280
Steve Naroffbe4b3332008-02-01 22:08:12 +00001281 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001282 // Now rewrite the body...
1283 lastCatchBody = catchList->getCatchBody();
1284 SourceLocation rParenLoc = catchList->getRParenLoc();
1285 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1286 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1287 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1288 assert((*rParenBuf == ')') && "bogus @catch paren location");
1289 assert((*bodyBuf == '{') && "bogus @catch body location");
1290
1291 buf += "1) { id _tmp = _caught;";
1292 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1293 buf.c_str(), buf.size());
1294 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001295 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001296 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001297 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001298 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001299 sawIdTypedCatch = true;
1300 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001301 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001302
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001303 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001304 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001305 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001306 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001307 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001308 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001309 }
1310 }
1311 // Now rewrite the body...
1312 lastCatchBody = catchList->getCatchBody();
1313 SourceLocation rParenLoc = catchList->getRParenLoc();
1314 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1315 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1316 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1317 assert((*rParenBuf == ')') && "bogus @catch paren location");
1318 assert((*bodyBuf == '{') && "bogus @catch body location");
1319
1320 buf = " = _caught;";
1321 // Here we replace ") {" with "= _caught;" (which initializes and
1322 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001323 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001324 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001325 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001326 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001327 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001328 catchList = catchList->getNextCatchStmt();
1329 }
1330 // Complete the catch list...
1331 if (lastCatchBody) {
1332 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1333 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1334 assert((*bodyBuf == '}') && "bogus @catch body location");
1335 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1336 buf = " } } /* @catch end */\n";
1337
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001338 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001339
1340 // Set lastCurlyLoc
1341 lastCurlyLoc = lastCatchBody->getLocEnd();
1342 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001343 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001344 startLoc = finalStmt->getLocStart();
1345 startBuf = SM->getCharacterData(startLoc);
1346 assert((*startBuf == '@') && "bogus @finally start");
1347
1348 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001349 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001350
1351 Stmt *body = finalStmt->getFinallyBody();
1352 SourceLocation startLoc = body->getLocStart();
1353 SourceLocation endLoc = body->getLocEnd();
1354 const char *startBuf = SM->getCharacterData(startLoc);
1355 const char *endBuf = SM->getCharacterData(endLoc);
1356 assert((*startBuf == '{') && "bogus @finally body location");
1357 assert((*endBuf == '}') && "bogus @finally body location");
1358
1359 startLoc = startLoc.getFileLocWithOffset(1);
1360 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001361 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001362 endLoc = endLoc.getFileLocWithOffset(-1);
1363 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001364 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001365
1366 // Set lastCurlyLoc
1367 lastCurlyLoc = body->getLocEnd();
1368 }
1369 // Now emit the final closing curly brace...
1370 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1371 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001372 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001373 return 0;
1374}
1375
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001376Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001377 return 0;
1378}
1379
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001380Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001381 return 0;
1382}
1383
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001384// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001385// the throw expression is typically a message expression that's already
1386// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001387Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001388 // Get the start location and compute the semi location.
1389 SourceLocation startLoc = S->getLocStart();
1390 const char *startBuf = SM->getCharacterData(startLoc);
1391
1392 assert((*startBuf == '@') && "bogus @throw location");
1393
1394 std::string buf;
1395 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001396 if (S->getThrowExpr())
1397 buf = "objc_exception_throw(";
1398 else // add an implicit argument
1399 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001400 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001401 const char *semiBuf = strchr(startBuf, ';');
1402 assert((*semiBuf == ';') && "@throw: can't find ';'");
1403 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1404 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001405 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001406 return 0;
1407}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001408
Chris Lattnere64b7772007-10-24 16:57:36 +00001409Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001410 // Create a new string expression.
1411 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001412 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001413 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1414 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001415 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1416 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001417 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001418 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001419
Chris Lattner07506182007-11-30 22:53:43 +00001420 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001421 delete Exp;
1422 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001423}
1424
Steve Naroffb42f8412007-11-05 14:50:49 +00001425Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1426 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1427 // Create a call to sel_registerName("selName").
1428 llvm::SmallVector<Expr*, 8> SelExprs;
1429 QualType argType = Context->getPointerType(Context->CharTy);
1430 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1431 Exp->getSelector().getName().size(),
1432 false, argType, SourceLocation(),
1433 SourceLocation()));
1434 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1435 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001436 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001437 delete Exp;
1438 return SelExp;
1439}
1440
Steve Naroff934f2762007-10-24 22:48:43 +00001441CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1442 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001443 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001444 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001445
1446 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001447 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001448
1449 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001450 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001451 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1452
1453 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001454
Steve Naroff934f2762007-10-24 22:48:43 +00001455 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1456}
1457
Steve Naroffd5255f52007-11-01 13:24:47 +00001458static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1459 const char *&startRef, const char *&endRef) {
1460 while (startBuf < endBuf) {
1461 if (*startBuf == '<')
1462 startRef = startBuf; // mark the start.
1463 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001464 if (startRef && *startRef == '<') {
1465 endRef = startBuf; // mark the end.
1466 return true;
1467 }
1468 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001469 }
1470 startBuf++;
1471 }
1472 return false;
1473}
1474
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001475static void scanToNextArgument(const char *&argRef) {
1476 int angle = 0;
1477 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1478 if (*argRef == '<')
1479 angle++;
1480 else if (*argRef == '>')
1481 angle--;
1482 argRef++;
1483 }
1484 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1485}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001486
Steve Naroffd5255f52007-11-01 13:24:47 +00001487bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001488
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001489 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001490 return true;
1491
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001492 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001493 return true;
1494
Steve Naroffd5255f52007-11-01 13:24:47 +00001495 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001496 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001497 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001498 return true; // we have "Class <Protocol> *".
1499 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001500 return false;
1501}
1502
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001503void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001504 SourceLocation Loc;
1505 QualType Type;
1506 const FunctionTypeProto *proto = 0;
1507 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1508 Loc = VD->getLocation();
1509 Type = VD->getType();
1510 }
1511 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1512 Loc = FD->getLocation();
1513 // Check for ObjC 'id' and class types that have been adorned with protocol
1514 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1515 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1516 assert(funcType && "missing function type");
1517 proto = dyn_cast<FunctionTypeProto>(funcType);
1518 if (!proto)
1519 return;
1520 Type = proto->getResultType();
1521 }
1522 else
1523 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001524
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001525 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001526 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001527
1528 const char *endBuf = SM->getCharacterData(Loc);
1529 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001530 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001531 startBuf--; // scan backward (from the decl location) for return type.
1532 const char *startRef = 0, *endRef = 0;
1533 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1534 // Get the locations of the startRef, endRef.
1535 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1536 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1537 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001538 InsertText(LessLoc, "/*", 2);
1539 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001540 }
1541 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001542 if (!proto)
1543 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001544 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001545 const char *startBuf = SM->getCharacterData(Loc);
1546 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001547 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1548 if (needToScanForQualifiers(proto->getArgType(i))) {
1549 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001550
Steve Naroffd5255f52007-11-01 13:24:47 +00001551 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001552 // scan forward (from the decl location) for argument types.
1553 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001554 const char *startRef = 0, *endRef = 0;
1555 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1556 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001557 SourceLocation LessLoc =
1558 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1559 SourceLocation GreaterLoc =
1560 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001561 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001562 InsertText(LessLoc, "/*", 2);
1563 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001564 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001565 startBuf = ++endBuf;
1566 }
1567 else {
1568 while (*startBuf != ')' && *startBuf != ',')
1569 startBuf++; // scan forward (from the decl location) for argument types.
1570 startBuf++;
1571 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001572 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001573}
1574
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001575// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1576void RewriteTest::SynthSelGetUidFunctionDecl() {
1577 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1578 llvm::SmallVector<QualType, 16> ArgTys;
1579 ArgTys.push_back(Context->getPointerType(
1580 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001581 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001582 &ArgTys[0], ArgTys.size(),
1583 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001584 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, NULL,
1585 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001586 SelGetUidIdent, getFuncType,
1587 FunctionDecl::Extern, false, 0);
1588}
1589
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001590// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1591void RewriteTest::SynthGetProtocolFunctionDecl() {
1592 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1593 llvm::SmallVector<QualType, 16> ArgTys;
1594 ArgTys.push_back(Context->getPointerType(
1595 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001596 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001597 &ArgTys[0], ArgTys.size(),
1598 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001599 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, NULL,
1600 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001601 SelGetProtoIdent, getFuncType,
1602 FunctionDecl::Extern, false, 0);
1603}
1604
Steve Naroff09b266e2007-10-30 23:14:51 +00001605void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1606 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001607 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001608 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001609 return;
1610 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001612}
1613
Steve Naroffc0a123c2008-03-11 17:37:02 +00001614// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1615void RewriteTest::SynthSuperContructorFunctionDecl() {
1616 if (SuperContructorFunctionDecl)
1617 return;
1618 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1619 llvm::SmallVector<QualType, 16> ArgTys;
1620 QualType argT = Context->getObjCIdType();
1621 assert(!argT.isNull() && "Can't find 'id' type");
1622 ArgTys.push_back(argT);
1623 ArgTys.push_back(argT);
1624 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1625 &ArgTys[0], ArgTys.size(),
1626 false);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001627 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, NULL,
1628 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001629 msgSendIdent, msgSendType,
1630 FunctionDecl::Extern, false, 0);
1631}
1632
Steve Naroff09b266e2007-10-30 23:14:51 +00001633// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1634void RewriteTest::SynthMsgSendFunctionDecl() {
1635 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1636 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001637 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001638 assert(!argT.isNull() && "Can't find 'id' type");
1639 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001640 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001641 assert(!argT.isNull() && "Can't find 'SEL' type");
1642 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001643 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001644 &ArgTys[0], ArgTys.size(),
1645 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001646 MsgSendFunctionDecl = FunctionDecl::Create(*Context, NULL,
1647 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001648 msgSendIdent, msgSendType,
1649 FunctionDecl::Extern, false, 0);
1650}
1651
Steve Naroff874e2322007-11-15 10:28:18 +00001652// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1653void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1654 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1655 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001656 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1657 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001658 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001659 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1660 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1661 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001662 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001663 assert(!argT.isNull() && "Can't find 'SEL' type");
1664 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001665 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001666 &ArgTys[0], ArgTys.size(),
1667 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001668 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, NULL,
1669 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001670 msgSendIdent, msgSendType,
1671 FunctionDecl::Extern, false, 0);
1672}
1673
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001674// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1675void RewriteTest::SynthMsgSendStretFunctionDecl() {
1676 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1677 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001678 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001679 assert(!argT.isNull() && "Can't find 'id' type");
1680 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001681 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001682 assert(!argT.isNull() && "Can't find 'SEL' type");
1683 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001684 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001685 &ArgTys[0], ArgTys.size(),
1686 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001687 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1688 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001689 msgSendIdent, msgSendType,
1690 FunctionDecl::Extern, false, 0);
1691}
1692
1693// SynthMsgSendSuperStretFunctionDecl -
1694// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1695void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1696 IdentifierInfo *msgSendIdent =
1697 &Context->Idents.get("objc_msgSendSuper_stret");
1698 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner0ed844b2008-04-04 06:12:32 +00001699 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, NULL,
1700 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001701 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001702 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1703 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1704 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001705 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001706 assert(!argT.isNull() && "Can't find 'SEL' type");
1707 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001708 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001709 &ArgTys[0], ArgTys.size(),
1710 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001711 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, NULL,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001712 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001713 msgSendIdent, msgSendType,
1714 FunctionDecl::Extern, false, 0);
1715}
1716
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001717// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1718void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1719 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1720 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001721 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001722 assert(!argT.isNull() && "Can't find 'id' type");
1723 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001724 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001725 assert(!argT.isNull() && "Can't find 'SEL' type");
1726 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001727 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001728 &ArgTys[0], ArgTys.size(),
1729 true /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001730 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, NULL,
1731 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001732 msgSendIdent, msgSendType,
1733 FunctionDecl::Extern, false, 0);
1734}
1735
Steve Naroff09b266e2007-10-30 23:14:51 +00001736// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1737void RewriteTest::SynthGetClassFunctionDecl() {
1738 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1739 llvm::SmallVector<QualType, 16> ArgTys;
1740 ArgTys.push_back(Context->getPointerType(
1741 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001743 &ArgTys[0], ArgTys.size(),
1744 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001745 GetClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1746 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001747 getClassIdent, getClassType,
1748 FunctionDecl::Extern, false, 0);
1749}
1750
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001751// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1752void RewriteTest::SynthGetMetaClassFunctionDecl() {
1753 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1754 llvm::SmallVector<QualType, 16> ArgTys;
1755 ArgTys.push_back(Context->getPointerType(
1756 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001757 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001758 &ArgTys[0], ArgTys.size(),
1759 false /*isVariadic*/);
Chris Lattner0ed844b2008-04-04 06:12:32 +00001760 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, NULL,
1761 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001762 getClassIdent, getClassType,
1763 FunctionDecl::Extern, false, 0);
1764}
1765
Steve Naroffbeaf2992007-11-03 11:27:19 +00001766Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001767 QualType strType = getConstantStringStructType();
1768
1769 std::string S = "__NSConstantStringImpl_";
1770 S += utostr(NumObjCStringLiterals++);
1771
Steve Naroffba92b2e2008-03-27 22:29:16 +00001772 Preamble += "static __NSConstantStringImpl " + S;
1773 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1774 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001775 // The pretty printer for StringLiteral handles escape characters properly.
1776 std::ostringstream prettyBuf;
1777 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001778 Preamble += prettyBuf.str();
1779 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001780 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001781 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001782
Chris Lattner0ed844b2008-04-04 06:12:32 +00001783 FileVarDecl *NewVD = FileVarDecl::Create(*Context, NULL, SourceLocation(),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001784 &Context->Idents.get(S.c_str()), strType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001785 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001786 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1787 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1788 Context->getPointerType(DRE->getType()),
1789 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001790 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001791 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001792 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001793 delete Exp;
1794 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001795}
1796
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001797ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001798 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001799 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1800
1801 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1802 if (!CE) return 0;
1803
1804 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1805 if (!DRE) return 0;
1806
1807 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1808 if (!PVD) return 0;
1809
1810 if (strcmp(PVD->getName(), "self") != 0)
1811 return 0;
1812
1813 // is this id<P1..> type?
1814 if (CE->getType()->isObjCQualifiedIdType())
1815 return 0;
1816 const PointerType *PT = CE->getType()->getAsPointerType();
1817 if (!PT) return 0;
1818
1819 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1820 if (!IT) return 0;
1821
1822 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1823 return 0;
1824
1825 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001826}
1827
1828// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1829QualType RewriteTest::getSuperStructType() {
1830 if (!SuperStructDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001831 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001832 SourceLocation(),
1833 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001834 QualType FieldTypes[2];
1835
1836 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001837 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001838 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001839 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001840 // Create fields
1841 FieldDecl *FieldDecls[2];
1842
1843 for (unsigned i = 0; i < 2; ++i)
Chris Lattner0ed844b2008-04-04 06:12:32 +00001844 FieldDecls[i] = FieldDecl::Create(*Context, SuperStructDecl,
1845 SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001846 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001847
1848 SuperStructDecl->defineBody(FieldDecls, 4);
1849 }
1850 return Context->getTagDeclType(SuperStructDecl);
1851}
1852
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001853QualType RewriteTest::getConstantStringStructType() {
1854 if (!ConstantStringDecl) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001855 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, NULL,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001856 SourceLocation(),
1857 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001858 QualType FieldTypes[4];
1859
1860 // struct objc_object *receiver;
1861 FieldTypes[0] = Context->getObjCIdType();
1862 // int flags;
1863 FieldTypes[1] = Context->IntTy;
1864 // char *str;
1865 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1866 // long length;
1867 FieldTypes[3] = Context->LongTy;
1868 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001869 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001870
1871 for (unsigned i = 0; i < 4; ++i)
Chris Lattner0ed844b2008-04-04 06:12:32 +00001872 FieldDecls[i] = FieldDecl::Create(*Context, ConstantStringDecl,
1873 SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001874 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001875
1876 ConstantStringDecl->defineBody(FieldDecls, 4);
1877 }
1878 return Context->getTagDeclType(ConstantStringDecl);
1879}
1880
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001881Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001882 if (!SelGetUidFunctionDecl)
1883 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001884 if (!MsgSendFunctionDecl)
1885 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001886 if (!MsgSendSuperFunctionDecl)
1887 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001888 if (!MsgSendStretFunctionDecl)
1889 SynthMsgSendStretFunctionDecl();
1890 if (!MsgSendSuperStretFunctionDecl)
1891 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001892 if (!MsgSendFpretFunctionDecl)
1893 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001894 if (!GetClassFunctionDecl)
1895 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001896 if (!GetMetaClassFunctionDecl)
1897 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001898
Steve Naroff874e2322007-11-15 10:28:18 +00001899 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001900 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1901 // May need to use objc_msgSend_stret() as well.
1902 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001903 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001904 QualType resultType = mDecl->getResultType();
1905 if (resultType.getCanonicalType()->isStructureType()
1906 || resultType.getCanonicalType()->isUnionType())
1907 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001908 else if (resultType.getCanonicalType()->isRealFloatingType())
1909 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001910 }
Steve Naroff874e2322007-11-15 10:28:18 +00001911
Steve Naroff934f2762007-10-24 22:48:43 +00001912 // Synthesize a call to objc_msgSend().
1913 llvm::SmallVector<Expr*, 8> MsgExprs;
1914 IdentifierInfo *clsName = Exp->getClassName();
1915
1916 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1917 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001918 if (!strcmp(clsName->getName(), "super")) {
1919 MsgSendFlavor = MsgSendSuperFunctionDecl;
1920 if (MsgSendStretFlavor)
1921 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1922 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1923
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001925 CurMethodDecl->getClassInterface()->getSuperClass();
1926
1927 llvm::SmallVector<Expr*, 4> InitExprs;
1928
1929 // set the receiver to self, the first argument to all methods.
1930 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001932 SourceLocation()));
1933 llvm::SmallVector<Expr*, 8> ClsExprs;
1934 QualType argType = Context->getPointerType(Context->CharTy);
1935 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1936 SuperDecl->getIdentifier()->getLength(),
1937 false, argType, SourceLocation(),
1938 SourceLocation()));
1939 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1940 &ClsExprs[0],
1941 ClsExprs.size());
1942 // To turn off a warning, type-cast to 'id'
1943 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001945 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1946 // struct objc_super
1947 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001948 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001949
Steve Naroff23f41272008-03-11 18:14:26 +00001950 if (LangOpts.Microsoft) {
1951 SynthSuperContructorFunctionDecl();
1952 // Simulate a contructor call...
1953 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1954 superType, SourceLocation());
1955 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1956 superType, SourceLocation());
1957 } else {
1958 // (struct objc_super) { <exprs from above> }
1959 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1960 &InitExprs[0], InitExprs.size(),
1961 SourceLocation());
1962 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1963 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001964 // struct objc_super *
1965 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1966 Context->getPointerType(SuperRep->getType()),
1967 SourceLocation());
1968 MsgExprs.push_back(Unop);
1969 } else {
1970 llvm::SmallVector<Expr*, 8> ClsExprs;
1971 QualType argType = Context->getPointerType(Context->CharTy);
1972 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1973 clsName->getLength(),
1974 false, argType, SourceLocation(),
1975 SourceLocation()));
1976 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1977 &ClsExprs[0],
1978 ClsExprs.size());
1979 MsgExprs.push_back(Cls);
1980 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001981 } else { // instance message.
1982 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001983
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001985 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001986 if (MsgSendStretFlavor)
1987 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001988 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1989
1990 llvm::SmallVector<Expr*, 4> InitExprs;
1991
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001992 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001994 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001995
1996 llvm::SmallVector<Expr*, 8> ClsExprs;
1997 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001998 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1999 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002000 false, argType, SourceLocation(),
2001 SourceLocation()));
2002 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002003 &ClsExprs[0],
2004 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002005 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002006 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002007 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002008 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002009 // struct objc_super
2010 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002011 Expr *SuperRep;
2012
2013 if (LangOpts.Microsoft) {
2014 SynthSuperContructorFunctionDecl();
2015 // Simulate a contructor call...
2016 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2017 superType, SourceLocation());
2018 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2019 superType, SourceLocation());
2020 } else {
2021 // (struct objc_super) { <exprs from above> }
2022 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2023 &InitExprs[0], InitExprs.size(),
2024 SourceLocation());
2025 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2026 }
Steve Naroff874e2322007-11-15 10:28:18 +00002027 // struct objc_super *
2028 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2029 Context->getPointerType(SuperRep->getType()),
2030 SourceLocation());
2031 MsgExprs.push_back(Unop);
2032 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002033 // Remove all type-casts because it may contain objc-style types; e.g.
2034 // Foo<Proto> *.
2035 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2036 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002037 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002038 MsgExprs.push_back(recExpr);
2039 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002040 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002041 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002042 llvm::SmallVector<Expr*, 8> SelExprs;
2043 QualType argType = Context->getPointerType(Context->CharTy);
2044 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2045 Exp->getSelector().getName().size(),
2046 false, argType, SourceLocation(),
2047 SourceLocation()));
2048 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2049 &SelExprs[0], SelExprs.size());
2050 MsgExprs.push_back(SelExp);
2051
2052 // Now push any user supplied arguments.
2053 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002054 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002055 // Make all implicit casts explicit...ICE comes in handy:-)
2056 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2057 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2059 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002060 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002061 }
2062 // Make id<P...> cast into an 'id' cast.
2063 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002065 while ((CE = dyn_cast<CastExpr>(userExpr)))
2066 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002068 userExpr, SourceLocation());
2069 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002070 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002071 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002072 // We've transferred the ownership to MsgExprs. Null out the argument in
2073 // the original expression, since we will delete it below.
2074 Exp->setArg(i, 0);
2075 }
Steve Naroffab972d32007-11-04 22:37:50 +00002076 // Generate the funky cast.
2077 CastExpr *cast;
2078 llvm::SmallVector<QualType, 8> ArgTypes;
2079 QualType returnType;
2080
2081 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002082 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2083 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2084 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002085 ArgTypes.push_back(Context->getObjCIdType());
2086 ArgTypes.push_back(Context->getObjCSelType());
2087 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002088 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002089 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002090 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2091 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002092 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002093 ArgTypes.push_back(t);
2094 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2096 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002097 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002099 }
2100 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002101 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002102
2103 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002104 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2105 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002106
2107 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2108 // If we don't do this cast, we get the following bizarre warning/note:
2109 // xx.m:13: warning: function called through a non-compatible type
2110 // xx.m:13: note: if this code is reached, the program will abort
2111 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2112 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002113
Steve Naroffab972d32007-11-04 22:37:50 +00002114 // Now do the "normal" pointer to function cast.
2115 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002116 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002117 // If we don't have a method decl, force a variadic cast.
2118 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002119 castType = Context->getPointerType(castType);
2120 cast = new CastExpr(castType, cast, SourceLocation());
2121
2122 // Don't forget the parens to enforce the proper binding.
2123 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2124
2125 const FunctionType *FT = msgSendType->getAsFunctionType();
2126 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2127 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002128 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002129 if (MsgSendStretFlavor) {
2130 // We have the method which returns a struct/union. Must also generate
2131 // call to objc_msgSend_stret and hang both varieties on a conditional
2132 // expression which dictate which one to envoke depending on size of
2133 // method's return type.
2134
2135 // Create a reference to the objc_msgSend_stret() declaration.
2136 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2137 SourceLocation());
2138 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2139 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2140 SourceLocation());
2141 // Now do the "normal" pointer to function cast.
2142 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002143 &ArgTypes[0], ArgTypes.size(),
2144 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002145 castType = Context->getPointerType(castType);
2146 cast = new CastExpr(castType, cast, SourceLocation());
2147
2148 // Don't forget the parens to enforce the proper binding.
2149 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2150
2151 FT = msgSendType->getAsFunctionType();
2152 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2153 FT->getResultType(), SourceLocation());
2154
2155 // Build sizeof(returnType)
2156 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2157 returnType, Context->getSizeType(),
2158 SourceLocation(), SourceLocation());
2159 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2160 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2161 // For X86 it is more complicated and some kind of target specific routine
2162 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002163 unsigned IntSize =
2164 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002165 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2166 Context->IntTy,
2167 SourceLocation());
2168 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2169 BinaryOperator::LE,
2170 Context->IntTy,
2171 SourceLocation());
2172 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2173 ConditionalOperator *CondExpr =
2174 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002175 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002176 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002177 return ReplacingStmt;
2178}
2179
2180Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2181 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002182 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002183 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002184
Chris Lattnere64b7772007-10-24 16:57:36 +00002185 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002186 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002187}
2188
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002189/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2190/// call to objc_getProtocol("proto-name").
2191Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2192 if (!GetProtocolFunctionDecl)
2193 SynthGetProtocolFunctionDecl();
2194 // Create a call to objc_getProtocol("ProtocolName").
2195 llvm::SmallVector<Expr*, 8> ProtoExprs;
2196 QualType argType = Context->getPointerType(Context->CharTy);
2197 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2198 strlen(Exp->getProtocol()->getName()),
2199 false, argType, SourceLocation(),
2200 SourceLocation()));
2201 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2202 &ProtoExprs[0],
2203 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002204 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002205 delete Exp;
2206 return ProtoExp;
2207
2208}
2209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002211/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002212void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002213 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002214 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2215 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002216 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002218 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002220 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002221 SourceLocation LocStart = CDecl->getLocStart();
2222 SourceLocation LocEnd = CDecl->getLocEnd();
2223
2224 const char *startBuf = SM->getCharacterData(LocStart);
2225 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002226 // If no ivars and no root or if its root, directly or indirectly,
2227 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002228 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2229 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002231 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002232 return;
2233 }
2234
2235 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002237 Result += "\nstruct ";
2238 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002239 if (LangOpts.Microsoft)
2240 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002241
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002242 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002243 const char *cursor = strchr(startBuf, '{');
2244 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002246
2247 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002248 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002250 Result = "\n struct ";
2251 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002252 Result += "_IMPL ";
2253 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002254 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002255
2256 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002257 SourceLocation OnePastCurly =
2258 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2259 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002260 }
2261 cursor++; // past '{'
2262
2263 // Now comment out any visibility specifiers.
2264 while (cursor < endBuf) {
2265 if (*cursor == '@') {
2266 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002267 // Skip whitespace.
2268 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2269 /*scan*/;
2270
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002271 // FIXME: presence of @public, etc. inside comment results in
2272 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002273 if (!strncmp(cursor, "public", strlen("public")) ||
2274 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002275 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002276 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002277 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002278 // FIXME: If there are cases where '<' is used in ivar declaration part
2279 // of user code, then scan the ivar list and use needToScanForQualifiers
2280 // for type checking.
2281 else if (*cursor == '<') {
2282 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002283 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002284 cursor = strchr(cursor, '>');
2285 cursor++;
2286 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002287 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002288 }
Steve Narofffea763e82007-11-14 19:25:57 +00002289 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002290 }
Steve Narofffea763e82007-11-14 19:25:57 +00002291 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002292 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002293 } else { // we don't have any instance variables - insert super struct.
2294 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2295 Result += " {\n struct ";
2296 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002297 Result += "_IMPL ";
2298 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002299 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002300 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002301 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002302 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002303 if (!ObjCSynthesizedStructs.insert(CDecl))
2304 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002305}
2306
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002307// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002308/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002309void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002310 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002311 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002312 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002313 const char *ClassName,
2314 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002315 if (MethodBegin == MethodEnd) return;
2316
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002317 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002318 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002319 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002320 SEL _cmd;
2321 char *method_types;
2322 void *_imp;
2323 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002324 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002325 Result += "\nstruct _objc_method {\n";
2326 Result += "\tSEL _cmd;\n";
2327 Result += "\tchar *method_types;\n";
2328 Result += "\tvoid *_imp;\n";
2329 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002330
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002331 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002332 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002333
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002334 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002335
2336 /* struct {
2337 struct _objc_method_list *next_method;
2338 int method_count;
2339 struct _objc_method method_list[];
2340 }
2341 */
2342 Result += "\nstatic struct {\n";
2343 Result += "\tstruct _objc_method_list *next_method;\n";
2344 Result += "\tint method_count;\n";
2345 Result += "\tstruct _objc_method method_list[";
2346 Result += utostr(MethodEnd-MethodBegin);
2347 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002348 Result += prefix;
2349 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2350 Result += "_METHODS_";
2351 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002352 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002353 Result += IsInstanceMethod ? "inst" : "cls";
2354 Result += "_meth\")))= ";
2355 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002356
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002357 Result += "\t,{{(SEL)\"";
2358 Result += (*MethodBegin)->getSelector().getName().c_str();
2359 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002360 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002361 Result += "\", \"";
2362 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002363 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002364 Result += MethodInternalNames[*MethodBegin];
2365 Result += "}\n";
2366 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2367 Result += "\t ,{(SEL)\"";
2368 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002369 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002371 Result += "\", \"";
2372 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002373 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002374 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002375 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002376 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002377 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002378}
2379
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002380/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2381void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002382 int NumProtocols,
2383 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002384 const char *ClassName,
2385 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002386 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002387 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002388 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002389 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002390 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002391 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002392 /* struct protocol_methods {
2393 SEL _cmd;
2394 char *method_types;
2395 }
2396 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002397 Result += "\nstruct protocol_methods {\n";
2398 Result += "\tSEL _cmd;\n";
2399 Result += "\tchar *method_types;\n";
2400 Result += "};\n";
2401
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002402 objc_protocol_methods = true;
2403 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002404 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2405 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002406 /* struct _objc_protocol_method_list {
2407 int protocol_method_count;
2408 struct protocol_methods protocols[];
2409 }
2410 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002411 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002412 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002413 Result += "\tstruct protocol_methods protocols[";
2414 Result += utostr(NumMethods);
2415 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002416 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002417 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002418 "{\n\t" + utostr(NumMethods) + "\n";
2419
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002420 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002422 E = PDecl->instmeth_end(); I != E; ++I) {
2423 if (I == PDecl->instmeth_begin())
2424 Result += "\t ,{{(SEL)\"";
2425 else
2426 Result += "\t ,{(SEL)\"";
2427 Result += (*I)->getSelector().getName().c_str();
2428 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002429 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002430 Result += "\", \"";
2431 Result += MethodTypeString;
2432 Result += "\"}\n";
2433 }
2434 Result += "\t }\n};\n";
2435 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002436
2437 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002438 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002439 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002440 /* struct _objc_protocol_method_list {
2441 int protocol_method_count;
2442 struct protocol_methods protocols[];
2443 }
2444 */
2445 Result += "\nstatic struct {\n";
2446 Result += "\tint protocol_method_count;\n";
2447 Result += "\tstruct protocol_methods protocols[";
2448 Result += utostr(NumMethods);
2449 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002450 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002451 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002452 "{\n\t";
2453 Result += utostr(NumMethods);
2454 Result += "\n";
2455
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002456 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002458 E = PDecl->classmeth_end(); I != E; ++I) {
2459 if (I == PDecl->classmeth_begin())
2460 Result += "\t ,{{(SEL)\"";
2461 else
2462 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002463 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002464 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002466 Result += "\", \"";
2467 Result += MethodTypeString;
2468 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002469 }
2470 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002471 }
2472 // Output:
2473 /* struct _objc_protocol {
2474 // Objective-C 1.0 extensions
2475 struct _objc_protocol_extension *isa;
2476 char *protocol_name;
2477 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002478 struct _objc_protocol_method_list *instance_methods;
2479 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002480 };
2481 */
2482 static bool objc_protocol = false;
2483 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484 Result += "\nstruct _objc_protocol {\n";
2485 Result += "\tstruct _objc_protocol_extension *isa;\n";
2486 Result += "\tchar *protocol_name;\n";
2487 Result += "\tstruct _objc_protocol **protocol_list;\n";
2488 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2489 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2490 Result += "};\n";
2491
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002492 objc_protocol = true;
2493 }
2494
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002495 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2496 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002497 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002498 "{\n\t0, \"";
2499 Result += PDecl->getName();
2500 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002501 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002502 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002503 Result += PDecl->getName();
2504 Result += ", ";
2505 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002506 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002507 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002508 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002509 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002510 Result += PDecl->getName();
2511 Result += "\n";
2512 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002513 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002514 Result += "0\n";
2515 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002516 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002517 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002518 /* struct _objc_protocol_list {
2519 struct _objc_protocol_list *next;
2520 int protocol_count;
2521 struct _objc_protocol *class_protocols[];
2522 }
2523 */
2524 Result += "\nstatic struct {\n";
2525 Result += "\tstruct _objc_protocol_list *next;\n";
2526 Result += "\tint protocol_count;\n";
2527 Result += "\tstruct _objc_protocol *class_protocols[";
2528 Result += utostr(NumProtocols);
2529 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002530 Result += prefix;
2531 Result += "_PROTOCOLS_";
2532 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002533 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002534 "{\n\t0, ";
2535 Result += utostr(NumProtocols);
2536 Result += "\n";
2537
2538 Result += "\t,{&_OBJC_PROTOCOL_";
2539 Result += Protocols[0]->getName();
2540 Result += " \n";
2541
2542 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002543 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002544 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002545 Result += PDecl->getName();
2546 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002547 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002548 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002549 }
2550}
2551
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002552/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002553/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002554void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002555 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002557 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002558 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002559 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2560 CDecl = CDecl->getNextClassCategory())
2561 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2562 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002563
Chris Lattnereb44eee2007-12-23 01:40:15 +00002564 std::string FullCategoryName = ClassDecl->getName();
2565 FullCategoryName += '_';
2566 FullCategoryName += IDecl->getName();
2567
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002568 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002569 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002570 true, "CATEGORY_", FullCategoryName.c_str(),
2571 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002572
2573 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002574 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002575 false, "CATEGORY_", FullCategoryName.c_str(),
2576 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002577
2578 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002579 // Null CDecl is case of a category implementation with no category interface
2580 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002581 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002582 CDecl->getNumReferencedProtocols(),
2583 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002584 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002585
2586 /* struct _objc_category {
2587 char *category_name;
2588 char *class_name;
2589 struct _objc_method_list *instance_methods;
2590 struct _objc_method_list *class_methods;
2591 struct _objc_protocol_list *protocols;
2592 // Objective-C 1.0 extensions
2593 uint32_t size; // sizeof (struct _objc_category)
2594 struct _objc_property_list *instance_properties; // category's own
2595 // @property decl.
2596 };
2597 */
2598
2599 static bool objc_category = false;
2600 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002601 Result += "\nstruct _objc_category {\n";
2602 Result += "\tchar *category_name;\n";
2603 Result += "\tchar *class_name;\n";
2604 Result += "\tstruct _objc_method_list *instance_methods;\n";
2605 Result += "\tstruct _objc_method_list *class_methods;\n";
2606 Result += "\tstruct _objc_protocol_list *protocols;\n";
2607 Result += "\tunsigned int size;\n";
2608 Result += "\tstruct _objc_property_list *instance_properties;\n";
2609 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002610 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002611 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002612 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2613 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002614 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002615 Result += IDecl->getName();
2616 Result += "\"\n\t, \"";
2617 Result += ClassDecl->getName();
2618 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002619
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002620 if (IDecl->getNumInstanceMethods() > 0) {
2621 Result += "\t, (struct _objc_method_list *)"
2622 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2623 Result += FullCategoryName;
2624 Result += "\n";
2625 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002626 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002627 Result += "\t, 0\n";
2628 if (IDecl->getNumClassMethods() > 0) {
2629 Result += "\t, (struct _objc_method_list *)"
2630 "&_OBJC_CATEGORY_CLASS_METHODS_";
2631 Result += FullCategoryName;
2632 Result += "\n";
2633 }
2634 else
2635 Result += "\t, 0\n";
2636
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002637 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002638 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2639 Result += FullCategoryName;
2640 Result += "\n";
2641 }
2642 else
2643 Result += "\t, 0\n";
2644 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002645}
2646
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002647/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2648/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002649void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2650 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002651 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002652 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002653 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002654 if (LangOpts.Microsoft)
2655 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002656 Result += ", ";
2657 Result += ivar->getName();
2658 Result += ")";
2659}
2660
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002661//===----------------------------------------------------------------------===//
2662// Meta Data Emission
2663//===----------------------------------------------------------------------===//
2664
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002665void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002666 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002667 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002668
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002669 // Explictly declared @interface's are already synthesized.
2670 if (CDecl->ImplicitInterfaceDecl()) {
2671 // FIXME: Implementation of a class with no @interface (legacy) doese not
2672 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002673 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002674 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002675
Chris Lattnerbe6df082007-12-12 07:56:42 +00002676 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002677 unsigned NumIvars = !IDecl->ivar_empty()
2678 ? IDecl->ivar_size()
2679 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002680 if (NumIvars > 0) {
2681 static bool objc_ivar = false;
2682 if (!objc_ivar) {
2683 /* struct _objc_ivar {
2684 char *ivar_name;
2685 char *ivar_type;
2686 int ivar_offset;
2687 };
2688 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002689 Result += "\nstruct _objc_ivar {\n";
2690 Result += "\tchar *ivar_name;\n";
2691 Result += "\tchar *ivar_type;\n";
2692 Result += "\tint ivar_offset;\n";
2693 Result += "};\n";
2694
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002695 objc_ivar = true;
2696 }
2697
Steve Naroff946a6932008-03-11 00:12:29 +00002698 /* struct {
2699 int ivar_count;
2700 struct _objc_ivar ivar_list[nIvars];
2701 };
2702 */
2703 Result += "\nstatic struct {\n";
2704 Result += "\tint ivar_count;\n";
2705 Result += "\tstruct _objc_ivar ivar_list[";
2706 Result += utostr(NumIvars);
2707 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002708 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002709 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002710 "{\n\t";
2711 Result += utostr(NumIvars);
2712 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002713
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002714 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002715 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002716 IVI = IDecl->ivar_begin();
2717 IVE = IDecl->ivar_end();
2718 } else {
2719 IVI = CDecl->ivar_begin();
2720 IVE = CDecl->ivar_end();
2721 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002722 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002723 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002724 Result += "\", \"";
2725 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002726 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2727 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002728 Result += StrEncoding;
2729 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002730 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002731 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002732 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002733 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002734 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002735 Result += "\", \"";
2736 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002737 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2738 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002739 Result += StrEncoding;
2740 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002741 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002742 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002743 }
2744
2745 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002746 }
2747
2748 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002749 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002750 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751
2752 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002753 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002754 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002755
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002757 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002758 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002759 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002760
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002761
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002762 // Declaration of class/meta-class metadata
2763 /* struct _objc_class {
2764 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002765 const char *super_class_name;
2766 char *name;
2767 long version;
2768 long info;
2769 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002770 struct _objc_ivar_list *ivars;
2771 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002772 struct objc_cache *cache;
2773 struct objc_protocol_list *protocols;
2774 const char *ivar_layout;
2775 struct _objc_class_ext *ext;
2776 };
2777 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002778 static bool objc_class = false;
2779 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002780 Result += "\nstruct _objc_class {\n";
2781 Result += "\tstruct _objc_class *isa;\n";
2782 Result += "\tconst char *super_class_name;\n";
2783 Result += "\tchar *name;\n";
2784 Result += "\tlong version;\n";
2785 Result += "\tlong info;\n";
2786 Result += "\tlong instance_size;\n";
2787 Result += "\tstruct _objc_ivar_list *ivars;\n";
2788 Result += "\tstruct _objc_method_list *methods;\n";
2789 Result += "\tstruct objc_cache *cache;\n";
2790 Result += "\tstruct _objc_protocol_list *protocols;\n";
2791 Result += "\tconst char *ivar_layout;\n";
2792 Result += "\tstruct _objc_class_ext *ext;\n";
2793 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002794 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002795 }
2796
2797 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002798 ObjCInterfaceDecl *RootClass = 0;
2799 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002800 while (SuperClass) {
2801 RootClass = SuperClass;
2802 SuperClass = SuperClass->getSuperClass();
2803 }
2804 SuperClass = CDecl->getSuperClass();
2805
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002806 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2807 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002808 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002809 "{\n\t(struct _objc_class *)\"";
2810 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2811 Result += "\"";
2812
2813 if (SuperClass) {
2814 Result += ", \"";
2815 Result += SuperClass->getName();
2816 Result += "\", \"";
2817 Result += CDecl->getName();
2818 Result += "\"";
2819 }
2820 else {
2821 Result += ", 0, \"";
2822 Result += CDecl->getName();
2823 Result += "\"";
2824 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002825 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002826 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002827 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002828 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002829 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002830 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002831 Result += "\n";
2832 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002833 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002834 Result += ", 0\n";
2835 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002836 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002837 Result += CDecl->getName();
2838 Result += ",0,0\n";
2839 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002840 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002841 Result += "\t,0,0,0,0\n";
2842 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002843
2844 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002845 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2846 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002847 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002848 "{\n\t&_OBJC_METACLASS_";
2849 Result += CDecl->getName();
2850 if (SuperClass) {
2851 Result += ", \"";
2852 Result += SuperClass->getName();
2853 Result += "\", \"";
2854 Result += CDecl->getName();
2855 Result += "\"";
2856 }
2857 else {
2858 Result += ", 0, \"";
2859 Result += CDecl->getName();
2860 Result += "\"";
2861 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002862 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002863 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002864 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002865 Result += ",0";
2866 else {
2867 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002868 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002869 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002870 if (LangOpts.Microsoft)
2871 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002872 Result += ")";
2873 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002874 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002875 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 Result += CDecl->getName();
2877 Result += "\n\t";
2878 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002879 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += ",0";
2881 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002882 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002883 Result += CDecl->getName();
2884 Result += ", 0\n\t";
2885 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002886 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002887 Result += ",0,0";
2888 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002889 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002890 Result += CDecl->getName();
2891 Result += ", 0,0\n";
2892 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002893 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002894 Result += ",0,0,0\n";
2895 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002896}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002897
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002898/// RewriteImplementations - This routine rewrites all method implementations
2899/// and emits meta-data.
2900
2901void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002902 int ClsDefCount = ClassImplementation.size();
2903 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002904
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002905 if (ClsDefCount == 0 && CatDefCount == 0)
2906 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002907 // Rewrite implemented methods
2908 for (int i = 0; i < ClsDefCount; i++)
2909 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002910
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002911 for (int i = 0; i < CatDefCount; i++)
2912 RewriteImplementationDecl(CategoryImplementation[i]);
2913
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002914 // This is needed for use of offsetof
2915 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002916
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002917 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002918 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002919 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002920
2921 // For each implemented category, write out all its meta data.
2922 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002923 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002924
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002925 // Write objc_symtab metadata
2926 /*
2927 struct _objc_symtab
2928 {
2929 long sel_ref_cnt;
2930 SEL *refs;
2931 short cls_def_cnt;
2932 short cat_def_cnt;
2933 void *defs[cls_def_cnt + cat_def_cnt];
2934 };
2935 */
2936
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002937 Result += "\nstruct _objc_symtab {\n";
2938 Result += "\tlong sel_ref_cnt;\n";
2939 Result += "\tSEL *refs;\n";
2940 Result += "\tshort cls_def_cnt;\n";
2941 Result += "\tshort cat_def_cnt;\n";
2942 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2943 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002944
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002945 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002946 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002947 Result += "\t0, 0, " + utostr(ClsDefCount)
2948 + ", " + utostr(CatDefCount) + "\n";
2949 for (int i = 0; i < ClsDefCount; i++) {
2950 Result += "\t,&_OBJC_CLASS_";
2951 Result += ClassImplementation[i]->getName();
2952 Result += "\n";
2953 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002954
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002955 for (int i = 0; i < CatDefCount; i++) {
2956 Result += "\t,&_OBJC_CATEGORY_";
2957 Result += CategoryImplementation[i]->getClassInterface()->getName();
2958 Result += "_";
2959 Result += CategoryImplementation[i]->getName();
2960 Result += "\n";
2961 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002962
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002963 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002964
2965 // Write objc_module metadata
2966
2967 /*
2968 struct _objc_module {
2969 long version;
2970 long size;
2971 const char *name;
2972 struct _objc_symtab *symtab;
2973 }
2974 */
2975
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002976 Result += "\nstruct _objc_module {\n";
2977 Result += "\tlong version;\n";
2978 Result += "\tlong size;\n";
2979 Result += "\tconst char *name;\n";
2980 Result += "\tstruct _objc_symtab *symtab;\n";
2981 Result += "};\n\n";
2982 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002983 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002984 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2985 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002986 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002987
2988 if (LangOpts.Microsoft) {
2989 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2990 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2991 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2992 Result += "&_OBJC_MODULES;\n";
2993 Result += "#pragma data_seg(pop)\n\n";
2994 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002995}
Chris Lattner311ff022007-10-16 22:36:42 +00002996