blob: d80b924ef04c099985874618836bd419fee598e5 [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
Chris Lattnerc68ab772008-03-22 00:08:40 +000087 std::ostream &OutFile;
88
Steve Naroffba92b2e2008-03-27 22:29:16 +000089 std::string Preamble;
90
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000091 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000092 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000093 void Initialize(ASTContext &context);
94
Chris Lattner8a12c272007-10-11 18:38:32 +000095
Chris Lattnerf04da132007-10-24 17:06:59 +000096 // Top Level Driver code.
97 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000098 void HandleDeclInMainFile(Decl *D);
Chris Lattnerc68ab772008-03-22 00:08:40 +000099 RewriteTest(bool isHeader, std::ostream &outFile,
100 Diagnostic &D, const LangOptions &LOpts)
101 : Diags(D), LangOpts(LOpts), OutFile(outFile) {
Steve Narofff69cc5d2008-01-30 19:17:43 +0000102 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +0000103 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
104 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +0000105 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000106 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000107
108 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000109 // If replacement succeeded or warning disabled return with no warning.
110 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000111 return;
112
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000113 SourceRange Range = Old->getSourceRange();
114 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
115 0, 0, &Range, 1);
116 }
117
Steve Naroffba92b2e2008-03-27 22:29:16 +0000118 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
119 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000120 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000122 SilenceRewriteMacroWarning)
123 return;
124
125 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
126 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000127
Chris Lattneraadaf782008-01-31 19:51:04 +0000128 void RemoveText(SourceLocation Loc, unsigned StrLen) {
129 // If removal succeeded or warning disabled return with no warning.
130 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
131 return;
132
133 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
134 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000135
Chris Lattneraadaf782008-01-31 19:51:04 +0000136 void ReplaceText(SourceLocation Start, unsigned OrigLength,
137 const char *NewStr, unsigned NewLength) {
138 // If removal succeeded or warning disabled return with no warning.
139 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
140 SilenceRewriteMacroWarning)
141 return;
142
143 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
144 }
145
Chris Lattnerf04da132007-10-24 17:06:59 +0000146 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000147 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000148 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000149 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000150 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
151 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000152 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000153 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
154 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
155 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
156 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
157 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000158 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000159 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000161 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000162 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000163 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000164 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000167 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000168 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000169 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000170 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000171 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000172 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000173 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000175 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000176 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
177 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
178 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000179 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
180 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000181 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
182 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000183 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000184 Stmt *RewriteBreakStmt(BreakStmt *S);
185 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000186 void SynthCountByEnumWithState(std::string &buf);
187
Steve Naroff09b266e2007-10-30 23:14:51 +0000188 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000189 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000190 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000191 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000192 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000193 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000194 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000195 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000196 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000197 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000198
Chris Lattnerf04da132007-10-24 17:06:59 +0000199 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000201 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000202
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000203 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000204 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000205
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000206 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
207 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000208 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000209 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000210 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000211 const char *ClassName,
212 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000213
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000214 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000215 int NumProtocols,
216 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000217 const char *ClassName,
218 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000220 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000221 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
222 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000223 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000224 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000225 };
226}
227
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000228static bool IsHeaderFile(const std::string &Filename) {
229 std::string::size_type DotPos = Filename.rfind('.');
230
231 if (DotPos == std::string::npos) {
232 // no file extension
233 return false;
234 }
235
236 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
237 // C header: .h
238 // C++ header: .hh or .H;
239 return Ext == "h" || Ext == "hh" || Ext == "H";
240}
241
242ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000243 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000244 Diagnostic &Diags,
245 const LangOptions &LOpts) {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000246 // Create the output file.
247
248 std::ostream *Out;
249 if (OutFile == "-") {
250 Out = llvm::cout.stream();
251 } else if (!OutFile.empty()) {
252 Out = new std::ofstream(OutFile.c_str(),
253 std::ios_base::binary|std::ios_base::out);
254 } else if (InFile == "-") {
255 Out = llvm::cout.stream();
256 } else {
257 llvm::sys::Path Path(InFile);
258 Path.eraseSuffix();
259 Path.appendSuffix("cpp");
260 Out = new std::ofstream(Path.toString().c_str(),
261 std::ios_base::binary|std::ios_base::out);
262 }
263
264 return new RewriteTest(IsHeaderFile(InFile), *Out, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000265}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000266
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000267void RewriteTest::Initialize(ASTContext &context) {
268 Context = &context;
269 SM = &Context->getSourceManager();
270 MsgSendFunctionDecl = 0;
271 MsgSendSuperFunctionDecl = 0;
272 MsgSendStretFunctionDecl = 0;
273 MsgSendSuperStretFunctionDecl = 0;
274 MsgSendFpretFunctionDecl = 0;
275 GetClassFunctionDecl = 0;
276 GetMetaClassFunctionDecl = 0;
277 SelGetUidFunctionDecl = 0;
278 CFStringFunctionDecl = 0;
279 GetProtocolFunctionDecl = 0;
280 ConstantStringClassReference = 0;
281 NSStringRecord = 0;
282 CurMethodDecl = 0;
283 SuperStructDecl = 0;
284 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000285 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000286 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287
288 // Get the ID and start/end of the main file.
289 MainFileID = SM->getMainFileID();
290 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
291 MainFileStart = MainBuf->getBufferStart();
292 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000293
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000294 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000295
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000296 // declaring objc_selector outside the parameter list removes a silly
297 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000298 if (IsHeader)
299 Preamble = "#pragma once\n";
300 Preamble += "struct objc_selector; struct objc_class;\n";
301 Preamble += "#ifndef OBJC_SUPER\n";
302 Preamble += "struct objc_super { struct objc_object *object; ";
303 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000304 if (LangOpts.Microsoft) {
305 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000306 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
307 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000308 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000309 Preamble += "};\n";
310 Preamble += "#define OBJC_SUPER\n";
311 Preamble += "#endif\n";
312 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
313 Preamble += "typedef struct objc_object Protocol;\n";
314 Preamble += "#define _REWRITER_typedef_Protocol\n";
315 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000316 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000317 Preamble += "extern \"C\" {\n";
318 Preamble += "struct objc_object *objc_msgSend";
319 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
320 Preamble += "extern struct objc_object *objc_msgSendSuper";
321 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
322 Preamble += "extern struct objc_object *objc_msgSend_stret";
323 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
324 Preamble += "extern struct objc_object *objc_msgSendSuper_stret";
325 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
326 Preamble += "extern struct objc_object *objc_msgSend_fpret";
327 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
328 Preamble += "struct objc_object *objc_getClass";
329 Preamble += "(const char *);\n";
330 Preamble += "extern struct objc_object *objc_getMetaClass";
331 Preamble += "(const char *);\n";
332 Preamble += "extern void objc_exception_throw(struct objc_object *);\n";
333 Preamble += "extern void objc_exception_try_enter(void *);\n";
334 Preamble += "extern void objc_exception_try_exit(void *);\n";
335 Preamble += "extern struct objc_object *objc_exception_extract(void *);\n";
336 Preamble += "extern int objc_exception_match";
337 Preamble += "(struct objc_class *, struct objc_object *, ...);\n";
338 Preamble += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000339 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000340 Preamble += "} // end extern \"C\"\n";
341 Preamble += "#include <objc/objc.h>\n";
342 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
343 Preamble += "struct __objcFastEnumerationState {\n\t";
344 Preamble += "unsigned long state;\n\t";
345 Preamble += "id *itemsPtr;\n\t";
346 Preamble += "unsigned long *mutationsPtr;\n\t";
347 Preamble += "unsigned long extra[5];\n};\n";
348 Preamble += "#define __FASTENUMERATIONSTATE\n";
349 Preamble += "#endif\n";
350 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
351 Preamble += "struct __NSConstantStringImpl {\n";
352 Preamble += " int *isa;\n";
353 Preamble += " int flags;\n";
354 Preamble += " char *str;\n";
355 Preamble += " long length;\n";
356 Preamble += "};\n";
357 Preamble += "extern int __CFConstantStringClassReference[];\n";
358 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
359 Preamble += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000360 if (LangOpts.Microsoft)
Steve Naroffba92b2e2008-03-27 22:29:16 +0000361 Preamble += "#define __attribute__(X)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000362}
363
364
Chris Lattnerf04da132007-10-24 17:06:59 +0000365//===----------------------------------------------------------------------===//
366// Top Level Driver Code
367//===----------------------------------------------------------------------===//
368
Chris Lattner8a12c272007-10-11 18:38:32 +0000369void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000370 // Two cases: either the decl could be in the main file, or it could be in a
371 // #included file. If the former, rewrite it now. If the later, check to see
372 // if we rewrote the #include/#import.
373 SourceLocation Loc = D->getLocation();
374 Loc = SM->getLogicalLoc(Loc);
375
376 // If this is for a builtin, ignore it.
377 if (Loc.isInvalid()) return;
378
Steve Naroffebf2b562007-10-23 23:50:29 +0000379 // Look for built-in declarations that we need to refer during the rewrite.
380 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000381 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000382 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
383 // declared in <Foundation/NSString.h>
384 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
385 ConstantStringClassReference = FVD;
386 return;
387 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000388 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000389 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000390 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000391 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000392 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000393 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000394 } else if (ObjCForwardProtocolDecl *FP =
395 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000396 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000397 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000398 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000399 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
400 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000401}
402
Chris Lattnerf04da132007-10-24 17:06:59 +0000403/// HandleDeclInMainFile - This is called for each top-level decl defined in the
404/// main file of the input.
405void RewriteTest::HandleDeclInMainFile(Decl *D) {
406 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
407 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000408 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000409
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000411 if (Stmt *Body = MD->getBody()) {
412 //Body->dump();
413 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000414 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000415 CurMethodDecl = 0;
416 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000417 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000418 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000419 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000420 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000421 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000423 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000424 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000426 if (VD->getInit())
427 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
428 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000429 // Nothing yet.
430}
431
432RewriteTest::~RewriteTest() {
433 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000434
435 // Rewrite tabs if we care.
436 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000437
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000438 RewriteInclude();
439
Steve Naroffba92b2e2008-03-27 22:29:16 +0000440 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
441 Preamble.c_str(), Preamble.size(), false);
442
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000443 // Rewrite Objective-c meta data*
444 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000445 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000446
Chris Lattnerf04da132007-10-24 17:06:59 +0000447 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
448 // we are done.
449 if (const RewriteBuffer *RewriteBuf =
450 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000451 //printf("Changed:\n");
Chris Lattnerc68ab772008-03-22 00:08:40 +0000452 OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000453 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000454 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000455 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000456 // Emit metadata.
Chris Lattnerc68ab772008-03-22 00:08:40 +0000457 OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000458}
459
Chris Lattnerf04da132007-10-24 17:06:59 +0000460//===----------------------------------------------------------------------===//
461// Syntactic (non-AST) Rewriting Code
462//===----------------------------------------------------------------------===//
463
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000464void RewriteTest::RewriteInclude() {
465 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
466 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
467 const char *MainBufStart = MainBuf.first;
468 const char *MainBufEnd = MainBuf.second;
469 size_t ImportLen = strlen("import");
470 size_t IncludeLen = strlen("include");
471
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000472 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000473 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
474 if (*BufPtr == '#') {
475 if (++BufPtr == MainBufEnd)
476 return;
477 while (*BufPtr == ' ' || *BufPtr == '\t')
478 if (++BufPtr == MainBufEnd)
479 return;
480 if (!strncmp(BufPtr, "import", ImportLen)) {
481 // replace import with include
482 SourceLocation ImportLoc =
483 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000484 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000485 BufPtr += ImportLen;
486 }
487 }
488 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000489}
490
Chris Lattnerf04da132007-10-24 17:06:59 +0000491void RewriteTest::RewriteTabs() {
492 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
493 const char *MainBufStart = MainBuf.first;
494 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000495
Chris Lattnerf04da132007-10-24 17:06:59 +0000496 // Loop over the whole file, looking for tabs.
497 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
498 if (*BufPtr != '\t')
499 continue;
500
501 // Okay, we found a tab. This tab will turn into at least one character,
502 // but it depends on which 'virtual column' it is in. Compute that now.
503 unsigned VCol = 0;
504 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
505 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
506 ++VCol;
507
508 // Okay, now that we know the virtual column, we know how many spaces to
509 // insert. We assume 8-character tab-stops.
510 unsigned Spaces = 8-(VCol & 7);
511
512 // Get the location of the tab.
513 SourceLocation TabLoc =
514 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
515
516 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000517 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000518 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000519}
520
521
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000522void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000523 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000524 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000525
526 // Get the start location and compute the semi location.
527 SourceLocation startLoc = ClassDecl->getLocation();
528 const char *startBuf = SM->getCharacterData(startLoc);
529 const char *semiPtr = strchr(startBuf, ';');
530
531 // Translate to typedef's that forward reference structs with the same name
532 // as the class. As a convenience, we include the original declaration
533 // as a comment.
534 std::string typedefString;
535 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000536 typedefString.append(startBuf, semiPtr-startBuf+1);
537 typedefString += "\n";
538 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000539 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000540 typedefString += "#ifndef _REWRITER_typedef_";
541 typedefString += ForwardDecl->getName();
542 typedefString += "\n";
543 typedefString += "#define _REWRITER_typedef_";
544 typedefString += ForwardDecl->getName();
545 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000546 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000547 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000548 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000549 }
550
551 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000552 ReplaceText(startLoc, semiPtr-startBuf+1,
553 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000554}
555
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000556void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000557 SourceLocation LocStart = Method->getLocStart();
558 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000559
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000560 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000561 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000562 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000563 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000564 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000565 }
566}
567
Chris Lattner55d13b42008-03-16 21:23:50 +0000568void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000569{
Chris Lattner55d13b42008-03-16 21:23:50 +0000570 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000571 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000572 SourceLocation Loc = Property->getLocation();
573
Chris Lattneraadaf782008-01-31 19:51:04 +0000574 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000575
576 // FIXME: handle properties that are declared across multiple lines.
577 }
578}
579
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000581 SourceLocation LocStart = CatDecl->getLocStart();
582
583 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000584 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000585
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000586 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000587 E = CatDecl->instmeth_end(); I != E; ++I)
588 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000590 E = CatDecl->classmeth_end(); I != E; ++I)
591 RewriteMethodDeclaration(*I);
592
Steve Naroff423cb562007-10-30 13:30:57 +0000593 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000594 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000595}
596
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000598 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000599
Steve Naroff752d6ef2007-10-30 16:42:30 +0000600 SourceLocation LocStart = PDecl->getLocStart();
601
602 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000603 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000604
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000605 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000606 E = PDecl->instmeth_end(); I != E; ++I)
607 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000609 E = PDecl->classmeth_end(); I != E; ++I)
610 RewriteMethodDeclaration(*I);
611
Steve Naroff752d6ef2007-10-30 16:42:30 +0000612 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000613 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000614 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000615
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000616 // Must comment out @optional/@required
617 const char *startBuf = SM->getCharacterData(LocStart);
618 const char *endBuf = SM->getCharacterData(LocEnd);
619 for (const char *p = startBuf; p < endBuf; p++) {
620 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
621 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000622 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000623 ReplaceText(OptionalLoc, strlen("@optional"),
624 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000625
626 }
627 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
628 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000629 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000630 ReplaceText(OptionalLoc, strlen("@required"),
631 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000632
633 }
634 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000635}
636
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000637void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000638 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000639 if (LocStart.isInvalid())
640 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000641 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000642 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000643}
644
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000646 std::string &ResultStr) {
647 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000648 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000649 ResultStr += "id";
650 else
651 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000652 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000653
654 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000655 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000656
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000657 if (OMD->isInstance())
658 NameStr += "_I_";
659 else
660 NameStr += "_C_";
661
662 NameStr += OMD->getClassInterface()->getName();
663 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000664
665 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000666 if (ObjCCategoryImplDecl *CID =
667 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000668 NameStr += CID->getName();
669 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670 }
671 // Append selector names, replacing ':' with '_'
672 const char *selName = OMD->getSelector().getName().c_str();
673 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000674 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000675 else {
676 std::string selString = OMD->getSelector().getName();
677 int len = selString.size();
678 for (int i = 0; i < len; i++)
679 if (selString[i] == ':')
680 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000681 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000682 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000683 // Remember this name for metadata emission
684 MethodInternalNames[OMD] = NameStr;
685 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000686
687 // Rewrite arguments
688 ResultStr += "(";
689
690 // invisible arguments
691 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000693 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000694 if (!LangOpts.Microsoft) {
695 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
696 ResultStr += "struct ";
697 }
698 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000699 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000700 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000701 }
702 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000704
705 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000707 ResultStr += " _cmd";
708
709 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000710 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000711 ParmVarDecl *PDecl = OMD->getParamDecl(i);
712 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000714 ResultStr += "id";
715 else
716 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717 ResultStr += " ";
718 ResultStr += PDecl->getName();
719 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000720 if (OMD->isVariadic())
721 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000722 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000723
724}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000725void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000726 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
727 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000728
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000729 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000730 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000731 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000732 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000733
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000735 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
736 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000737 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 ObjCMethodDecl *OMD = *I;
739 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000740 SourceLocation LocStart = OMD->getLocStart();
741 SourceLocation LocEnd = OMD->getBody()->getLocStart();
742
743 const char *startBuf = SM->getCharacterData(LocStart);
744 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000745 ReplaceText(LocStart, endBuf-startBuf,
746 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000747 }
748
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000749 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000750 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
751 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000752 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 ObjCMethodDecl *OMD = *I;
754 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 SourceLocation LocStart = OMD->getLocStart();
756 SourceLocation LocEnd = OMD->getBody()->getLocStart();
757
758 const char *startBuf = SM->getCharacterData(LocStart);
759 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(LocStart, endBuf-startBuf,
761 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000763 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000764 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000765 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000766 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000767}
768
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000770 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000771 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000772 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000773 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000774 ResultStr += ClassDecl->getName();
775 ResultStr += "\n";
776 ResultStr += "#define _REWRITER_typedef_";
777 ResultStr += ClassDecl->getName();
778 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000779 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000780 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000781 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000782 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000784 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000786
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000787 RewriteProperties(ClassDecl->getNumPropertyDecl(),
788 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000789 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000790 E = ClassDecl->instmeth_end(); I != E; ++I)
791 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000792 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000793 E = ClassDecl->classmeth_end(); I != E; ++I)
794 RewriteMethodDeclaration(*I);
795
Steve Naroff2feac5e2007-10-30 03:43:13 +0000796 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000797 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000798}
799
Steve Naroff7e3411b2007-11-15 02:58:25 +0000800Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000802 if (CurMethodDecl) {
803 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
804 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
805 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000806 // lookup which class implements the instance variable.
807 ObjCInterfaceDecl *clsDeclared = 0;
808 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
809 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000810
811 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000812 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000813 RecName += "_IMPL";
814 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattnerc63e6602008-03-15 21:32:50 +0000815 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct,
816 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000817 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
818 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
819 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
820 // Don't forget the parens to enforce the proper binding.
821 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
822 if (IV->isFreeIvar()) {
823 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
824 ReplaceStmt(IV, ME);
825 delete IV;
826 return ME;
827 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000828 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000829 // Cannot delete IV->getBase(), since PE points to it.
830 // Replace the old base with the cast. This is important when doing
831 // embedded rewrites. For example, [newInv->_container addObject:0].
832 IV->setBase(PE);
833 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000834 }
835 }
836 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000837 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000838 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000839 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
840 IV->getLocation(), D->getType());
841 ReplaceStmt(IV, Replacement);
842 delete IV;
843 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000844}
845
Chris Lattnerf04da132007-10-24 17:06:59 +0000846//===----------------------------------------------------------------------===//
847// Function Body / Expression rewriting
848//===----------------------------------------------------------------------===//
849
Steve Narofff3473a72007-11-09 15:20:18 +0000850Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000851 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
852 isa<DoStmt>(S) || isa<ForStmt>(S))
853 Stmts.push_back(S);
854 else if (isa<ObjCForCollectionStmt>(S)) {
855 Stmts.push_back(S);
856 ObjCBcLabelNo.push_back(++BcLabelCount);
857 }
858
Chris Lattner338d1e22008-01-31 05:10:40 +0000859 SourceLocation OrigStmtEnd = S->getLocEnd();
860
861 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000862 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
863 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000864 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000865 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000866 if (newStmt)
867 *CI = newStmt;
868 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000869
870 // Handle specific things.
871 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
872 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000873
874 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
875 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000876
877 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
878 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000879
Steve Naroffbeaf2992007-11-03 11:27:19 +0000880 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
881 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000882
Steve Naroff934f2762007-10-24 22:48:43 +0000883 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
884 // Before we rewrite it, put the original message expression in a comment.
885 SourceLocation startLoc = MessExpr->getLocStart();
886 SourceLocation endLoc = MessExpr->getLocEnd();
887
888 const char *startBuf = SM->getCharacterData(startLoc);
889 const char *endBuf = SM->getCharacterData(endLoc);
890
891 std::string messString;
892 messString += "// ";
893 messString.append(startBuf, endBuf-startBuf+1);
894 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000895
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000896 // FIXME: Missing definition of
897 // InsertText(clang::SourceLocation, char const*, unsigned int).
898 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000899 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000900 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000901 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000902 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000903
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000904 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
905 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000906
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000907 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
908 return RewriteObjCSynchronizedStmt(StmtTry);
909
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000910 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
911 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000912
913 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
914 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000915
916 if (ObjCForCollectionStmt *StmtForCollection =
917 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000918 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000919 if (BreakStmt *StmtBreakStmt =
920 dyn_cast<BreakStmt>(S))
921 return RewriteBreakStmt(StmtBreakStmt);
922 if (ContinueStmt *StmtContinueStmt =
923 dyn_cast<ContinueStmt>(S))
924 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000925
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000926 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
927 isa<DoStmt>(S) || isa<ForStmt>(S)) {
928 assert(!Stmts.empty() && "Statement stack is empty");
929 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
930 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
931 && "Statement stack mismatch");
932 Stmts.pop_back();
933 }
Steve Naroff874e2322007-11-15 10:28:18 +0000934#if 0
935 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
936 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
937 // Get the new text.
938 std::ostringstream Buf;
939 Replacement->printPretty(Buf);
940 const std::string &Str = Buf.str();
941
942 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000943 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000944 delete S;
945 return Replacement;
946 }
947#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000948 // Return this stmt unmodified.
949 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000950}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000951
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000952/// SynthCountByEnumWithState - To print:
953/// ((unsigned int (*)
954/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
955/// (void *)objc_msgSend)((id)l_collection,
956/// sel_registerName(
957/// "countByEnumeratingWithState:objects:count:"),
958/// &enumState,
959/// (id *)items, (unsigned int)16)
960///
961void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
962 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
963 "id *, unsigned int))(void *)objc_msgSend)";
964 buf += "\n\t\t";
965 buf += "((id)l_collection,\n\t\t";
966 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
967 buf += "\n\t\t";
968 buf += "&enumState, "
969 "(id *)items, (unsigned int)16)";
970}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000971
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000972/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
973/// statement to exit to its outer synthesized loop.
974///
975Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
976 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
977 return S;
978 // replace break with goto __break_label
979 std::string buf;
980
981 SourceLocation startLoc = S->getLocStart();
982 buf = "goto __break_label_";
983 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000984 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000985
986 return 0;
987}
988
989/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
990/// statement to continue with its inner synthesized loop.
991///
992Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
993 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
994 return S;
995 // replace continue with goto __continue_label
996 std::string buf;
997
998 SourceLocation startLoc = S->getLocStart();
999 buf = "goto __continue_label_";
1000 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001002
1003 return 0;
1004}
1005
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001006/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001007/// It rewrites:
1008/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001009
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001010/// Into:
1011/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001012/// type elem;
1013/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001014/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001015/// id l_collection = (id)collection;
1016/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1017/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001018/// if (limit) {
1019/// unsigned long startMutations = *enumState.mutationsPtr;
1020/// do {
1021/// unsigned long counter = 0;
1022/// do {
1023/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001024/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001025/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001026/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001027/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001028/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001029/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1030/// objects:items count:16]);
1031/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001032/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001033/// }
1034/// else
1035/// elem = nil;
1036/// }
1037///
Chris Lattner338d1e22008-01-31 05:10:40 +00001038Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1039 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001040 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1041 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1042 "ObjCForCollectionStmt Statement stack mismatch");
1043 assert(!ObjCBcLabelNo.empty() &&
1044 "ObjCForCollectionStmt - Label No stack empty");
1045
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001046 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001047 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001048 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001049 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001050 std::string buf;
1051 buf = "\n{\n\t";
1052 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1053 // type elem;
1054 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001055 elementTypeAsString = ElementType.getAsString();
1056 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001057 buf += " ";
1058 elementName = DS->getDecl()->getName();
1059 buf += elementName;
1060 buf += ";\n\t";
1061 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001062 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001063 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001064 elementTypeAsString = DR->getDecl()->getType().getAsString();
1065 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001066 else
1067 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1068
1069 // struct __objcFastEnumerationState enumState = { 0 };
1070 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1071 // id items[16];
1072 buf += "id items[16];\n\t";
1073 // id l_collection = (id)
1074 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001075 // Find start location of 'collection' the hard way!
1076 const char *startCollectionBuf = startBuf;
1077 startCollectionBuf += 3; // skip 'for'
1078 startCollectionBuf = strchr(startCollectionBuf, '(');
1079 startCollectionBuf++; // skip '('
1080 // find 'in' and skip it.
1081 while (*startCollectionBuf != ' ' ||
1082 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1083 (*(startCollectionBuf+3) != ' ' &&
1084 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1085 startCollectionBuf++;
1086 startCollectionBuf += 3;
1087
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001088 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001089 ReplaceText(startLoc, startCollectionBuf - startBuf,
1090 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001091 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001092 SourceLocation rightParenLoc = S->getRParenLoc();
1093 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1094 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001095 buf = ";\n\t";
1096
1097 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1098 // objects:items count:16];
1099 // which is synthesized into:
1100 // unsigned int limit =
1101 // ((unsigned int (*)
1102 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1103 // (void *)objc_msgSend)((id)l_collection,
1104 // sel_registerName(
1105 // "countByEnumeratingWithState:objects:count:"),
1106 // (struct __objcFastEnumerationState *)&state,
1107 // (id *)items, (unsigned int)16);
1108 buf += "unsigned long limit =\n\t\t";
1109 SynthCountByEnumWithState(buf);
1110 buf += ";\n\t";
1111 /// if (limit) {
1112 /// unsigned long startMutations = *enumState.mutationsPtr;
1113 /// do {
1114 /// unsigned long counter = 0;
1115 /// do {
1116 /// if (startMutations != *enumState.mutationsPtr)
1117 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001118 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001119 buf += "if (limit) {\n\t";
1120 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1121 buf += "do {\n\t\t";
1122 buf += "unsigned long counter = 0;\n\t\t";
1123 buf += "do {\n\t\t\t";
1124 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1125 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1126 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001127 buf += " = (";
1128 buf += elementTypeAsString;
1129 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001130 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001131 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001132
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001133 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134 /// } while (counter < limit);
1135 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1136 /// objects:items count:16]);
1137 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001138 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001139 /// }
1140 /// else
1141 /// elem = nil;
1142 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001143 ///
1144 buf = ";\n\t";
1145 buf += "__continue_label_";
1146 buf += utostr(ObjCBcLabelNo.back());
1147 buf += ": ;";
1148 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001149 buf += "} while (counter < limit);\n\t";
1150 buf += "} while (limit = ";
1151 SynthCountByEnumWithState(buf);
1152 buf += ");\n\t";
1153 buf += elementName;
1154 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001155 buf += "__break_label_";
1156 buf += utostr(ObjCBcLabelNo.back());
1157 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158 buf += "}\n\t";
1159 buf += "else\n\t\t";
1160 buf += elementName;
1161 buf += " = nil;\n";
1162 buf += "}\n";
1163 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001164 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001165 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001166 Stmts.pop_back();
1167 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001168 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001169}
1170
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001171/// RewriteObjCSynchronizedStmt -
1172/// This routine rewrites @synchronized(expr) stmt;
1173/// into:
1174/// objc_sync_enter(expr);
1175/// @try stmt @finally { objc_sync_exit(expr); }
1176///
1177Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1178 // Get the start location and compute the semi location.
1179 SourceLocation startLoc = S->getLocStart();
1180 const char *startBuf = SM->getCharacterData(startLoc);
1181
1182 assert((*startBuf == '@') && "bogus @synchronized location");
1183
1184 std::string buf;
1185 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001186 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001187 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1188 const char *endBuf = SM->getCharacterData(endLoc);
1189 endBuf++;
1190 const char *rparenBuf = strchr(endBuf, ')');
1191 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1192 buf = ");\n";
1193 // declare a new scope with two variables, _stack and _rethrow.
1194 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1195 buf += "int buf[18/*32-bit i386*/];\n";
1196 buf += "char *pointers[4];} _stack;\n";
1197 buf += "id volatile _rethrow = 0;\n";
1198 buf += "objc_exception_try_enter(&_stack);\n";
1199 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001200 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001201 startLoc = S->getSynchBody()->getLocEnd();
1202 startBuf = SM->getCharacterData(startLoc);
1203
1204 assert((*startBuf == '}') && "bogus @try block");
1205 SourceLocation lastCurlyLoc = startLoc;
1206 buf = "}\nelse {\n";
1207 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1208 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1209 // FIXME: This must be objc_sync_exit(syncExpr);
1210 buf += " objc_sync_exit();\n";
1211 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1212 buf += "}\n";
1213 buf += "}";
1214
Chris Lattneraadaf782008-01-31 19:51:04 +00001215 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001216 return 0;
1217}
1218
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001219Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001220 // Get the start location and compute the semi location.
1221 SourceLocation startLoc = S->getLocStart();
1222 const char *startBuf = SM->getCharacterData(startLoc);
1223
1224 assert((*startBuf == '@') && "bogus @try location");
1225
1226 std::string buf;
1227 // declare a new scope with two variables, _stack and _rethrow.
1228 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1229 buf += "int buf[18/*32-bit i386*/];\n";
1230 buf += "char *pointers[4];} _stack;\n";
1231 buf += "id volatile _rethrow = 0;\n";
1232 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001233 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001234
Chris Lattneraadaf782008-01-31 19:51:04 +00001235 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001236
1237 startLoc = S->getTryBody()->getLocEnd();
1238 startBuf = SM->getCharacterData(startLoc);
1239
1240 assert((*startBuf == '}') && "bogus @try block");
1241
1242 SourceLocation lastCurlyLoc = startLoc;
1243
1244 startLoc = startLoc.getFileLocWithOffset(1);
1245 buf = " /* @catch begin */ else {\n";
1246 buf += " id _caught = objc_exception_extract(&_stack);\n";
1247 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001248 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001249 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1250 buf += " else { /* @catch continue */";
1251
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001252 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001253
1254 bool sawIdTypedCatch = false;
1255 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001256 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001257 while (catchList) {
1258 Stmt *catchStmt = catchList->getCatchParamStmt();
1259
1260 if (catchList == S->getCatchStmts())
1261 buf = "if ("; // we are generating code for the first catch clause
1262 else
1263 buf = "else if (";
1264 startLoc = catchList->getLocStart();
1265 startBuf = SM->getCharacterData(startLoc);
1266
1267 assert((*startBuf == '@') && "bogus @catch location");
1268
1269 const char *lParenLoc = strchr(startBuf, '(');
1270
Steve Naroffbe4b3332008-02-01 22:08:12 +00001271 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001272 // Now rewrite the body...
1273 lastCatchBody = catchList->getCatchBody();
1274 SourceLocation rParenLoc = catchList->getRParenLoc();
1275 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1276 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1277 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1278 assert((*rParenBuf == ')') && "bogus @catch paren location");
1279 assert((*bodyBuf == '{') && "bogus @catch body location");
1280
1281 buf += "1) { id _tmp = _caught;";
1282 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1283 buf.c_str(), buf.size());
1284 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001285 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001286 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001287 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001288 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001289 sawIdTypedCatch = true;
1290 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001291 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001292
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001293 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001294 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001295 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001296 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001297 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001298 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001299 }
1300 }
1301 // Now rewrite the body...
1302 lastCatchBody = catchList->getCatchBody();
1303 SourceLocation rParenLoc = catchList->getRParenLoc();
1304 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1305 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1306 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1307 assert((*rParenBuf == ')') && "bogus @catch paren location");
1308 assert((*bodyBuf == '{') && "bogus @catch body location");
1309
1310 buf = " = _caught;";
1311 // Here we replace ") {" with "= _caught;" (which initializes and
1312 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001313 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001314 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001315 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001316 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001317 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001318 catchList = catchList->getNextCatchStmt();
1319 }
1320 // Complete the catch list...
1321 if (lastCatchBody) {
1322 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1323 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1324 assert((*bodyBuf == '}') && "bogus @catch body location");
1325 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1326 buf = " } } /* @catch end */\n";
1327
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001328 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001329
1330 // Set lastCurlyLoc
1331 lastCurlyLoc = lastCatchBody->getLocEnd();
1332 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001333 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001334 startLoc = finalStmt->getLocStart();
1335 startBuf = SM->getCharacterData(startLoc);
1336 assert((*startBuf == '@') && "bogus @finally start");
1337
1338 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001339 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001340
1341 Stmt *body = finalStmt->getFinallyBody();
1342 SourceLocation startLoc = body->getLocStart();
1343 SourceLocation endLoc = body->getLocEnd();
1344 const char *startBuf = SM->getCharacterData(startLoc);
1345 const char *endBuf = SM->getCharacterData(endLoc);
1346 assert((*startBuf == '{') && "bogus @finally body location");
1347 assert((*endBuf == '}') && "bogus @finally body location");
1348
1349 startLoc = startLoc.getFileLocWithOffset(1);
1350 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001351 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001352 endLoc = endLoc.getFileLocWithOffset(-1);
1353 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001354 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001355
1356 // Set lastCurlyLoc
1357 lastCurlyLoc = body->getLocEnd();
1358 }
1359 // Now emit the final closing curly brace...
1360 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1361 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001362 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001363 return 0;
1364}
1365
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001366Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001367 return 0;
1368}
1369
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001370Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001371 return 0;
1372}
1373
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001374// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001375// the throw expression is typically a message expression that's already
1376// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001377Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001378 // Get the start location and compute the semi location.
1379 SourceLocation startLoc = S->getLocStart();
1380 const char *startBuf = SM->getCharacterData(startLoc);
1381
1382 assert((*startBuf == '@') && "bogus @throw location");
1383
1384 std::string buf;
1385 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001386 if (S->getThrowExpr())
1387 buf = "objc_exception_throw(";
1388 else // add an implicit argument
1389 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001390 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001391 const char *semiBuf = strchr(startBuf, ';');
1392 assert((*semiBuf == ';') && "@throw: can't find ';'");
1393 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1394 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001395 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001396 return 0;
1397}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001398
Chris Lattnere64b7772007-10-24 16:57:36 +00001399Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001400 // Create a new string expression.
1401 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001402 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001403 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1404 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001405 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1406 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001407 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001408 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001409
Chris Lattner07506182007-11-30 22:53:43 +00001410 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001411 delete Exp;
1412 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001413}
1414
Steve Naroffb42f8412007-11-05 14:50:49 +00001415Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1416 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1417 // Create a call to sel_registerName("selName").
1418 llvm::SmallVector<Expr*, 8> SelExprs;
1419 QualType argType = Context->getPointerType(Context->CharTy);
1420 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1421 Exp->getSelector().getName().size(),
1422 false, argType, SourceLocation(),
1423 SourceLocation()));
1424 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1425 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001426 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001427 delete Exp;
1428 return SelExp;
1429}
1430
Steve Naroff934f2762007-10-24 22:48:43 +00001431CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1432 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001433 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001434 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001435
1436 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001437 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001438
1439 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001440 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001441 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1442
1443 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001444
Steve Naroff934f2762007-10-24 22:48:43 +00001445 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1446}
1447
Steve Naroffd5255f52007-11-01 13:24:47 +00001448static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1449 const char *&startRef, const char *&endRef) {
1450 while (startBuf < endBuf) {
1451 if (*startBuf == '<')
1452 startRef = startBuf; // mark the start.
1453 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001454 if (startRef && *startRef == '<') {
1455 endRef = startBuf; // mark the end.
1456 return true;
1457 }
1458 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001459 }
1460 startBuf++;
1461 }
1462 return false;
1463}
1464
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001465static void scanToNextArgument(const char *&argRef) {
1466 int angle = 0;
1467 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1468 if (*argRef == '<')
1469 angle++;
1470 else if (*argRef == '>')
1471 angle--;
1472 argRef++;
1473 }
1474 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1475}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001476
Steve Naroffd5255f52007-11-01 13:24:47 +00001477bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001478
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001479 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001480 return true;
1481
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001482 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001483 return true;
1484
Steve Naroffd5255f52007-11-01 13:24:47 +00001485 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001486 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001487 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001488 return true; // we have "Class <Protocol> *".
1489 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001490 return false;
1491}
1492
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001493void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001494 SourceLocation Loc;
1495 QualType Type;
1496 const FunctionTypeProto *proto = 0;
1497 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1498 Loc = VD->getLocation();
1499 Type = VD->getType();
1500 }
1501 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1502 Loc = FD->getLocation();
1503 // Check for ObjC 'id' and class types that have been adorned with protocol
1504 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1505 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1506 assert(funcType && "missing function type");
1507 proto = dyn_cast<FunctionTypeProto>(funcType);
1508 if (!proto)
1509 return;
1510 Type = proto->getResultType();
1511 }
1512 else
1513 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001514
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001515 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001516 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001517
1518 const char *endBuf = SM->getCharacterData(Loc);
1519 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001520 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001521 startBuf--; // scan backward (from the decl location) for return type.
1522 const char *startRef = 0, *endRef = 0;
1523 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1524 // Get the locations of the startRef, endRef.
1525 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1526 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1527 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001528 InsertText(LessLoc, "/*", 2);
1529 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001530 }
1531 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001532 if (!proto)
1533 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001534 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001535 const char *startBuf = SM->getCharacterData(Loc);
1536 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001537 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1538 if (needToScanForQualifiers(proto->getArgType(i))) {
1539 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001540
Steve Naroffd5255f52007-11-01 13:24:47 +00001541 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001542 // scan forward (from the decl location) for argument types.
1543 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001544 const char *startRef = 0, *endRef = 0;
1545 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1546 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001547 SourceLocation LessLoc =
1548 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1549 SourceLocation GreaterLoc =
1550 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001551 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001552 InsertText(LessLoc, "/*", 2);
1553 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001554 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001555 startBuf = ++endBuf;
1556 }
1557 else {
1558 while (*startBuf != ')' && *startBuf != ',')
1559 startBuf++; // scan forward (from the decl location) for argument types.
1560 startBuf++;
1561 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001562 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001563}
1564
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001565// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1566void RewriteTest::SynthSelGetUidFunctionDecl() {
1567 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1568 llvm::SmallVector<QualType, 16> ArgTys;
1569 ArgTys.push_back(Context->getPointerType(
1570 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001571 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001572 &ArgTys[0], ArgTys.size(),
1573 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001574 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001575 SelGetUidIdent, getFuncType,
1576 FunctionDecl::Extern, false, 0);
1577}
1578
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001579// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1580void RewriteTest::SynthGetProtocolFunctionDecl() {
1581 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1582 llvm::SmallVector<QualType, 16> ArgTys;
1583 ArgTys.push_back(Context->getPointerType(
1584 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001585 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001586 &ArgTys[0], ArgTys.size(),
1587 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001588 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001589 SelGetProtoIdent, getFuncType,
1590 FunctionDecl::Extern, false, 0);
1591}
1592
Steve Naroff09b266e2007-10-30 23:14:51 +00001593void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1594 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001595 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001596 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001597 return;
1598 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001599 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001600}
1601
Steve Naroffc0a123c2008-03-11 17:37:02 +00001602// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1603void RewriteTest::SynthSuperContructorFunctionDecl() {
1604 if (SuperContructorFunctionDecl)
1605 return;
1606 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1607 llvm::SmallVector<QualType, 16> ArgTys;
1608 QualType argT = Context->getObjCIdType();
1609 assert(!argT.isNull() && "Can't find 'id' type");
1610 ArgTys.push_back(argT);
1611 ArgTys.push_back(argT);
1612 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1613 &ArgTys[0], ArgTys.size(),
1614 false);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001615 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001616 msgSendIdent, msgSendType,
1617 FunctionDecl::Extern, false, 0);
1618}
1619
Steve Naroff09b266e2007-10-30 23:14:51 +00001620// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1621void RewriteTest::SynthMsgSendFunctionDecl() {
1622 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1623 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001624 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001625 assert(!argT.isNull() && "Can't find 'id' type");
1626 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001627 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001628 assert(!argT.isNull() && "Can't find 'SEL' type");
1629 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001630 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001631 &ArgTys[0], ArgTys.size(),
1632 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001633 MsgSendFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001634 msgSendIdent, msgSendType,
1635 FunctionDecl::Extern, false, 0);
1636}
1637
Steve Naroff874e2322007-11-15 10:28:18 +00001638// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1639void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1640 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1641 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001642 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1643 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001644 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1645 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1646 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001648 assert(!argT.isNull() && "Can't find 'SEL' type");
1649 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001650 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001651 &ArgTys[0], ArgTys.size(),
1652 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001653 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001654 msgSendIdent, msgSendType,
1655 FunctionDecl::Extern, false, 0);
1656}
1657
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001658// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1659void RewriteTest::SynthMsgSendStretFunctionDecl() {
1660 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1661 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001662 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001663 assert(!argT.isNull() && "Can't find 'id' type");
1664 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001665 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001666 assert(!argT.isNull() && "Can't find 'SEL' type");
1667 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001668 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001669 &ArgTys[0], ArgTys.size(),
1670 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001671 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001672 msgSendIdent, msgSendType,
1673 FunctionDecl::Extern, false, 0);
1674}
1675
1676// SynthMsgSendSuperStretFunctionDecl -
1677// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1678void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1679 IdentifierInfo *msgSendIdent =
1680 &Context->Idents.get("objc_msgSendSuper_stret");
1681 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001682 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1683 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001684 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1685 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1686 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001687 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001688 assert(!argT.isNull() && "Can't find 'SEL' type");
1689 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001690 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001691 &ArgTys[0], ArgTys.size(),
1692 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001693 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context,
1694 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001695 msgSendIdent, msgSendType,
1696 FunctionDecl::Extern, false, 0);
1697}
1698
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001699// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1700void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1701 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1702 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001703 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001704 assert(!argT.isNull() && "Can't find 'id' type");
1705 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001707 assert(!argT.isNull() && "Can't find 'SEL' type");
1708 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001709 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001710 &ArgTys[0], ArgTys.size(),
1711 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001712 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001713 msgSendIdent, msgSendType,
1714 FunctionDecl::Extern, false, 0);
1715}
1716
Steve Naroff09b266e2007-10-30 23:14:51 +00001717// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1718void RewriteTest::SynthGetClassFunctionDecl() {
1719 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1720 llvm::SmallVector<QualType, 16> ArgTys;
1721 ArgTys.push_back(Context->getPointerType(
1722 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001723 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001724 &ArgTys[0], ArgTys.size(),
1725 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001726 GetClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001727 getClassIdent, getClassType,
1728 FunctionDecl::Extern, false, 0);
1729}
1730
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001731// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1732void RewriteTest::SynthGetMetaClassFunctionDecl() {
1733 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1734 llvm::SmallVector<QualType, 16> ArgTys;
1735 ArgTys.push_back(Context->getPointerType(
1736 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001737 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001738 &ArgTys[0], ArgTys.size(),
1739 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001740 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001741 getClassIdent, getClassType,
1742 FunctionDecl::Extern, false, 0);
1743}
1744
Steve Naroffbeaf2992007-11-03 11:27:19 +00001745Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001746 QualType strType = getConstantStringStructType();
1747
1748 std::string S = "__NSConstantStringImpl_";
1749 S += utostr(NumObjCStringLiterals++);
1750
Steve Naroffba92b2e2008-03-27 22:29:16 +00001751 Preamble += "static __NSConstantStringImpl " + S;
1752 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1753 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001754 // The pretty printer for StringLiteral handles escape characters properly.
1755 std::ostringstream prettyBuf;
1756 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001757 Preamble += prettyBuf.str();
1758 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001759 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001760 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001761
Chris Lattnerc63e6602008-03-15 21:32:50 +00001762 FileVarDecl *NewVD = FileVarDecl::Create(*Context, SourceLocation(),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001763 &Context->Idents.get(S.c_str()), strType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001764 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001765 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1766 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1767 Context->getPointerType(DRE->getType()),
1768 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001769 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001770 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001771 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001772 delete Exp;
1773 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001774}
1775
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001776ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001777 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001778 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1779
1780 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1781 if (!CE) return 0;
1782
1783 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1784 if (!DRE) return 0;
1785
1786 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1787 if (!PVD) return 0;
1788
1789 if (strcmp(PVD->getName(), "self") != 0)
1790 return 0;
1791
1792 // is this id<P1..> type?
1793 if (CE->getType()->isObjCQualifiedIdType())
1794 return 0;
1795 const PointerType *PT = CE->getType()->getAsPointerType();
1796 if (!PT) return 0;
1797
1798 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1799 if (!IT) return 0;
1800
1801 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1802 return 0;
1803
1804 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001805}
1806
1807// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1808QualType RewriteTest::getSuperStructType() {
1809 if (!SuperStructDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001810 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct,
1811 SourceLocation(),
1812 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001813 QualType FieldTypes[2];
1814
1815 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001816 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001817 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001818 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001819 // Create fields
1820 FieldDecl *FieldDecls[2];
1821
1822 for (unsigned i = 0; i < 2; ++i)
Chris Lattner8e25d862008-03-16 00:16:02 +00001823 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1824 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001825
1826 SuperStructDecl->defineBody(FieldDecls, 4);
1827 }
1828 return Context->getTagDeclType(SuperStructDecl);
1829}
1830
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001831QualType RewriteTest::getConstantStringStructType() {
1832 if (!ConstantStringDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001833 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct,
1834 SourceLocation(),
1835 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001836 QualType FieldTypes[4];
1837
1838 // struct objc_object *receiver;
1839 FieldTypes[0] = Context->getObjCIdType();
1840 // int flags;
1841 FieldTypes[1] = Context->IntTy;
1842 // char *str;
1843 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1844 // long length;
1845 FieldTypes[3] = Context->LongTy;
1846 // Create fields
1847 FieldDecl *FieldDecls[2];
1848
1849 for (unsigned i = 0; i < 4; ++i)
Chris Lattner8e25d862008-03-16 00:16:02 +00001850 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1851 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001852
1853 ConstantStringDecl->defineBody(FieldDecls, 4);
1854 }
1855 return Context->getTagDeclType(ConstantStringDecl);
1856}
1857
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001858Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001859 if (!SelGetUidFunctionDecl)
1860 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001861 if (!MsgSendFunctionDecl)
1862 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001863 if (!MsgSendSuperFunctionDecl)
1864 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001865 if (!MsgSendStretFunctionDecl)
1866 SynthMsgSendStretFunctionDecl();
1867 if (!MsgSendSuperStretFunctionDecl)
1868 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001869 if (!MsgSendFpretFunctionDecl)
1870 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001871 if (!GetClassFunctionDecl)
1872 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001873 if (!GetMetaClassFunctionDecl)
1874 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001875
Steve Naroff874e2322007-11-15 10:28:18 +00001876 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001877 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1878 // May need to use objc_msgSend_stret() as well.
1879 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001880 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001881 QualType resultType = mDecl->getResultType();
1882 if (resultType.getCanonicalType()->isStructureType()
1883 || resultType.getCanonicalType()->isUnionType())
1884 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001885 else if (resultType.getCanonicalType()->isRealFloatingType())
1886 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001887 }
Steve Naroff874e2322007-11-15 10:28:18 +00001888
Steve Naroff934f2762007-10-24 22:48:43 +00001889 // Synthesize a call to objc_msgSend().
1890 llvm::SmallVector<Expr*, 8> MsgExprs;
1891 IdentifierInfo *clsName = Exp->getClassName();
1892
1893 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1894 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001895 if (!strcmp(clsName->getName(), "super")) {
1896 MsgSendFlavor = MsgSendSuperFunctionDecl;
1897 if (MsgSendStretFlavor)
1898 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1899 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1900
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001901 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001902 CurMethodDecl->getClassInterface()->getSuperClass();
1903
1904 llvm::SmallVector<Expr*, 4> InitExprs;
1905
1906 // set the receiver to self, the first argument to all methods.
1907 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001908 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001909 SourceLocation()));
1910 llvm::SmallVector<Expr*, 8> ClsExprs;
1911 QualType argType = Context->getPointerType(Context->CharTy);
1912 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1913 SuperDecl->getIdentifier()->getLength(),
1914 false, argType, SourceLocation(),
1915 SourceLocation()));
1916 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1917 &ClsExprs[0],
1918 ClsExprs.size());
1919 // To turn off a warning, type-cast to 'id'
1920 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001922 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1923 // struct objc_super
1924 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001925 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001926
Steve Naroff23f41272008-03-11 18:14:26 +00001927 if (LangOpts.Microsoft) {
1928 SynthSuperContructorFunctionDecl();
1929 // Simulate a contructor call...
1930 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1931 superType, SourceLocation());
1932 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1933 superType, SourceLocation());
1934 } else {
1935 // (struct objc_super) { <exprs from above> }
1936 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1937 &InitExprs[0], InitExprs.size(),
1938 SourceLocation());
1939 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1940 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001941 // struct objc_super *
1942 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1943 Context->getPointerType(SuperRep->getType()),
1944 SourceLocation());
1945 MsgExprs.push_back(Unop);
1946 } else {
1947 llvm::SmallVector<Expr*, 8> ClsExprs;
1948 QualType argType = Context->getPointerType(Context->CharTy);
1949 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1950 clsName->getLength(),
1951 false, argType, SourceLocation(),
1952 SourceLocation()));
1953 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1954 &ClsExprs[0],
1955 ClsExprs.size());
1956 MsgExprs.push_back(Cls);
1957 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001958 } else { // instance message.
1959 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001960
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001961 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001962 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001963 if (MsgSendStretFlavor)
1964 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001965 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1966
1967 llvm::SmallVector<Expr*, 4> InitExprs;
1968
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001969 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001970 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001971 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001972
1973 llvm::SmallVector<Expr*, 8> ClsExprs;
1974 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001975 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1976 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001977 false, argType, SourceLocation(),
1978 SourceLocation()));
1979 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001980 &ClsExprs[0],
1981 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001982 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001983 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001985 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001986 // struct objc_super
1987 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001988 Expr *SuperRep;
1989
1990 if (LangOpts.Microsoft) {
1991 SynthSuperContructorFunctionDecl();
1992 // Simulate a contructor call...
1993 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1994 superType, SourceLocation());
1995 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1996 superType, SourceLocation());
1997 } else {
1998 // (struct objc_super) { <exprs from above> }
1999 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2000 &InitExprs[0], InitExprs.size(),
2001 SourceLocation());
2002 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2003 }
Steve Naroff874e2322007-11-15 10:28:18 +00002004 // struct objc_super *
2005 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2006 Context->getPointerType(SuperRep->getType()),
2007 SourceLocation());
2008 MsgExprs.push_back(Unop);
2009 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002010 // Remove all type-casts because it may contain objc-style types; e.g.
2011 // Foo<Proto> *.
2012 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2013 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002014 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002015 MsgExprs.push_back(recExpr);
2016 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002017 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002018 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002019 llvm::SmallVector<Expr*, 8> SelExprs;
2020 QualType argType = Context->getPointerType(Context->CharTy);
2021 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2022 Exp->getSelector().getName().size(),
2023 false, argType, SourceLocation(),
2024 SourceLocation()));
2025 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2026 &SelExprs[0], SelExprs.size());
2027 MsgExprs.push_back(SelExp);
2028
2029 // Now push any user supplied arguments.
2030 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002031 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002032 // Make all implicit casts explicit...ICE comes in handy:-)
2033 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2034 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2036 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002037 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002038 }
2039 // Make id<P...> cast into an 'id' cast.
2040 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002042 while ((CE = dyn_cast<CastExpr>(userExpr)))
2043 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002044 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002045 userExpr, SourceLocation());
2046 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002047 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002048 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002049 // We've transferred the ownership to MsgExprs. Null out the argument in
2050 // the original expression, since we will delete it below.
2051 Exp->setArg(i, 0);
2052 }
Steve Naroffab972d32007-11-04 22:37:50 +00002053 // Generate the funky cast.
2054 CastExpr *cast;
2055 llvm::SmallVector<QualType, 8> ArgTypes;
2056 QualType returnType;
2057
2058 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002059 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2060 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2061 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062 ArgTypes.push_back(Context->getObjCIdType());
2063 ArgTypes.push_back(Context->getObjCSelType());
2064 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002065 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002066 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2068 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002069 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002070 ArgTypes.push_back(t);
2071 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002072 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2073 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002074 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002075 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002076 }
2077 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002078 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002079
2080 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002081 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2082 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002083
2084 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2085 // If we don't do this cast, we get the following bizarre warning/note:
2086 // xx.m:13: warning: function called through a non-compatible type
2087 // xx.m:13: note: if this code is reached, the program will abort
2088 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2089 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002090
Steve Naroffab972d32007-11-04 22:37:50 +00002091 // Now do the "normal" pointer to function cast.
2092 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002093 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002094 // If we don't have a method decl, force a variadic cast.
2095 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002096 castType = Context->getPointerType(castType);
2097 cast = new CastExpr(castType, cast, SourceLocation());
2098
2099 // Don't forget the parens to enforce the proper binding.
2100 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2101
2102 const FunctionType *FT = msgSendType->getAsFunctionType();
2103 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2104 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002105 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002106 if (MsgSendStretFlavor) {
2107 // We have the method which returns a struct/union. Must also generate
2108 // call to objc_msgSend_stret and hang both varieties on a conditional
2109 // expression which dictate which one to envoke depending on size of
2110 // method's return type.
2111
2112 // Create a reference to the objc_msgSend_stret() declaration.
2113 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2114 SourceLocation());
2115 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2116 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2117 SourceLocation());
2118 // Now do the "normal" pointer to function cast.
2119 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002120 &ArgTypes[0], ArgTypes.size(),
2121 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002122 castType = Context->getPointerType(castType);
2123 cast = new CastExpr(castType, cast, SourceLocation());
2124
2125 // Don't forget the parens to enforce the proper binding.
2126 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2127
2128 FT = msgSendType->getAsFunctionType();
2129 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2130 FT->getResultType(), SourceLocation());
2131
2132 // Build sizeof(returnType)
2133 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2134 returnType, Context->getSizeType(),
2135 SourceLocation(), SourceLocation());
2136 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2137 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2138 // For X86 it is more complicated and some kind of target specific routine
2139 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002140 unsigned IntSize =
2141 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002142 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2143 Context->IntTy,
2144 SourceLocation());
2145 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2146 BinaryOperator::LE,
2147 Context->IntTy,
2148 SourceLocation());
2149 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2150 ConditionalOperator *CondExpr =
2151 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002152 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002153 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002154 return ReplacingStmt;
2155}
2156
2157Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2158 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002159 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002160 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002161
Chris Lattnere64b7772007-10-24 16:57:36 +00002162 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002163 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002164}
2165
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002166/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2167/// call to objc_getProtocol("proto-name").
2168Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2169 if (!GetProtocolFunctionDecl)
2170 SynthGetProtocolFunctionDecl();
2171 // Create a call to objc_getProtocol("ProtocolName").
2172 llvm::SmallVector<Expr*, 8> ProtoExprs;
2173 QualType argType = Context->getPointerType(Context->CharTy);
2174 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2175 strlen(Exp->getProtocol()->getName()),
2176 false, argType, SourceLocation(),
2177 SourceLocation()));
2178 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2179 &ProtoExprs[0],
2180 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002181 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002182 delete Exp;
2183 return ProtoExp;
2184
2185}
2186
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002187/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002188/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002190 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002191 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2192 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002193 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002194 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002195 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002196 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002197 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002198 SourceLocation LocStart = CDecl->getLocStart();
2199 SourceLocation LocEnd = CDecl->getLocEnd();
2200
2201 const char *startBuf = SM->getCharacterData(LocStart);
2202 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002203 // If no ivars and no root or if its root, directly or indirectly,
2204 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002205 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2206 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002207 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002208 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002209 return;
2210 }
2211
2212 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002213 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002214 Result += "\nstruct ";
2215 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002216 if (LangOpts.Microsoft)
2217 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002218
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002219 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002220 const char *cursor = strchr(startBuf, '{');
2221 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002222 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002223
2224 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002225 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002226 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002227 Result = "\n struct ";
2228 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002229 Result += "_IMPL ";
2230 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002231 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002232
2233 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002234 SourceLocation OnePastCurly =
2235 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2236 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002237 }
2238 cursor++; // past '{'
2239
2240 // Now comment out any visibility specifiers.
2241 while (cursor < endBuf) {
2242 if (*cursor == '@') {
2243 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002244 // Skip whitespace.
2245 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2246 /*scan*/;
2247
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002248 // FIXME: presence of @public, etc. inside comment results in
2249 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002250 if (!strncmp(cursor, "public", strlen("public")) ||
2251 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002252 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002253 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002254 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002255 // FIXME: If there are cases where '<' is used in ivar declaration part
2256 // of user code, then scan the ivar list and use needToScanForQualifiers
2257 // for type checking.
2258 else if (*cursor == '<') {
2259 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002260 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002261 cursor = strchr(cursor, '>');
2262 cursor++;
2263 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002264 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002265 }
Steve Narofffea763e82007-11-14 19:25:57 +00002266 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002267 }
Steve Narofffea763e82007-11-14 19:25:57 +00002268 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002269 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002270 } else { // we don't have any instance variables - insert super struct.
2271 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2272 Result += " {\n struct ";
2273 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002274 Result += "_IMPL ";
2275 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002276 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002277 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002278 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002279 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 if (!ObjCSynthesizedStructs.insert(CDecl))
2281 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002282}
2283
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002284// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002285/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002286void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002287 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002288 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002289 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002290 const char *ClassName,
2291 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002292 if (MethodBegin == MethodEnd) return;
2293
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002294 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002295 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002296 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002297 SEL _cmd;
2298 char *method_types;
2299 void *_imp;
2300 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002301 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002302 Result += "\nstruct _objc_method {\n";
2303 Result += "\tSEL _cmd;\n";
2304 Result += "\tchar *method_types;\n";
2305 Result += "\tvoid *_imp;\n";
2306 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002307
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002308 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002309 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002310
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002311 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002312
2313 /* struct {
2314 struct _objc_method_list *next_method;
2315 int method_count;
2316 struct _objc_method method_list[];
2317 }
2318 */
2319 Result += "\nstatic struct {\n";
2320 Result += "\tstruct _objc_method_list *next_method;\n";
2321 Result += "\tint method_count;\n";
2322 Result += "\tstruct _objc_method method_list[";
2323 Result += utostr(MethodEnd-MethodBegin);
2324 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002325 Result += prefix;
2326 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2327 Result += "_METHODS_";
2328 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002329 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002330 Result += IsInstanceMethod ? "inst" : "cls";
2331 Result += "_meth\")))= ";
2332 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002333
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002334 Result += "\t,{{(SEL)\"";
2335 Result += (*MethodBegin)->getSelector().getName().c_str();
2336 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002337 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002338 Result += "\", \"";
2339 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002340 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002341 Result += MethodInternalNames[*MethodBegin];
2342 Result += "}\n";
2343 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2344 Result += "\t ,{(SEL)\"";
2345 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002346 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002347 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002348 Result += "\", \"";
2349 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002350 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002351 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002352 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002353 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002354 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002355}
2356
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002357/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2358void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002359 int NumProtocols,
2360 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002361 const char *ClassName,
2362 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002363 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002364 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002365 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002366 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002367 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002368 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002369 /* struct protocol_methods {
2370 SEL _cmd;
2371 char *method_types;
2372 }
2373 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002374 Result += "\nstruct protocol_methods {\n";
2375 Result += "\tSEL _cmd;\n";
2376 Result += "\tchar *method_types;\n";
2377 Result += "};\n";
2378
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002379 objc_protocol_methods = true;
2380 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002381 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2382 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383 /* struct _objc_protocol_method_list {
2384 int protocol_method_count;
2385 struct protocol_methods protocols[];
2386 }
2387 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002388 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002389 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002390 Result += "\tstruct protocol_methods protocols[";
2391 Result += utostr(NumMethods);
2392 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002393 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002394 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 "{\n\t" + utostr(NumMethods) + "\n";
2396
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002397 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002398 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002399 E = PDecl->instmeth_end(); I != E; ++I) {
2400 if (I == PDecl->instmeth_begin())
2401 Result += "\t ,{{(SEL)\"";
2402 else
2403 Result += "\t ,{(SEL)\"";
2404 Result += (*I)->getSelector().getName().c_str();
2405 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002407 Result += "\", \"";
2408 Result += MethodTypeString;
2409 Result += "\"}\n";
2410 }
2411 Result += "\t }\n};\n";
2412 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002413
2414 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002415 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002416 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002417 /* struct _objc_protocol_method_list {
2418 int protocol_method_count;
2419 struct protocol_methods protocols[];
2420 }
2421 */
2422 Result += "\nstatic struct {\n";
2423 Result += "\tint protocol_method_count;\n";
2424 Result += "\tstruct protocol_methods protocols[";
2425 Result += utostr(NumMethods);
2426 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002427 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002428 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 "{\n\t";
2430 Result += utostr(NumMethods);
2431 Result += "\n";
2432
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002433 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002435 E = PDecl->classmeth_end(); I != E; ++I) {
2436 if (I == PDecl->classmeth_begin())
2437 Result += "\t ,{{(SEL)\"";
2438 else
2439 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002440 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002441 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002442 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002443 Result += "\", \"";
2444 Result += MethodTypeString;
2445 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002446 }
2447 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002448 }
2449 // Output:
2450 /* struct _objc_protocol {
2451 // Objective-C 1.0 extensions
2452 struct _objc_protocol_extension *isa;
2453 char *protocol_name;
2454 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 struct _objc_protocol_method_list *instance_methods;
2456 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002457 };
2458 */
2459 static bool objc_protocol = false;
2460 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002461 Result += "\nstruct _objc_protocol {\n";
2462 Result += "\tstruct _objc_protocol_extension *isa;\n";
2463 Result += "\tchar *protocol_name;\n";
2464 Result += "\tstruct _objc_protocol **protocol_list;\n";
2465 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2466 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2467 Result += "};\n";
2468
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002469 objc_protocol = true;
2470 }
2471
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002472 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2473 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002474 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002475 "{\n\t0, \"";
2476 Result += PDecl->getName();
2477 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002478 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002479 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002480 Result += PDecl->getName();
2481 Result += ", ";
2482 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002483 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002485 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002486 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002487 Result += PDecl->getName();
2488 Result += "\n";
2489 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002490 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002491 Result += "0\n";
2492 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002493 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002494 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002495 /* struct _objc_protocol_list {
2496 struct _objc_protocol_list *next;
2497 int protocol_count;
2498 struct _objc_protocol *class_protocols[];
2499 }
2500 */
2501 Result += "\nstatic struct {\n";
2502 Result += "\tstruct _objc_protocol_list *next;\n";
2503 Result += "\tint protocol_count;\n";
2504 Result += "\tstruct _objc_protocol *class_protocols[";
2505 Result += utostr(NumProtocols);
2506 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002507 Result += prefix;
2508 Result += "_PROTOCOLS_";
2509 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002510 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002511 "{\n\t0, ";
2512 Result += utostr(NumProtocols);
2513 Result += "\n";
2514
2515 Result += "\t,{&_OBJC_PROTOCOL_";
2516 Result += Protocols[0]->getName();
2517 Result += " \n";
2518
2519 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002520 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002521 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002522 Result += PDecl->getName();
2523 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002524 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002525 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002526 }
2527}
2528
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002530/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002532 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002533 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002534 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002536 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2537 CDecl = CDecl->getNextClassCategory())
2538 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2539 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540
Chris Lattnereb44eee2007-12-23 01:40:15 +00002541 std::string FullCategoryName = ClassDecl->getName();
2542 FullCategoryName += '_';
2543 FullCategoryName += IDecl->getName();
2544
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002545 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002547 true, "CATEGORY_", FullCategoryName.c_str(),
2548 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002549
2550 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002552 false, "CATEGORY_", FullCategoryName.c_str(),
2553 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002554
2555 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002556 // Null CDecl is case of a category implementation with no category interface
2557 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002558 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002559 CDecl->getNumReferencedProtocols(),
2560 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002561 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002562
2563 /* struct _objc_category {
2564 char *category_name;
2565 char *class_name;
2566 struct _objc_method_list *instance_methods;
2567 struct _objc_method_list *class_methods;
2568 struct _objc_protocol_list *protocols;
2569 // Objective-C 1.0 extensions
2570 uint32_t size; // sizeof (struct _objc_category)
2571 struct _objc_property_list *instance_properties; // category's own
2572 // @property decl.
2573 };
2574 */
2575
2576 static bool objc_category = false;
2577 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002578 Result += "\nstruct _objc_category {\n";
2579 Result += "\tchar *category_name;\n";
2580 Result += "\tchar *class_name;\n";
2581 Result += "\tstruct _objc_method_list *instance_methods;\n";
2582 Result += "\tstruct _objc_method_list *class_methods;\n";
2583 Result += "\tstruct _objc_protocol_list *protocols;\n";
2584 Result += "\tunsigned int size;\n";
2585 Result += "\tstruct _objc_property_list *instance_properties;\n";
2586 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002587 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002588 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002589 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2590 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002591 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002592 Result += IDecl->getName();
2593 Result += "\"\n\t, \"";
2594 Result += ClassDecl->getName();
2595 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002596
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002597 if (IDecl->getNumInstanceMethods() > 0) {
2598 Result += "\t, (struct _objc_method_list *)"
2599 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2600 Result += FullCategoryName;
2601 Result += "\n";
2602 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002603 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002604 Result += "\t, 0\n";
2605 if (IDecl->getNumClassMethods() > 0) {
2606 Result += "\t, (struct _objc_method_list *)"
2607 "&_OBJC_CATEGORY_CLASS_METHODS_";
2608 Result += FullCategoryName;
2609 Result += "\n";
2610 }
2611 else
2612 Result += "\t, 0\n";
2613
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002614 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002615 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2616 Result += FullCategoryName;
2617 Result += "\n";
2618 }
2619 else
2620 Result += "\t, 0\n";
2621 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002622}
2623
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002624/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2625/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002626void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2627 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002628 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002629 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002630 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002631 if (LangOpts.Microsoft)
2632 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002633 Result += ", ";
2634 Result += ivar->getName();
2635 Result += ")";
2636}
2637
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002638//===----------------------------------------------------------------------===//
2639// Meta Data Emission
2640//===----------------------------------------------------------------------===//
2641
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002642void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002643 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002644 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002645
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002646 // Explictly declared @interface's are already synthesized.
2647 if (CDecl->ImplicitInterfaceDecl()) {
2648 // FIXME: Implementation of a class with no @interface (legacy) doese not
2649 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002650 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002651 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002652
Chris Lattnerbe6df082007-12-12 07:56:42 +00002653 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002654 unsigned NumIvars = !IDecl->ivar_empty()
2655 ? IDecl->ivar_size()
2656 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002657 if (NumIvars > 0) {
2658 static bool objc_ivar = false;
2659 if (!objc_ivar) {
2660 /* struct _objc_ivar {
2661 char *ivar_name;
2662 char *ivar_type;
2663 int ivar_offset;
2664 };
2665 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002666 Result += "\nstruct _objc_ivar {\n";
2667 Result += "\tchar *ivar_name;\n";
2668 Result += "\tchar *ivar_type;\n";
2669 Result += "\tint ivar_offset;\n";
2670 Result += "};\n";
2671
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002672 objc_ivar = true;
2673 }
2674
Steve Naroff946a6932008-03-11 00:12:29 +00002675 /* struct {
2676 int ivar_count;
2677 struct _objc_ivar ivar_list[nIvars];
2678 };
2679 */
2680 Result += "\nstatic struct {\n";
2681 Result += "\tint ivar_count;\n";
2682 Result += "\tstruct _objc_ivar ivar_list[";
2683 Result += utostr(NumIvars);
2684 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002685 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002686 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002687 "{\n\t";
2688 Result += utostr(NumIvars);
2689 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002690
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002691 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002692 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002693 IVI = IDecl->ivar_begin();
2694 IVE = IDecl->ivar_end();
2695 } else {
2696 IVI = CDecl->ivar_begin();
2697 IVE = CDecl->ivar_end();
2698 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002699 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002700 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002701 Result += "\", \"";
2702 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002703 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2704 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002705 Result += StrEncoding;
2706 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002707 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002708 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002709 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002710 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002711 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002712 Result += "\", \"";
2713 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002714 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2715 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002716 Result += StrEncoding;
2717 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002718 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002719 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002720 }
2721
2722 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002723 }
2724
2725 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002726 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002727 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002728
2729 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002731 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002733 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002734 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002735 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002736 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002737
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002738
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002739 // Declaration of class/meta-class metadata
2740 /* struct _objc_class {
2741 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002742 const char *super_class_name;
2743 char *name;
2744 long version;
2745 long info;
2746 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002747 struct _objc_ivar_list *ivars;
2748 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002749 struct objc_cache *cache;
2750 struct objc_protocol_list *protocols;
2751 const char *ivar_layout;
2752 struct _objc_class_ext *ext;
2753 };
2754 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002755 static bool objc_class = false;
2756 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002757 Result += "\nstruct _objc_class {\n";
2758 Result += "\tstruct _objc_class *isa;\n";
2759 Result += "\tconst char *super_class_name;\n";
2760 Result += "\tchar *name;\n";
2761 Result += "\tlong version;\n";
2762 Result += "\tlong info;\n";
2763 Result += "\tlong instance_size;\n";
2764 Result += "\tstruct _objc_ivar_list *ivars;\n";
2765 Result += "\tstruct _objc_method_list *methods;\n";
2766 Result += "\tstruct objc_cache *cache;\n";
2767 Result += "\tstruct _objc_protocol_list *protocols;\n";
2768 Result += "\tconst char *ivar_layout;\n";
2769 Result += "\tstruct _objc_class_ext *ext;\n";
2770 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002771 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002772 }
2773
2774 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002775 ObjCInterfaceDecl *RootClass = 0;
2776 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002777 while (SuperClass) {
2778 RootClass = SuperClass;
2779 SuperClass = SuperClass->getSuperClass();
2780 }
2781 SuperClass = CDecl->getSuperClass();
2782
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002783 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2784 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002785 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002786 "{\n\t(struct _objc_class *)\"";
2787 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2788 Result += "\"";
2789
2790 if (SuperClass) {
2791 Result += ", \"";
2792 Result += SuperClass->getName();
2793 Result += "\", \"";
2794 Result += CDecl->getName();
2795 Result += "\"";
2796 }
2797 else {
2798 Result += ", 0, \"";
2799 Result += CDecl->getName();
2800 Result += "\"";
2801 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002802 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002803 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002804 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002805 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002806 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002807 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808 Result += "\n";
2809 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002810 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002811 Result += ", 0\n";
2812 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002813 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002814 Result += CDecl->getName();
2815 Result += ",0,0\n";
2816 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002817 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002818 Result += "\t,0,0,0,0\n";
2819 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002820
2821 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002822 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2823 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002824 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002825 "{\n\t&_OBJC_METACLASS_";
2826 Result += CDecl->getName();
2827 if (SuperClass) {
2828 Result += ", \"";
2829 Result += SuperClass->getName();
2830 Result += "\", \"";
2831 Result += CDecl->getName();
2832 Result += "\"";
2833 }
2834 else {
2835 Result += ", 0, \"";
2836 Result += CDecl->getName();
2837 Result += "\"";
2838 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002839 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002840 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002841 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002842 Result += ",0";
2843 else {
2844 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002845 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002846 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002847 if (LangOpts.Microsoft)
2848 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002849 Result += ")";
2850 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002851 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002852 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002853 Result += CDecl->getName();
2854 Result += "\n\t";
2855 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002856 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002857 Result += ",0";
2858 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002859 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002860 Result += CDecl->getName();
2861 Result += ", 0\n\t";
2862 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002863 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002864 Result += ",0,0";
2865 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002866 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002867 Result += CDecl->getName();
2868 Result += ", 0,0\n";
2869 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002870 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002871 Result += ",0,0,0\n";
2872 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002873}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002874
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002875/// RewriteImplementations - This routine rewrites all method implementations
2876/// and emits meta-data.
2877
2878void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002879 int ClsDefCount = ClassImplementation.size();
2880 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002881
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002882 if (ClsDefCount == 0 && CatDefCount == 0)
2883 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002884 // Rewrite implemented methods
2885 for (int i = 0; i < ClsDefCount; i++)
2886 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002887
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002888 for (int i = 0; i < CatDefCount; i++)
2889 RewriteImplementationDecl(CategoryImplementation[i]);
2890
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002891 // This is needed for use of offsetof
2892 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002893
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002894 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002895 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002896 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002897
2898 // For each implemented category, write out all its meta data.
2899 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002901
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002902 // Write objc_symtab metadata
2903 /*
2904 struct _objc_symtab
2905 {
2906 long sel_ref_cnt;
2907 SEL *refs;
2908 short cls_def_cnt;
2909 short cat_def_cnt;
2910 void *defs[cls_def_cnt + cat_def_cnt];
2911 };
2912 */
2913
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002914 Result += "\nstruct _objc_symtab {\n";
2915 Result += "\tlong sel_ref_cnt;\n";
2916 Result += "\tSEL *refs;\n";
2917 Result += "\tshort cls_def_cnt;\n";
2918 Result += "\tshort cat_def_cnt;\n";
2919 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2920 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002921
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002922 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002923 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002924 Result += "\t0, 0, " + utostr(ClsDefCount)
2925 + ", " + utostr(CatDefCount) + "\n";
2926 for (int i = 0; i < ClsDefCount; i++) {
2927 Result += "\t,&_OBJC_CLASS_";
2928 Result += ClassImplementation[i]->getName();
2929 Result += "\n";
2930 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002931
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002932 for (int i = 0; i < CatDefCount; i++) {
2933 Result += "\t,&_OBJC_CATEGORY_";
2934 Result += CategoryImplementation[i]->getClassInterface()->getName();
2935 Result += "_";
2936 Result += CategoryImplementation[i]->getName();
2937 Result += "\n";
2938 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002939
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002941
2942 // Write objc_module metadata
2943
2944 /*
2945 struct _objc_module {
2946 long version;
2947 long size;
2948 const char *name;
2949 struct _objc_symtab *symtab;
2950 }
2951 */
2952
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002953 Result += "\nstruct _objc_module {\n";
2954 Result += "\tlong version;\n";
2955 Result += "\tlong size;\n";
2956 Result += "\tconst char *name;\n";
2957 Result += "\tstruct _objc_symtab *symtab;\n";
2958 Result += "};\n\n";
2959 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002960 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002961 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2962 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002963 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002964
2965 if (LangOpts.Microsoft) {
2966 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2967 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2968 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2969 Result += "&_OBJC_MODULES;\n";
2970 Result += "#pragma data_seg(pop)\n\n";
2971 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002972}
Chris Lattner311ff022007-10-16 22:36:42 +00002973