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