blob: 89de81bb38f183de21303fb64db92702f330f107 [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;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000048 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
49 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
50 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
51 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
52 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000053 llvm::SmallVector<Stmt *, 32> Stmts;
54 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000055 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000056
Steve Naroffd82a9ab2008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
58
Steve Naroffebf2b562007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000068 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000069 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070
Steve Naroffbeaf2992007-11-03 11:27:19 +000071 // ObjC string constant support.
72 FileVarDecl *ConstantStringClassReference;
73 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000074
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000075 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 int BcLabelCount;
77
Steve Naroff874e2322007-11-15 10:28:18 +000078 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000079 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000080 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000081 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000082
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000083 // Needed for header files being rewritten
84 bool IsHeader;
85
Chris Lattnerc68ab772008-03-22 00:08:40 +000086 std::ostream &OutFile;
87
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000088 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000089 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000090 void Initialize(ASTContext &context);
91
Chris Lattner8a12c272007-10-11 18:38:32 +000092
Chris Lattnerf04da132007-10-24 17:06:59 +000093 // Top Level Driver code.
94 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000095 void HandleDeclInMainFile(Decl *D);
Chris Lattnerc68ab772008-03-22 00:08:40 +000096 RewriteTest(bool isHeader, std::ostream &outFile,
97 Diagnostic &D, const LangOptions &LOpts)
98 : Diags(D), LangOpts(LOpts), OutFile(outFile) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000099 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +0000100 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
101 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +0000102 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000104
105 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000106 // If replacement succeeded or warning disabled return with no warning.
107 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000108 return;
109
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000110 SourceRange Range = Old->getSourceRange();
111 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
112 0, 0, &Range, 1);
113 }
114
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000115 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000116 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000117 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
118 SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000123
Chris Lattneraadaf782008-01-31 19:51:04 +0000124 void RemoveText(SourceLocation Loc, unsigned StrLen) {
125 // If removal succeeded or warning disabled return with no warning.
126 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
127 return;
128
129 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
130 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000131
Chris Lattneraadaf782008-01-31 19:51:04 +0000132 void ReplaceText(SourceLocation Start, unsigned OrigLength,
133 const char *NewStr, unsigned NewLength) {
134 // If removal succeeded or warning disabled return with no warning.
135 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
136 SilenceRewriteMacroWarning)
137 return;
138
139 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
140 }
141
Chris Lattnerf04da132007-10-24 17:06:59 +0000142 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000143 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000144 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000145 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000146 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
147 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000148 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
150 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
151 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
152 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
153 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000154 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000155 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000156 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000157 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000159 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000160 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000163 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000164 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000165 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000166 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000167 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000168 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000169 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000170 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000171 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
173 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
174 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000175 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
176 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000177 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
178 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000179 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000180 Stmt *RewriteBreakStmt(BreakStmt *S);
181 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000182 void SynthCountByEnumWithState(std::string &buf);
183
Steve Naroff09b266e2007-10-30 23:14:51 +0000184 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000185 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000186 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000187 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000188 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000189 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000190 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000191 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000192 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000193 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000194
Chris Lattnerf04da132007-10-24 17:06:59 +0000195 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000197 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000198
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
203 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000204 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000205 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000206 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000207 const char *ClassName,
208 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000209
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000211 int NumProtocols,
212 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000213 const char *ClassName,
214 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000215 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000216 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
218 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000219 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000220 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000221 };
222}
223
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000224static bool IsHeaderFile(const std::string &Filename) {
225 std::string::size_type DotPos = Filename.rfind('.');
226
227 if (DotPos == std::string::npos) {
228 // no file extension
229 return false;
230 }
231
232 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
233 // C header: .h
234 // C++ header: .hh or .H;
235 return Ext == "h" || Ext == "hh" || Ext == "H";
236}
237
238ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000239 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000240 Diagnostic &Diags,
241 const LangOptions &LOpts) {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000242 // Create the output file.
243
244 std::ostream *Out;
245 if (OutFile == "-") {
246 Out = llvm::cout.stream();
247 } else if (!OutFile.empty()) {
248 Out = new std::ofstream(OutFile.c_str(),
249 std::ios_base::binary|std::ios_base::out);
250 } else if (InFile == "-") {
251 Out = llvm::cout.stream();
252 } else {
253 llvm::sys::Path Path(InFile);
254 Path.eraseSuffix();
255 Path.appendSuffix("cpp");
256 Out = new std::ofstream(Path.toString().c_str(),
257 std::ios_base::binary|std::ios_base::out);
258 }
259
260 return new RewriteTest(IsHeaderFile(InFile), *Out, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000261}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000262
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000263void RewriteTest::Initialize(ASTContext &context) {
264 Context = &context;
265 SM = &Context->getSourceManager();
266 MsgSendFunctionDecl = 0;
267 MsgSendSuperFunctionDecl = 0;
268 MsgSendStretFunctionDecl = 0;
269 MsgSendSuperStretFunctionDecl = 0;
270 MsgSendFpretFunctionDecl = 0;
271 GetClassFunctionDecl = 0;
272 GetMetaClassFunctionDecl = 0;
273 SelGetUidFunctionDecl = 0;
274 CFStringFunctionDecl = 0;
275 GetProtocolFunctionDecl = 0;
276 ConstantStringClassReference = 0;
277 NSStringRecord = 0;
278 CurMethodDecl = 0;
279 SuperStructDecl = 0;
280 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000281 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000282 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000283
284 // Get the ID and start/end of the main file.
285 MainFileID = SM->getMainFileID();
286 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
287 MainFileStart = MainBuf->getBufferStart();
288 MainFileEnd = MainBuf->getBufferEnd();
289
290
291 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000292
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000293 // declaring objc_selector outside the parameter list removes a silly
294 // scope related warning...
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000295 std::string S = "#pragma once\n";
296 S += "struct objc_selector; struct objc_class;\n";
297 S += "#ifndef OBJC_SUPER\n";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000298 S += "struct objc_super { struct objc_object *object; ";
299 S += "struct objc_object *superClass; ";
300 if (LangOpts.Microsoft) {
301 // Add a constructor for creating temporary objects.
302 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
303 S += "object(o), superClass(s) {} ";
304 }
305 S += "};\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000306 S += "#define OBJC_SUPER\n";
307 S += "#endif\n";
308 S += "#ifndef _REWRITER_typedef_Protocol\n";
309 S += "typedef struct objc_object Protocol;\n";
310 S += "#define _REWRITER_typedef_Protocol\n";
311 S += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000312 if (LangOpts.Microsoft)
313 S += "extern \"C\" {\n";
314 S += "struct objc_object *objc_msgSend";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000315 S += "(struct objc_object *, struct objc_selector *, ...);\n";
316 S += "extern struct objc_object *objc_msgSendSuper";
317 S += "(struct objc_super *, struct objc_selector *, ...);\n";
318 S += "extern struct objc_object *objc_msgSend_stret";
319 S += "(struct objc_object *, struct objc_selector *, ...);\n";
320 S += "extern struct objc_object *objc_msgSendSuper_stret";
321 S += "(struct objc_super *, struct objc_selector *, ...);\n";
322 S += "extern struct objc_object *objc_msgSend_fpret";
323 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000324 S += "struct objc_object *objc_getClass";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000325 S += "(const char *);\n";
326 S += "extern struct objc_object *objc_getMetaClass";
327 S += "(const char *);\n";
328 S += "extern void objc_exception_throw(struct objc_object *);\n";
329 S += "extern void objc_exception_try_enter(void *);\n";
330 S += "extern void objc_exception_try_exit(void *);\n";
331 S += "extern struct objc_object *objc_exception_extract(void *);\n";
332 S += "extern int objc_exception_match";
333 S += "(struct objc_class *, struct objc_object *, ...);\n";
334 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000335 if (LangOpts.Microsoft)
336 S += "} // end extern \"C\"\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000337 S += "#include <objc/objc.h>\n";
338 S += "#ifndef __FASTENUMERATIONSTATE\n";
339 S += "struct __objcFastEnumerationState {\n\t";
340 S += "unsigned long state;\n\t";
341 S += "id *itemsPtr;\n\t";
342 S += "unsigned long *mutationsPtr;\n\t";
343 S += "unsigned long extra[5];\n};\n";
344 S += "#define __FASTENUMERATIONSTATE\n";
345 S += "#endif\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000346 S += "#ifndef __NSCONSTANTSTRINGIMPL\n";
347 S += "struct __NSConstantStringImpl {\n";
Steve Naroff2a228162008-03-18 01:47:18 +0000348 S += " int *isa;\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000349 S += " int flags;\n";
350 S += " char *str;\n";
351 S += " long length;\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000352 S += "};\n";
Steve Naroff2a228162008-03-18 01:47:18 +0000353 S += "extern int __CFConstantStringClassReference[];\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000354 S += "#define __NSCONSTANTSTRINGIMPL\n";
355 S += "#endif\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000356#if 0
357 if (LangOpts.Microsoft)
Steve Naroff4f943c22008-03-10 20:43:59 +0000358 S += "#define __attribute__(X)\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000359#endif
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 if (IsHeader) {
361 // insert the whole string when rewriting a header file
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000362 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000363 }
364 else {
365 // Not rewriting header, exclude the #pragma once pragma
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000366 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000367 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000368 }
369}
370
371
Chris Lattnerf04da132007-10-24 17:06:59 +0000372//===----------------------------------------------------------------------===//
373// Top Level Driver Code
374//===----------------------------------------------------------------------===//
375
Chris Lattner8a12c272007-10-11 18:38:32 +0000376void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000377 // Two cases: either the decl could be in the main file, or it could be in a
378 // #included file. If the former, rewrite it now. If the later, check to see
379 // if we rewrote the #include/#import.
380 SourceLocation Loc = D->getLocation();
381 Loc = SM->getLogicalLoc(Loc);
382
383 // If this is for a builtin, ignore it.
384 if (Loc.isInvalid()) return;
385
Steve Naroffebf2b562007-10-23 23:50:29 +0000386 // Look for built-in declarations that we need to refer during the rewrite.
387 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000388 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000389 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
390 // declared in <Foundation/NSString.h>
391 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
392 ConstantStringClassReference = FVD;
393 return;
394 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000395 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000396 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000397 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000398 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000399 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000400 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000401 } else if (ObjCForwardProtocolDecl *FP =
402 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000403 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000404 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000405 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000406 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
407 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000408}
409
Chris Lattnerf04da132007-10-24 17:06:59 +0000410/// HandleDeclInMainFile - This is called for each top-level decl defined in the
411/// main file of the input.
412void RewriteTest::HandleDeclInMainFile(Decl *D) {
413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
414 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000415 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000416
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000417 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000418 if (Stmt *Body = MD->getBody()) {
419 //Body->dump();
420 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000421 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000422 CurMethodDecl = 0;
423 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000424 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000426 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000427 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000428 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000429 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000430 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000431 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000432 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000433 if (VD->getInit())
434 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
435 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000436 // Nothing yet.
437}
438
439RewriteTest::~RewriteTest() {
440 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000441
442 // Rewrite tabs if we care.
443 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000444
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000445 RewriteInclude();
446
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000447 // Rewrite Objective-c meta data*
448 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000449 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000450
Chris Lattnerf04da132007-10-24 17:06:59 +0000451 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
452 // we are done.
453 if (const RewriteBuffer *RewriteBuf =
454 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000455 //printf("Changed:\n");
Chris Lattnerc68ab772008-03-22 00:08:40 +0000456 OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000457 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000458 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000459 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000460 // Emit metadata.
Chris Lattnerc68ab772008-03-22 00:08:40 +0000461 OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000462}
463
Chris Lattnerf04da132007-10-24 17:06:59 +0000464//===----------------------------------------------------------------------===//
465// Syntactic (non-AST) Rewriting Code
466//===----------------------------------------------------------------------===//
467
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000468void RewriteTest::RewriteInclude() {
469 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
470 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
471 const char *MainBufStart = MainBuf.first;
472 const char *MainBufEnd = MainBuf.second;
473 size_t ImportLen = strlen("import");
474 size_t IncludeLen = strlen("include");
475
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000476 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000477 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
478 if (*BufPtr == '#') {
479 if (++BufPtr == MainBufEnd)
480 return;
481 while (*BufPtr == ' ' || *BufPtr == '\t')
482 if (++BufPtr == MainBufEnd)
483 return;
484 if (!strncmp(BufPtr, "import", ImportLen)) {
485 // replace import with include
486 SourceLocation ImportLoc =
487 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000488 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000489 BufPtr += ImportLen;
490 }
491 }
492 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000493}
494
Chris Lattnerf04da132007-10-24 17:06:59 +0000495void RewriteTest::RewriteTabs() {
496 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
497 const char *MainBufStart = MainBuf.first;
498 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000499
Chris Lattnerf04da132007-10-24 17:06:59 +0000500 // Loop over the whole file, looking for tabs.
501 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
502 if (*BufPtr != '\t')
503 continue;
504
505 // Okay, we found a tab. This tab will turn into at least one character,
506 // but it depends on which 'virtual column' it is in. Compute that now.
507 unsigned VCol = 0;
508 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
509 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
510 ++VCol;
511
512 // Okay, now that we know the virtual column, we know how many spaces to
513 // insert. We assume 8-character tab-stops.
514 unsigned Spaces = 8-(VCol & 7);
515
516 // Get the location of the tab.
517 SourceLocation TabLoc =
518 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
519
520 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000521 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000522 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000523}
524
525
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000527 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000528 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000529
530 // Get the start location and compute the semi location.
531 SourceLocation startLoc = ClassDecl->getLocation();
532 const char *startBuf = SM->getCharacterData(startLoc);
533 const char *semiPtr = strchr(startBuf, ';');
534
535 // Translate to typedef's that forward reference structs with the same name
536 // as the class. As a convenience, we include the original declaration
537 // as a comment.
538 std::string typedefString;
539 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000540 typedefString.append(startBuf, semiPtr-startBuf+1);
541 typedefString += "\n";
542 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000544 typedefString += "#ifndef _REWRITER_typedef_";
545 typedefString += ForwardDecl->getName();
546 typedefString += "\n";
547 typedefString += "#define _REWRITER_typedef_";
548 typedefString += ForwardDecl->getName();
549 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000550 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000551 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000552 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000553 }
554
555 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000556 ReplaceText(startLoc, semiPtr-startBuf+1,
557 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000558}
559
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000560void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000561 SourceLocation LocStart = Method->getLocStart();
562 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000563
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000564 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000565 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000566 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000567 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000568 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000569 }
570}
571
Chris Lattner55d13b42008-03-16 21:23:50 +0000572void RewriteTest::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000573{
Chris Lattner55d13b42008-03-16 21:23:50 +0000574 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000575 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000576 SourceLocation Loc = Property->getLocation();
577
Chris Lattneraadaf782008-01-31 19:51:04 +0000578 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000579
580 // FIXME: handle properties that are declared across multiple lines.
581 }
582}
583
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000584void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000585 SourceLocation LocStart = CatDecl->getLocStart();
586
587 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000589
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000590 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000591 E = CatDecl->instmeth_end(); I != E; ++I)
592 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000593 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000594 E = CatDecl->classmeth_end(); I != E; ++I)
595 RewriteMethodDeclaration(*I);
596
Steve Naroff423cb562007-10-30 13:30:57 +0000597 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000598 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000599}
600
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000601void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000602 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000603
Steve Naroff752d6ef2007-10-30 16:42:30 +0000604 SourceLocation LocStart = PDecl->getLocStart();
605
606 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000607 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000608
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000609 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000610 E = PDecl->instmeth_end(); I != E; ++I)
611 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000613 E = PDecl->classmeth_end(); I != E; ++I)
614 RewriteMethodDeclaration(*I);
615
Steve Naroff752d6ef2007-10-30 16:42:30 +0000616 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000617 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000619
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000620 // Must comment out @optional/@required
621 const char *startBuf = SM->getCharacterData(LocStart);
622 const char *endBuf = SM->getCharacterData(LocEnd);
623 for (const char *p = startBuf; p < endBuf; p++) {
624 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
625 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000626 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000627 ReplaceText(OptionalLoc, strlen("@optional"),
628 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000629
630 }
631 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
632 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000633 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000634 ReplaceText(OptionalLoc, strlen("@required"),
635 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000636
637 }
638 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000639}
640
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000641void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000642 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000643 if (LocStart.isInvalid())
644 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000645 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000646 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000647}
648
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000649void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000650 std::string &ResultStr) {
651 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000652 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000653 ResultStr += "id";
654 else
655 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000656 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000657
658 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000659 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000660
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000661 if (OMD->isInstance())
662 NameStr += "_I_";
663 else
664 NameStr += "_C_";
665
666 NameStr += OMD->getClassInterface()->getName();
667 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000668
669 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 if (ObjCCategoryImplDecl *CID =
671 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000672 NameStr += CID->getName();
673 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000674 }
675 // Append selector names, replacing ':' with '_'
676 const char *selName = OMD->getSelector().getName().c_str();
677 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000678 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 else {
680 std::string selString = OMD->getSelector().getName();
681 int len = selString.size();
682 for (int i = 0; i < len; i++)
683 if (selString[i] == ':')
684 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000685 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000686 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000687 // Remember this name for metadata emission
688 MethodInternalNames[OMD] = NameStr;
689 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690
691 // Rewrite arguments
692 ResultStr += "(";
693
694 // invisible arguments
695 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000696 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000697 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000698 if (!LangOpts.Microsoft) {
699 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
700 ResultStr += "struct ";
701 }
702 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000703 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000704 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000705 }
706 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000708
709 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000710 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000711 ResultStr += " _cmd";
712
713 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000714 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 ParmVarDecl *PDecl = OMD->getParamDecl(i);
716 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000717 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000718 ResultStr += "id";
719 else
720 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ResultStr += " ";
722 ResultStr += PDecl->getName();
723 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000724 if (OMD->isVariadic())
725 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000726 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000727
728}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000729void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000730 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
731 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000732
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000733 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000734 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000735 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000736 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000737
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000739 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
740 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000741 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 ObjCMethodDecl *OMD = *I;
743 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000744 SourceLocation LocStart = OMD->getLocStart();
745 SourceLocation LocEnd = OMD->getBody()->getLocStart();
746
747 const char *startBuf = SM->getCharacterData(LocStart);
748 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000749 ReplaceText(LocStart, endBuf-startBuf,
750 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000751 }
752
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000754 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
755 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000756 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000757 ObjCMethodDecl *OMD = *I;
758 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 SourceLocation LocStart = OMD->getLocStart();
760 SourceLocation LocEnd = OMD->getBody()->getLocStart();
761
762 const char *startBuf = SM->getCharacterData(LocStart);
763 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(LocStart, endBuf-startBuf,
765 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000766 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000767 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000768 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000769 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000770 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000771}
772
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000773void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000774 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000775 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000776 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000777 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000778 ResultStr += ClassDecl->getName();
779 ResultStr += "\n";
780 ResultStr += "#define _REWRITER_typedef_";
781 ResultStr += ClassDecl->getName();
782 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000783 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000784 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000785 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000786 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000787 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000788 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000789 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000790
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000791 RewriteProperties(ClassDecl->getNumPropertyDecl(),
792 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000793 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000794 E = ClassDecl->instmeth_end(); I != E; ++I)
795 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000796 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000797 E = ClassDecl->classmeth_end(); I != E; ++I)
798 RewriteMethodDeclaration(*I);
799
Steve Naroff2feac5e2007-10-30 03:43:13 +0000800 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000801 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000802}
803
Steve Naroff7e3411b2007-11-15 02:58:25 +0000804Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000806 if (CurMethodDecl) {
807 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
808 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
809 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000810 // lookup which class implements the instance variable.
811 ObjCInterfaceDecl *clsDeclared = 0;
812 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
813 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5518e7c2008-03-12 23:15:19 +0000814
815 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000816 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000817 RecName += "_IMPL";
818 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Chris Lattnerc63e6602008-03-15 21:32:50 +0000819 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct,
820 SourceLocation(), II, 0);
Steve Naroff05b8c782008-03-12 00:25:36 +0000821 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
822 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
823 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
824 // Don't forget the parens to enforce the proper binding.
825 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
826 if (IV->isFreeIvar()) {
827 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
828 ReplaceStmt(IV, ME);
829 delete IV;
830 return ME;
831 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000832 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5518e7c2008-03-12 23:15:19 +0000833 // Cannot delete IV->getBase(), since PE points to it.
834 // Replace the old base with the cast. This is important when doing
835 // embedded rewrites. For example, [newInv->_container addObject:0].
836 IV->setBase(PE);
837 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000838 }
839 }
840 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000841 }
Steve Naroff5518e7c2008-03-12 23:15:19 +0000842 // FIXME: Implement public ivar access from a function.
Steve Naroff05b8c782008-03-12 00:25:36 +0000843 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
844 IV->getLocation(), D->getType());
845 ReplaceStmt(IV, Replacement);
846 delete IV;
847 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000848}
849
Chris Lattnerf04da132007-10-24 17:06:59 +0000850//===----------------------------------------------------------------------===//
851// Function Body / Expression rewriting
852//===----------------------------------------------------------------------===//
853
Steve Narofff3473a72007-11-09 15:20:18 +0000854Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000855 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
856 isa<DoStmt>(S) || isa<ForStmt>(S))
857 Stmts.push_back(S);
858 else if (isa<ObjCForCollectionStmt>(S)) {
859 Stmts.push_back(S);
860 ObjCBcLabelNo.push_back(++BcLabelCount);
861 }
862
Chris Lattner338d1e22008-01-31 05:10:40 +0000863 SourceLocation OrigStmtEnd = S->getLocEnd();
864
865 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000866 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
867 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000868 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000869 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000870 if (newStmt)
871 *CI = newStmt;
872 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000873
874 // Handle specific things.
875 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
876 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000877
878 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
879 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000880
881 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
882 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000883
Steve Naroffbeaf2992007-11-03 11:27:19 +0000884 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
885 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000886
Steve Naroff934f2762007-10-24 22:48:43 +0000887 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
888 // Before we rewrite it, put the original message expression in a comment.
889 SourceLocation startLoc = MessExpr->getLocStart();
890 SourceLocation endLoc = MessExpr->getLocEnd();
891
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *endBuf = SM->getCharacterData(endLoc);
894
895 std::string messString;
896 messString += "// ";
897 messString.append(startBuf, endBuf-startBuf+1);
898 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000899
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000900 // FIXME: Missing definition of
901 // InsertText(clang::SourceLocation, char const*, unsigned int).
902 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000903 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000904 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000905 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000906 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000907
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000908 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
909 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000910
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000911 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
912 return RewriteObjCSynchronizedStmt(StmtTry);
913
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000914 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
915 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000916
917 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
918 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000919
920 if (ObjCForCollectionStmt *StmtForCollection =
921 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000922 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000923 if (BreakStmt *StmtBreakStmt =
924 dyn_cast<BreakStmt>(S))
925 return RewriteBreakStmt(StmtBreakStmt);
926 if (ContinueStmt *StmtContinueStmt =
927 dyn_cast<ContinueStmt>(S))
928 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000929
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000930 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
931 isa<DoStmt>(S) || isa<ForStmt>(S)) {
932 assert(!Stmts.empty() && "Statement stack is empty");
933 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
934 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
935 && "Statement stack mismatch");
936 Stmts.pop_back();
937 }
Steve Naroff874e2322007-11-15 10:28:18 +0000938#if 0
939 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
940 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
941 // Get the new text.
942 std::ostringstream Buf;
943 Replacement->printPretty(Buf);
944 const std::string &Str = Buf.str();
945
946 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000947 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000948 delete S;
949 return Replacement;
950 }
951#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000952 // Return this stmt unmodified.
953 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000954}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000955
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000956/// SynthCountByEnumWithState - To print:
957/// ((unsigned int (*)
958/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
959/// (void *)objc_msgSend)((id)l_collection,
960/// sel_registerName(
961/// "countByEnumeratingWithState:objects:count:"),
962/// &enumState,
963/// (id *)items, (unsigned int)16)
964///
965void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
966 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
967 "id *, unsigned int))(void *)objc_msgSend)";
968 buf += "\n\t\t";
969 buf += "((id)l_collection,\n\t\t";
970 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
971 buf += "\n\t\t";
972 buf += "&enumState, "
973 "(id *)items, (unsigned int)16)";
974}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000975
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000976/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
977/// statement to exit to its outer synthesized loop.
978///
979Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
980 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
981 return S;
982 // replace break with goto __break_label
983 std::string buf;
984
985 SourceLocation startLoc = S->getLocStart();
986 buf = "goto __break_label_";
987 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000988 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000989
990 return 0;
991}
992
993/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
994/// statement to continue with its inner synthesized loop.
995///
996Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
997 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
998 return S;
999 // replace continue with goto __continue_label
1000 std::string buf;
1001
1002 SourceLocation startLoc = S->getLocStart();
1003 buf = "goto __continue_label_";
1004 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001005 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001006
1007 return 0;
1008}
1009
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001010/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001011/// It rewrites:
1012/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001013
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001014/// Into:
1015/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001016/// type elem;
1017/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001018/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001019/// id l_collection = (id)collection;
1020/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1021/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001022/// if (limit) {
1023/// unsigned long startMutations = *enumState.mutationsPtr;
1024/// do {
1025/// unsigned long counter = 0;
1026/// do {
1027/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001028/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001029/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001030/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001031/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001032/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001033/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1034/// objects:items count:16]);
1035/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001036/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001037/// }
1038/// else
1039/// elem = nil;
1040/// }
1041///
Chris Lattner338d1e22008-01-31 05:10:40 +00001042Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1043 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001044 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1045 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1046 "ObjCForCollectionStmt Statement stack mismatch");
1047 assert(!ObjCBcLabelNo.empty() &&
1048 "ObjCForCollectionStmt - Label No stack empty");
1049
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001050 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001051 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001053 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054 std::string buf;
1055 buf = "\n{\n\t";
1056 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1057 // type elem;
1058 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001059 elementTypeAsString = ElementType.getAsString();
1060 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001061 buf += " ";
1062 elementName = DS->getDecl()->getName();
1063 buf += elementName;
1064 buf += ";\n\t";
1065 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001066 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001068 elementTypeAsString = DR->getDecl()->getType().getAsString();
1069 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001070 else
1071 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1072
1073 // struct __objcFastEnumerationState enumState = { 0 };
1074 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1075 // id items[16];
1076 buf += "id items[16];\n\t";
1077 // id l_collection = (id)
1078 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001079 // Find start location of 'collection' the hard way!
1080 const char *startCollectionBuf = startBuf;
1081 startCollectionBuf += 3; // skip 'for'
1082 startCollectionBuf = strchr(startCollectionBuf, '(');
1083 startCollectionBuf++; // skip '('
1084 // find 'in' and skip it.
1085 while (*startCollectionBuf != ' ' ||
1086 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1087 (*(startCollectionBuf+3) != ' ' &&
1088 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1089 startCollectionBuf++;
1090 startCollectionBuf += 3;
1091
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001093 ReplaceText(startLoc, startCollectionBuf - startBuf,
1094 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001095 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001096 SourceLocation rightParenLoc = S->getRParenLoc();
1097 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1098 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001099 buf = ";\n\t";
1100
1101 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1102 // objects:items count:16];
1103 // which is synthesized into:
1104 // unsigned int limit =
1105 // ((unsigned int (*)
1106 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1107 // (void *)objc_msgSend)((id)l_collection,
1108 // sel_registerName(
1109 // "countByEnumeratingWithState:objects:count:"),
1110 // (struct __objcFastEnumerationState *)&state,
1111 // (id *)items, (unsigned int)16);
1112 buf += "unsigned long limit =\n\t\t";
1113 SynthCountByEnumWithState(buf);
1114 buf += ";\n\t";
1115 /// if (limit) {
1116 /// unsigned long startMutations = *enumState.mutationsPtr;
1117 /// do {
1118 /// unsigned long counter = 0;
1119 /// do {
1120 /// if (startMutations != *enumState.mutationsPtr)
1121 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001122 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001123 buf += "if (limit) {\n\t";
1124 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1125 buf += "do {\n\t\t";
1126 buf += "unsigned long counter = 0;\n\t\t";
1127 buf += "do {\n\t\t\t";
1128 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1129 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1130 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001131 buf += " = (";
1132 buf += elementTypeAsString;
1133 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001134 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001135 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001137 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001138 /// } while (counter < limit);
1139 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1140 /// objects:items count:16]);
1141 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001142 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001143 /// }
1144 /// else
1145 /// elem = nil;
1146 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001147 ///
1148 buf = ";\n\t";
1149 buf += "__continue_label_";
1150 buf += utostr(ObjCBcLabelNo.back());
1151 buf += ": ;";
1152 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001153 buf += "} while (counter < limit);\n\t";
1154 buf += "} while (limit = ";
1155 SynthCountByEnumWithState(buf);
1156 buf += ");\n\t";
1157 buf += elementName;
1158 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001159 buf += "__break_label_";
1160 buf += utostr(ObjCBcLabelNo.back());
1161 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 buf += "}\n\t";
1163 buf += "else\n\t\t";
1164 buf += elementName;
1165 buf += " = nil;\n";
1166 buf += "}\n";
1167 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001168 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001169 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001170 Stmts.pop_back();
1171 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001172 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001173}
1174
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001175/// RewriteObjCSynchronizedStmt -
1176/// This routine rewrites @synchronized(expr) stmt;
1177/// into:
1178/// objc_sync_enter(expr);
1179/// @try stmt @finally { objc_sync_exit(expr); }
1180///
1181Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1182 // Get the start location and compute the semi location.
1183 SourceLocation startLoc = S->getLocStart();
1184 const char *startBuf = SM->getCharacterData(startLoc);
1185
1186 assert((*startBuf == '@') && "bogus @synchronized location");
1187
1188 std::string buf;
1189 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001190 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001191 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1192 const char *endBuf = SM->getCharacterData(endLoc);
1193 endBuf++;
1194 const char *rparenBuf = strchr(endBuf, ')');
1195 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1196 buf = ");\n";
1197 // declare a new scope with two variables, _stack and _rethrow.
1198 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1199 buf += "int buf[18/*32-bit i386*/];\n";
1200 buf += "char *pointers[4];} _stack;\n";
1201 buf += "id volatile _rethrow = 0;\n";
1202 buf += "objc_exception_try_enter(&_stack);\n";
1203 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001204 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001205 startLoc = S->getSynchBody()->getLocEnd();
1206 startBuf = SM->getCharacterData(startLoc);
1207
1208 assert((*startBuf == '}') && "bogus @try block");
1209 SourceLocation lastCurlyLoc = startLoc;
1210 buf = "}\nelse {\n";
1211 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1212 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1213 // FIXME: This must be objc_sync_exit(syncExpr);
1214 buf += " objc_sync_exit();\n";
1215 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1216 buf += "}\n";
1217 buf += "}";
1218
Chris Lattneraadaf782008-01-31 19:51:04 +00001219 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001220 return 0;
1221}
1222
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001223Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001224 // Get the start location and compute the semi location.
1225 SourceLocation startLoc = S->getLocStart();
1226 const char *startBuf = SM->getCharacterData(startLoc);
1227
1228 assert((*startBuf == '@') && "bogus @try location");
1229
1230 std::string buf;
1231 // declare a new scope with two variables, _stack and _rethrow.
1232 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1233 buf += "int buf[18/*32-bit i386*/];\n";
1234 buf += "char *pointers[4];} _stack;\n";
1235 buf += "id volatile _rethrow = 0;\n";
1236 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001237 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001238
Chris Lattneraadaf782008-01-31 19:51:04 +00001239 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001240
1241 startLoc = S->getTryBody()->getLocEnd();
1242 startBuf = SM->getCharacterData(startLoc);
1243
1244 assert((*startBuf == '}') && "bogus @try block");
1245
1246 SourceLocation lastCurlyLoc = startLoc;
1247
1248 startLoc = startLoc.getFileLocWithOffset(1);
1249 buf = " /* @catch begin */ else {\n";
1250 buf += " id _caught = objc_exception_extract(&_stack);\n";
1251 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001252 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001253 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1254 buf += " else { /* @catch continue */";
1255
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001256 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001257
1258 bool sawIdTypedCatch = false;
1259 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001260 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001261 while (catchList) {
1262 Stmt *catchStmt = catchList->getCatchParamStmt();
1263
1264 if (catchList == S->getCatchStmts())
1265 buf = "if ("; // we are generating code for the first catch clause
1266 else
1267 buf = "else if (";
1268 startLoc = catchList->getLocStart();
1269 startBuf = SM->getCharacterData(startLoc);
1270
1271 assert((*startBuf == '@') && "bogus @catch location");
1272
1273 const char *lParenLoc = strchr(startBuf, '(');
1274
Steve Naroffbe4b3332008-02-01 22:08:12 +00001275 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001276 // Now rewrite the body...
1277 lastCatchBody = catchList->getCatchBody();
1278 SourceLocation rParenLoc = catchList->getRParenLoc();
1279 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1280 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1281 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1282 assert((*rParenBuf == ')') && "bogus @catch paren location");
1283 assert((*bodyBuf == '{') && "bogus @catch body location");
1284
1285 buf += "1) { id _tmp = _caught;";
1286 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1287 buf.c_str(), buf.size());
1288 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001289 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001290 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001291 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001292 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001293 sawIdTypedCatch = true;
1294 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001295 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001296
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001297 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001298 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001299 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001300 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001301 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001302 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001303 }
1304 }
1305 // Now rewrite the body...
1306 lastCatchBody = catchList->getCatchBody();
1307 SourceLocation rParenLoc = catchList->getRParenLoc();
1308 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1309 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1310 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1311 assert((*rParenBuf == ')') && "bogus @catch paren location");
1312 assert((*bodyBuf == '{') && "bogus @catch body location");
1313
1314 buf = " = _caught;";
1315 // Here we replace ") {" with "= _caught;" (which initializes and
1316 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001317 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001318 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001319 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001320 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001321 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001322 catchList = catchList->getNextCatchStmt();
1323 }
1324 // Complete the catch list...
1325 if (lastCatchBody) {
1326 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1327 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1328 assert((*bodyBuf == '}') && "bogus @catch body location");
1329 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1330 buf = " } } /* @catch end */\n";
1331
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001332 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001333
1334 // Set lastCurlyLoc
1335 lastCurlyLoc = lastCatchBody->getLocEnd();
1336 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001337 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001338 startLoc = finalStmt->getLocStart();
1339 startBuf = SM->getCharacterData(startLoc);
1340 assert((*startBuf == '@') && "bogus @finally start");
1341
1342 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001343 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001344
1345 Stmt *body = finalStmt->getFinallyBody();
1346 SourceLocation startLoc = body->getLocStart();
1347 SourceLocation endLoc = body->getLocEnd();
1348 const char *startBuf = SM->getCharacterData(startLoc);
1349 const char *endBuf = SM->getCharacterData(endLoc);
1350 assert((*startBuf == '{') && "bogus @finally body location");
1351 assert((*endBuf == '}') && "bogus @finally body location");
1352
1353 startLoc = startLoc.getFileLocWithOffset(1);
1354 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001355 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001356 endLoc = endLoc.getFileLocWithOffset(-1);
1357 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001358 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001359
1360 // Set lastCurlyLoc
1361 lastCurlyLoc = body->getLocEnd();
1362 }
1363 // Now emit the final closing curly brace...
1364 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1365 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001366 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001367 return 0;
1368}
1369
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001370Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001371 return 0;
1372}
1373
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001374Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001375 return 0;
1376}
1377
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001378// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001379// the throw expression is typically a message expression that's already
1380// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001381Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001382 // Get the start location and compute the semi location.
1383 SourceLocation startLoc = S->getLocStart();
1384 const char *startBuf = SM->getCharacterData(startLoc);
1385
1386 assert((*startBuf == '@') && "bogus @throw location");
1387
1388 std::string buf;
1389 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001390 if (S->getThrowExpr())
1391 buf = "objc_exception_throw(";
1392 else // add an implicit argument
1393 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001394 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001395 const char *semiBuf = strchr(startBuf, ';');
1396 assert((*semiBuf == ';') && "@throw: can't find ';'");
1397 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1398 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001399 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001400 return 0;
1401}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001402
Chris Lattnere64b7772007-10-24 16:57:36 +00001403Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001404 // Create a new string expression.
1405 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001406 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001407 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1408 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001409 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1410 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001411 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001412 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001413
Chris Lattner07506182007-11-30 22:53:43 +00001414 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001415 delete Exp;
1416 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001417}
1418
Steve Naroffb42f8412007-11-05 14:50:49 +00001419Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1420 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1421 // Create a call to sel_registerName("selName").
1422 llvm::SmallVector<Expr*, 8> SelExprs;
1423 QualType argType = Context->getPointerType(Context->CharTy);
1424 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1425 Exp->getSelector().getName().size(),
1426 false, argType, SourceLocation(),
1427 SourceLocation()));
1428 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1429 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001430 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001431 delete Exp;
1432 return SelExp;
1433}
1434
Steve Naroff934f2762007-10-24 22:48:43 +00001435CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1436 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001437 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001438 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001439
1440 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001441 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001442
1443 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001444 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001445 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1446
1447 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001448
Steve Naroff934f2762007-10-24 22:48:43 +00001449 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1450}
1451
Steve Naroffd5255f52007-11-01 13:24:47 +00001452static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1453 const char *&startRef, const char *&endRef) {
1454 while (startBuf < endBuf) {
1455 if (*startBuf == '<')
1456 startRef = startBuf; // mark the start.
1457 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001458 if (startRef && *startRef == '<') {
1459 endRef = startBuf; // mark the end.
1460 return true;
1461 }
1462 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001463 }
1464 startBuf++;
1465 }
1466 return false;
1467}
1468
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001469static void scanToNextArgument(const char *&argRef) {
1470 int angle = 0;
1471 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1472 if (*argRef == '<')
1473 angle++;
1474 else if (*argRef == '>')
1475 angle--;
1476 argRef++;
1477 }
1478 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1479}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001480
Steve Naroffd5255f52007-11-01 13:24:47 +00001481bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001482
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001483 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001484 return true;
1485
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001486 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001487 return true;
1488
Steve Naroffd5255f52007-11-01 13:24:47 +00001489 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001490 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001491 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001492 return true; // we have "Class <Protocol> *".
1493 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001494 return false;
1495}
1496
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001497void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001498 SourceLocation Loc;
1499 QualType Type;
1500 const FunctionTypeProto *proto = 0;
1501 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1502 Loc = VD->getLocation();
1503 Type = VD->getType();
1504 }
1505 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1506 Loc = FD->getLocation();
1507 // Check for ObjC 'id' and class types that have been adorned with protocol
1508 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1509 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1510 assert(funcType && "missing function type");
1511 proto = dyn_cast<FunctionTypeProto>(funcType);
1512 if (!proto)
1513 return;
1514 Type = proto->getResultType();
1515 }
1516 else
1517 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001518
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001519 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001520 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001521
1522 const char *endBuf = SM->getCharacterData(Loc);
1523 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001524 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001525 startBuf--; // scan backward (from the decl location) for return type.
1526 const char *startRef = 0, *endRef = 0;
1527 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1528 // Get the locations of the startRef, endRef.
1529 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1530 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1531 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001532 InsertText(LessLoc, "/*", 2);
1533 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001534 }
1535 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001536 if (!proto)
1537 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001538 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001539 const char *startBuf = SM->getCharacterData(Loc);
1540 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001541 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1542 if (needToScanForQualifiers(proto->getArgType(i))) {
1543 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001544
Steve Naroffd5255f52007-11-01 13:24:47 +00001545 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001546 // scan forward (from the decl location) for argument types.
1547 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001548 const char *startRef = 0, *endRef = 0;
1549 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1550 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001551 SourceLocation LessLoc =
1552 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1553 SourceLocation GreaterLoc =
1554 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001555 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001556 InsertText(LessLoc, "/*", 2);
1557 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001558 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001559 startBuf = ++endBuf;
1560 }
1561 else {
1562 while (*startBuf != ')' && *startBuf != ',')
1563 startBuf++; // scan forward (from the decl location) for argument types.
1564 startBuf++;
1565 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001566 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001567}
1568
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001569// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1570void RewriteTest::SynthSelGetUidFunctionDecl() {
1571 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1572 llvm::SmallVector<QualType, 16> ArgTys;
1573 ArgTys.push_back(Context->getPointerType(
1574 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001575 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001576 &ArgTys[0], ArgTys.size(),
1577 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001578 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001579 SelGetUidIdent, getFuncType,
1580 FunctionDecl::Extern, false, 0);
1581}
1582
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001583// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1584void RewriteTest::SynthGetProtocolFunctionDecl() {
1585 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1586 llvm::SmallVector<QualType, 16> ArgTys;
1587 ArgTys.push_back(Context->getPointerType(
1588 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001589 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001590 &ArgTys[0], ArgTys.size(),
1591 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001592 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001593 SelGetProtoIdent, getFuncType,
1594 FunctionDecl::Extern, false, 0);
1595}
1596
Steve Naroff09b266e2007-10-30 23:14:51 +00001597void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1598 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001599 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001600 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001601 return;
1602 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001603 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001604}
1605
Steve Naroffc0a123c2008-03-11 17:37:02 +00001606// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1607void RewriteTest::SynthSuperContructorFunctionDecl() {
1608 if (SuperContructorFunctionDecl)
1609 return;
1610 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1611 llvm::SmallVector<QualType, 16> ArgTys;
1612 QualType argT = Context->getObjCIdType();
1613 assert(!argT.isNull() && "Can't find 'id' type");
1614 ArgTys.push_back(argT);
1615 ArgTys.push_back(argT);
1616 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1617 &ArgTys[0], ArgTys.size(),
1618 false);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001619 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001620 msgSendIdent, msgSendType,
1621 FunctionDecl::Extern, false, 0);
1622}
1623
Steve Naroff09b266e2007-10-30 23:14:51 +00001624// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1625void RewriteTest::SynthMsgSendFunctionDecl() {
1626 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1627 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001628 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001629 assert(!argT.isNull() && "Can't find 'id' type");
1630 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001631 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001632 assert(!argT.isNull() && "Can't find 'SEL' type");
1633 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001634 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001635 &ArgTys[0], ArgTys.size(),
1636 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001637 MsgSendFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001638 msgSendIdent, msgSendType,
1639 FunctionDecl::Extern, false, 0);
1640}
1641
Steve Naroff874e2322007-11-15 10:28:18 +00001642// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1643void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1644 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1645 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001646 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1647 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001648 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1649 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1650 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001651 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001652 assert(!argT.isNull() && "Can't find 'SEL' type");
1653 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001654 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001655 &ArgTys[0], ArgTys.size(),
1656 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001657 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001658 msgSendIdent, msgSendType,
1659 FunctionDecl::Extern, false, 0);
1660}
1661
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001662// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1663void RewriteTest::SynthMsgSendStretFunctionDecl() {
1664 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1665 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001666 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001667 assert(!argT.isNull() && "Can't find 'id' type");
1668 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001669 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001670 assert(!argT.isNull() && "Can't find 'SEL' type");
1671 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001672 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001673 &ArgTys[0], ArgTys.size(),
1674 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001675 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001676 msgSendIdent, msgSendType,
1677 FunctionDecl::Extern, false, 0);
1678}
1679
1680// SynthMsgSendSuperStretFunctionDecl -
1681// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1682void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1683 IdentifierInfo *msgSendIdent =
1684 &Context->Idents.get("objc_msgSendSuper_stret");
1685 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattnerc63e6602008-03-15 21:32:50 +00001686 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, SourceLocation(),
1687 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001688 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1689 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1690 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001691 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001692 assert(!argT.isNull() && "Can't find 'SEL' type");
1693 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001694 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001695 &ArgTys[0], ArgTys.size(),
1696 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001697 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context,
1698 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001699 msgSendIdent, msgSendType,
1700 FunctionDecl::Extern, false, 0);
1701}
1702
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001703// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1704void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1705 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1706 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001708 assert(!argT.isNull() && "Can't find 'id' type");
1709 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001710 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001711 assert(!argT.isNull() && "Can't find 'SEL' type");
1712 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001713 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001714 &ArgTys[0], ArgTys.size(),
1715 true /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001716 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001717 msgSendIdent, msgSendType,
1718 FunctionDecl::Extern, false, 0);
1719}
1720
Steve Naroff09b266e2007-10-30 23:14:51 +00001721// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1722void RewriteTest::SynthGetClassFunctionDecl() {
1723 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1724 llvm::SmallVector<QualType, 16> ArgTys;
1725 ArgTys.push_back(Context->getPointerType(
1726 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001727 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001728 &ArgTys[0], ArgTys.size(),
1729 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001730 GetClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001731 getClassIdent, getClassType,
1732 FunctionDecl::Extern, false, 0);
1733}
1734
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001735// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1736void RewriteTest::SynthGetMetaClassFunctionDecl() {
1737 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1738 llvm::SmallVector<QualType, 16> ArgTys;
1739 ArgTys.push_back(Context->getPointerType(
1740 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001742 &ArgTys[0], ArgTys.size(),
1743 false /*isVariadic*/);
Chris Lattnera98e58d2008-03-15 21:24:04 +00001744 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001745 getClassIdent, getClassType,
1746 FunctionDecl::Extern, false, 0);
1747}
1748
Steve Naroffbeaf2992007-11-03 11:27:19 +00001749Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001750 QualType strType = getConstantStringStructType();
1751
1752 std::string S = "__NSConstantStringImpl_";
1753 S += utostr(NumObjCStringLiterals++);
1754
1755 std::string StrObjDecl = "static __NSConstantStringImpl " + S;
Steve Naroff2a228162008-03-18 01:47:18 +00001756 StrObjDecl += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1757 StrObjDecl += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001758 // The pretty printer for StringLiteral handles escape characters properly.
1759 std::ostringstream prettyBuf;
1760 Exp->getString()->printPretty(prettyBuf);
1761 StrObjDecl += prettyBuf.str();
1762 StrObjDecl += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001763 // The minus 2 removes the begin/end double quotes.
Steve Naroff2a228162008-03-18 01:47:18 +00001764 StrObjDecl += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001765 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
1766 StrObjDecl.c_str(), StrObjDecl.size());
1767
Chris Lattnerc63e6602008-03-15 21:32:50 +00001768 FileVarDecl *NewVD = FileVarDecl::Create(*Context, SourceLocation(),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001769 &Context->Idents.get(S.c_str()), strType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001770 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001771 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1772 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1773 Context->getPointerType(DRE->getType()),
1774 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001775 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001776 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001777 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001778 delete Exp;
1779 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001780}
1781
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001782ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001783 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001784 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1785
1786 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1787 if (!CE) return 0;
1788
1789 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1790 if (!DRE) return 0;
1791
1792 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1793 if (!PVD) return 0;
1794
1795 if (strcmp(PVD->getName(), "self") != 0)
1796 return 0;
1797
1798 // is this id<P1..> type?
1799 if (CE->getType()->isObjCQualifiedIdType())
1800 return 0;
1801 const PointerType *PT = CE->getType()->getAsPointerType();
1802 if (!PT) return 0;
1803
1804 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1805 if (!IT) return 0;
1806
1807 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1808 return 0;
1809
1810 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001811}
1812
1813// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1814QualType RewriteTest::getSuperStructType() {
1815 if (!SuperStructDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001816 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct,
1817 SourceLocation(),
1818 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001819 QualType FieldTypes[2];
1820
1821 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001823 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001824 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001825 // Create fields
1826 FieldDecl *FieldDecls[2];
1827
1828 for (unsigned i = 0; i < 2; ++i)
Chris Lattner8e25d862008-03-16 00:16:02 +00001829 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1830 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001831
1832 SuperStructDecl->defineBody(FieldDecls, 4);
1833 }
1834 return Context->getTagDeclType(SuperStructDecl);
1835}
1836
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001837QualType RewriteTest::getConstantStringStructType() {
1838 if (!ConstantStringDecl) {
Chris Lattnerc63e6602008-03-15 21:32:50 +00001839 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct,
1840 SourceLocation(),
1841 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001842 QualType FieldTypes[4];
1843
1844 // struct objc_object *receiver;
1845 FieldTypes[0] = Context->getObjCIdType();
1846 // int flags;
1847 FieldTypes[1] = Context->IntTy;
1848 // char *str;
1849 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1850 // long length;
1851 FieldTypes[3] = Context->LongTy;
1852 // Create fields
1853 FieldDecl *FieldDecls[2];
1854
1855 for (unsigned i = 0; i < 4; ++i)
Chris Lattner8e25d862008-03-16 00:16:02 +00001856 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
1857 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001858
1859 ConstantStringDecl->defineBody(FieldDecls, 4);
1860 }
1861 return Context->getTagDeclType(ConstantStringDecl);
1862}
1863
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001864Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001865 if (!SelGetUidFunctionDecl)
1866 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001867 if (!MsgSendFunctionDecl)
1868 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001869 if (!MsgSendSuperFunctionDecl)
1870 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001871 if (!MsgSendStretFunctionDecl)
1872 SynthMsgSendStretFunctionDecl();
1873 if (!MsgSendSuperStretFunctionDecl)
1874 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001875 if (!MsgSendFpretFunctionDecl)
1876 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001877 if (!GetClassFunctionDecl)
1878 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001879 if (!GetMetaClassFunctionDecl)
1880 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001881
Steve Naroff874e2322007-11-15 10:28:18 +00001882 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001883 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1884 // May need to use objc_msgSend_stret() as well.
1885 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001886 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001887 QualType resultType = mDecl->getResultType();
1888 if (resultType.getCanonicalType()->isStructureType()
1889 || resultType.getCanonicalType()->isUnionType())
1890 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001891 else if (resultType.getCanonicalType()->isRealFloatingType())
1892 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001893 }
Steve Naroff874e2322007-11-15 10:28:18 +00001894
Steve Naroff934f2762007-10-24 22:48:43 +00001895 // Synthesize a call to objc_msgSend().
1896 llvm::SmallVector<Expr*, 8> MsgExprs;
1897 IdentifierInfo *clsName = Exp->getClassName();
1898
1899 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1900 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001901 if (!strcmp(clsName->getName(), "super")) {
1902 MsgSendFlavor = MsgSendSuperFunctionDecl;
1903 if (MsgSendStretFlavor)
1904 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1905 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1906
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001907 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001908 CurMethodDecl->getClassInterface()->getSuperClass();
1909
1910 llvm::SmallVector<Expr*, 4> InitExprs;
1911
1912 // set the receiver to self, the first argument to all methods.
1913 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001915 SourceLocation()));
1916 llvm::SmallVector<Expr*, 8> ClsExprs;
1917 QualType argType = Context->getPointerType(Context->CharTy);
1918 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1919 SuperDecl->getIdentifier()->getLength(),
1920 false, argType, SourceLocation(),
1921 SourceLocation()));
1922 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1923 &ClsExprs[0],
1924 ClsExprs.size());
1925 // To turn off a warning, type-cast to 'id'
1926 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001927 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001928 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1929 // struct objc_super
1930 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001931 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001932
Steve Naroff23f41272008-03-11 18:14:26 +00001933 if (LangOpts.Microsoft) {
1934 SynthSuperContructorFunctionDecl();
1935 // Simulate a contructor call...
1936 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1937 superType, SourceLocation());
1938 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1939 superType, SourceLocation());
1940 } else {
1941 // (struct objc_super) { <exprs from above> }
1942 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1943 &InitExprs[0], InitExprs.size(),
1944 SourceLocation());
1945 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1946 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001947 // struct objc_super *
1948 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1949 Context->getPointerType(SuperRep->getType()),
1950 SourceLocation());
1951 MsgExprs.push_back(Unop);
1952 } else {
1953 llvm::SmallVector<Expr*, 8> ClsExprs;
1954 QualType argType = Context->getPointerType(Context->CharTy);
1955 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1956 clsName->getLength(),
1957 false, argType, SourceLocation(),
1958 SourceLocation()));
1959 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1960 &ClsExprs[0],
1961 ClsExprs.size());
1962 MsgExprs.push_back(Cls);
1963 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001964 } else { // instance message.
1965 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001966
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001967 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001968 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001969 if (MsgSendStretFlavor)
1970 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001971 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1972
1973 llvm::SmallVector<Expr*, 4> InitExprs;
1974
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001975 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001977 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001978
1979 llvm::SmallVector<Expr*, 8> ClsExprs;
1980 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001981 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1982 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001983 false, argType, SourceLocation(),
1984 SourceLocation()));
1985 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001986 &ClsExprs[0],
1987 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001988 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001989 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001990 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001991 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001992 // struct objc_super
1993 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001994 Expr *SuperRep;
1995
1996 if (LangOpts.Microsoft) {
1997 SynthSuperContructorFunctionDecl();
1998 // Simulate a contructor call...
1999 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2000 superType, SourceLocation());
2001 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2002 superType, SourceLocation());
2003 } else {
2004 // (struct objc_super) { <exprs from above> }
2005 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2006 &InitExprs[0], InitExprs.size(),
2007 SourceLocation());
2008 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2009 }
Steve Naroff874e2322007-11-15 10:28:18 +00002010 // struct objc_super *
2011 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2012 Context->getPointerType(SuperRep->getType()),
2013 SourceLocation());
2014 MsgExprs.push_back(Unop);
2015 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002016 // Remove all type-casts because it may contain objc-style types; e.g.
2017 // Foo<Proto> *.
2018 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2019 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002021 MsgExprs.push_back(recExpr);
2022 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002023 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002024 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002025 llvm::SmallVector<Expr*, 8> SelExprs;
2026 QualType argType = Context->getPointerType(Context->CharTy);
2027 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2028 Exp->getSelector().getName().size(),
2029 false, argType, SourceLocation(),
2030 SourceLocation()));
2031 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2032 &SelExprs[0], SelExprs.size());
2033 MsgExprs.push_back(SelExp);
2034
2035 // Now push any user supplied arguments.
2036 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002037 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002038 // Make all implicit casts explicit...ICE comes in handy:-)
2039 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2040 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2042 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002043 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002044 }
2045 // Make id<P...> cast into an 'id' cast.
2046 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002047 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002048 while ((CE = dyn_cast<CastExpr>(userExpr)))
2049 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002050 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002051 userExpr, SourceLocation());
2052 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002053 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002054 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002055 // We've transferred the ownership to MsgExprs. Null out the argument in
2056 // the original expression, since we will delete it below.
2057 Exp->setArg(i, 0);
2058 }
Steve Naroffab972d32007-11-04 22:37:50 +00002059 // Generate the funky cast.
2060 CastExpr *cast;
2061 llvm::SmallVector<QualType, 8> ArgTypes;
2062 QualType returnType;
2063
2064 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002065 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2066 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2067 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002068 ArgTypes.push_back(Context->getObjCIdType());
2069 ArgTypes.push_back(Context->getObjCSelType());
2070 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002071 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002072 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2074 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002075 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002076 ArgTypes.push_back(t);
2077 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2079 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002080 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002082 }
2083 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002084 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002085
2086 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002087 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2088 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002089
2090 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2091 // If we don't do this cast, we get the following bizarre warning/note:
2092 // xx.m:13: warning: function called through a non-compatible type
2093 // xx.m:13: note: if this code is reached, the program will abort
2094 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2095 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002096
Steve Naroffab972d32007-11-04 22:37:50 +00002097 // Now do the "normal" pointer to function cast.
2098 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002099 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002100 // If we don't have a method decl, force a variadic cast.
2101 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002102 castType = Context->getPointerType(castType);
2103 cast = new CastExpr(castType, cast, SourceLocation());
2104
2105 // Don't forget the parens to enforce the proper binding.
2106 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2107
2108 const FunctionType *FT = msgSendType->getAsFunctionType();
2109 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2110 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002111 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002112 if (MsgSendStretFlavor) {
2113 // We have the method which returns a struct/union. Must also generate
2114 // call to objc_msgSend_stret and hang both varieties on a conditional
2115 // expression which dictate which one to envoke depending on size of
2116 // method's return type.
2117
2118 // Create a reference to the objc_msgSend_stret() declaration.
2119 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2120 SourceLocation());
2121 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2122 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2123 SourceLocation());
2124 // Now do the "normal" pointer to function cast.
2125 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002126 &ArgTypes[0], ArgTypes.size(),
2127 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002128 castType = Context->getPointerType(castType);
2129 cast = new CastExpr(castType, cast, SourceLocation());
2130
2131 // Don't forget the parens to enforce the proper binding.
2132 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2133
2134 FT = msgSendType->getAsFunctionType();
2135 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2136 FT->getResultType(), SourceLocation());
2137
2138 // Build sizeof(returnType)
2139 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2140 returnType, Context->getSizeType(),
2141 SourceLocation(), SourceLocation());
2142 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2143 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2144 // For X86 it is more complicated and some kind of target specific routine
2145 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002146 unsigned IntSize =
2147 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002148 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2149 Context->IntTy,
2150 SourceLocation());
2151 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2152 BinaryOperator::LE,
2153 Context->IntTy,
2154 SourceLocation());
2155 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2156 ConditionalOperator *CondExpr =
2157 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002158 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002159 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002160 return ReplacingStmt;
2161}
2162
2163Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2164 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002165 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002166 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002167
Chris Lattnere64b7772007-10-24 16:57:36 +00002168 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002169 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002170}
2171
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002172/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2173/// call to objc_getProtocol("proto-name").
2174Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2175 if (!GetProtocolFunctionDecl)
2176 SynthGetProtocolFunctionDecl();
2177 // Create a call to objc_getProtocol("ProtocolName").
2178 llvm::SmallVector<Expr*, 8> ProtoExprs;
2179 QualType argType = Context->getPointerType(Context->CharTy);
2180 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2181 strlen(Exp->getProtocol()->getName()),
2182 false, argType, SourceLocation(),
2183 SourceLocation()));
2184 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2185 &ProtoExprs[0],
2186 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002187 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002188 delete Exp;
2189 return ProtoExp;
2190
2191}
2192
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002194/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002196 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2198 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002199 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002200 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002201 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002202 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002203 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002204 SourceLocation LocStart = CDecl->getLocStart();
2205 SourceLocation LocEnd = CDecl->getLocEnd();
2206
2207 const char *startBuf = SM->getCharacterData(LocStart);
2208 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002209 // If no ivars and no root or if its root, directly or indirectly,
2210 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002211 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2212 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002213 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002214 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002215 return;
2216 }
2217
2218 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002220 Result += "\nstruct ";
2221 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002222 if (LangOpts.Microsoft)
2223 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002224
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002225 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002226 const char *cursor = strchr(startBuf, '{');
2227 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002228 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002229
2230 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002231 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002232 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002233 Result = "\n struct ";
2234 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002235 Result += "_IMPL ";
2236 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002237 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002238
2239 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002240 SourceLocation OnePastCurly =
2241 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2242 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002243 }
2244 cursor++; // past '{'
2245
2246 // Now comment out any visibility specifiers.
2247 while (cursor < endBuf) {
2248 if (*cursor == '@') {
2249 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002250 // Skip whitespace.
2251 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2252 /*scan*/;
2253
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002254 // FIXME: presence of @public, etc. inside comment results in
2255 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002256 if (!strncmp(cursor, "public", strlen("public")) ||
2257 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002258 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002259 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002260 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002261 // FIXME: If there are cases where '<' is used in ivar declaration part
2262 // of user code, then scan the ivar list and use needToScanForQualifiers
2263 // for type checking.
2264 else if (*cursor == '<') {
2265 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002266 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002267 cursor = strchr(cursor, '>');
2268 cursor++;
2269 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002270 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002271 }
Steve Narofffea763e82007-11-14 19:25:57 +00002272 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002273 }
Steve Narofffea763e82007-11-14 19:25:57 +00002274 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002275 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002276 } else { // we don't have any instance variables - insert super struct.
2277 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2278 Result += " {\n struct ";
2279 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002280 Result += "_IMPL ";
2281 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002282 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002283 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002284 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002285 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002286 if (!ObjCSynthesizedStructs.insert(CDecl))
2287 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002288}
2289
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002290// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002291/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002292void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002293 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002294 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002295 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002296 const char *ClassName,
2297 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002298 if (MethodBegin == MethodEnd) return;
2299
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002300 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002301 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002302 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002303 SEL _cmd;
2304 char *method_types;
2305 void *_imp;
2306 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002307 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002308 Result += "\nstruct _objc_method {\n";
2309 Result += "\tSEL _cmd;\n";
2310 Result += "\tchar *method_types;\n";
2311 Result += "\tvoid *_imp;\n";
2312 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002313
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002314 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002315 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002316
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002317 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002318
2319 /* struct {
2320 struct _objc_method_list *next_method;
2321 int method_count;
2322 struct _objc_method method_list[];
2323 }
2324 */
2325 Result += "\nstatic struct {\n";
2326 Result += "\tstruct _objc_method_list *next_method;\n";
2327 Result += "\tint method_count;\n";
2328 Result += "\tstruct _objc_method method_list[";
2329 Result += utostr(MethodEnd-MethodBegin);
2330 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002331 Result += prefix;
2332 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2333 Result += "_METHODS_";
2334 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002335 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002336 Result += IsInstanceMethod ? "inst" : "cls";
2337 Result += "_meth\")))= ";
2338 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002339
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002340 Result += "\t,{{(SEL)\"";
2341 Result += (*MethodBegin)->getSelector().getName().c_str();
2342 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002343 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002344 Result += "\", \"";
2345 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002346 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002347 Result += MethodInternalNames[*MethodBegin];
2348 Result += "}\n";
2349 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2350 Result += "\t ,{(SEL)\"";
2351 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002352 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002353 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002354 Result += "\", \"";
2355 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002356 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002357 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002358 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002359 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002360 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002361}
2362
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2364void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002365 int NumProtocols,
2366 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002367 const char *ClassName,
2368 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002369 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002370 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002371 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002372 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002373 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002374 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002375 /* struct protocol_methods {
2376 SEL _cmd;
2377 char *method_types;
2378 }
2379 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002380 Result += "\nstruct protocol_methods {\n";
2381 Result += "\tSEL _cmd;\n";
2382 Result += "\tchar *method_types;\n";
2383 Result += "};\n";
2384
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002385 objc_protocol_methods = true;
2386 }
Chris Lattnerc8581052008-03-16 20:19:15 +00002387 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2388 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002389 /* struct _objc_protocol_method_list {
2390 int protocol_method_count;
2391 struct protocol_methods protocols[];
2392 }
2393 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002394 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002396 Result += "\tstruct protocol_methods protocols[";
2397 Result += utostr(NumMethods);
2398 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002399 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002400 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002401 "{\n\t" + utostr(NumMethods) + "\n";
2402
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002403 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002405 E = PDecl->instmeth_end(); I != E; ++I) {
2406 if (I == PDecl->instmeth_begin())
2407 Result += "\t ,{{(SEL)\"";
2408 else
2409 Result += "\t ,{(SEL)\"";
2410 Result += (*I)->getSelector().getName().c_str();
2411 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002413 Result += "\", \"";
2414 Result += MethodTypeString;
2415 Result += "\"}\n";
2416 }
2417 Result += "\t }\n};\n";
2418 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002419
2420 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002421 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002422 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002423 /* struct _objc_protocol_method_list {
2424 int protocol_method_count;
2425 struct protocol_methods protocols[];
2426 }
2427 */
2428 Result += "\nstatic struct {\n";
2429 Result += "\tint protocol_method_count;\n";
2430 Result += "\tstruct protocol_methods protocols[";
2431 Result += utostr(NumMethods);
2432 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002433 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002434 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002435 "{\n\t";
2436 Result += utostr(NumMethods);
2437 Result += "\n";
2438
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002439 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002440 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002441 E = PDecl->classmeth_end(); I != E; ++I) {
2442 if (I == PDecl->classmeth_begin())
2443 Result += "\t ,{{(SEL)\"";
2444 else
2445 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002446 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002447 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002448 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002449 Result += "\", \"";
2450 Result += MethodTypeString;
2451 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002452 }
2453 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002454 }
2455 // Output:
2456 /* struct _objc_protocol {
2457 // Objective-C 1.0 extensions
2458 struct _objc_protocol_extension *isa;
2459 char *protocol_name;
2460 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002461 struct _objc_protocol_method_list *instance_methods;
2462 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002463 };
2464 */
2465 static bool objc_protocol = false;
2466 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002467 Result += "\nstruct _objc_protocol {\n";
2468 Result += "\tstruct _objc_protocol_extension *isa;\n";
2469 Result += "\tchar *protocol_name;\n";
2470 Result += "\tstruct _objc_protocol **protocol_list;\n";
2471 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2472 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2473 Result += "};\n";
2474
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002475 objc_protocol = true;
2476 }
2477
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002478 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2479 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002480 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002481 "{\n\t0, \"";
2482 Result += PDecl->getName();
2483 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002484 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002485 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002486 Result += PDecl->getName();
2487 Result += ", ";
2488 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002489 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002490 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002491 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002492 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 Result += PDecl->getName();
2494 Result += "\n";
2495 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002496 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002497 Result += "0\n";
2498 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002499 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002500 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002501 /* struct _objc_protocol_list {
2502 struct _objc_protocol_list *next;
2503 int protocol_count;
2504 struct _objc_protocol *class_protocols[];
2505 }
2506 */
2507 Result += "\nstatic struct {\n";
2508 Result += "\tstruct _objc_protocol_list *next;\n";
2509 Result += "\tint protocol_count;\n";
2510 Result += "\tstruct _objc_protocol *class_protocols[";
2511 Result += utostr(NumProtocols);
2512 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513 Result += prefix;
2514 Result += "_PROTOCOLS_";
2515 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002516 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002517 "{\n\t0, ";
2518 Result += utostr(NumProtocols);
2519 Result += "\n";
2520
2521 Result += "\t,{&_OBJC_PROTOCOL_";
2522 Result += Protocols[0]->getName();
2523 Result += " \n";
2524
2525 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002527 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002528 Result += PDecl->getName();
2529 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002530 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002531 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002532 }
2533}
2534
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002536/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002537void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002538 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002539 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002541 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002542 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2543 CDecl = CDecl->getNextClassCategory())
2544 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2545 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002546
Chris Lattnereb44eee2007-12-23 01:40:15 +00002547 std::string FullCategoryName = ClassDecl->getName();
2548 FullCategoryName += '_';
2549 FullCategoryName += IDecl->getName();
2550
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002551 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002552 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002553 true, "CATEGORY_", FullCategoryName.c_str(),
2554 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555
2556 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002558 false, "CATEGORY_", FullCategoryName.c_str(),
2559 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002560
2561 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002562 // Null CDecl is case of a category implementation with no category interface
2563 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002564 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002565 CDecl->getNumReferencedProtocols(),
2566 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002567 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002568
2569 /* struct _objc_category {
2570 char *category_name;
2571 char *class_name;
2572 struct _objc_method_list *instance_methods;
2573 struct _objc_method_list *class_methods;
2574 struct _objc_protocol_list *protocols;
2575 // Objective-C 1.0 extensions
2576 uint32_t size; // sizeof (struct _objc_category)
2577 struct _objc_property_list *instance_properties; // category's own
2578 // @property decl.
2579 };
2580 */
2581
2582 static bool objc_category = false;
2583 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002584 Result += "\nstruct _objc_category {\n";
2585 Result += "\tchar *category_name;\n";
2586 Result += "\tchar *class_name;\n";
2587 Result += "\tstruct _objc_method_list *instance_methods;\n";
2588 Result += "\tstruct _objc_method_list *class_methods;\n";
2589 Result += "\tstruct _objc_protocol_list *protocols;\n";
2590 Result += "\tunsigned int size;\n";
2591 Result += "\tstruct _objc_property_list *instance_properties;\n";
2592 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002593 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002594 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002595 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2596 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002597 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002598 Result += IDecl->getName();
2599 Result += "\"\n\t, \"";
2600 Result += ClassDecl->getName();
2601 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002602
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002603 if (IDecl->getNumInstanceMethods() > 0) {
2604 Result += "\t, (struct _objc_method_list *)"
2605 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2606 Result += FullCategoryName;
2607 Result += "\n";
2608 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002609 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002610 Result += "\t, 0\n";
2611 if (IDecl->getNumClassMethods() > 0) {
2612 Result += "\t, (struct _objc_method_list *)"
2613 "&_OBJC_CATEGORY_CLASS_METHODS_";
2614 Result += FullCategoryName;
2615 Result += "\n";
2616 }
2617 else
2618 Result += "\t, 0\n";
2619
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002620 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002621 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2622 Result += FullCategoryName;
2623 Result += "\n";
2624 }
2625 else
2626 Result += "\t, 0\n";
2627 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002628}
2629
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002630/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2631/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002632void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2633 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002634 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002635 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002636 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002637 if (LangOpts.Microsoft)
2638 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002639 Result += ", ";
2640 Result += ivar->getName();
2641 Result += ")";
2642}
2643
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002644//===----------------------------------------------------------------------===//
2645// Meta Data Emission
2646//===----------------------------------------------------------------------===//
2647
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002648void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002649 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002650 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002651
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002652 // Explictly declared @interface's are already synthesized.
2653 if (CDecl->ImplicitInterfaceDecl()) {
2654 // FIXME: Implementation of a class with no @interface (legacy) doese not
2655 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002656 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002657 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002658
Chris Lattnerbe6df082007-12-12 07:56:42 +00002659 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002660 unsigned NumIvars = !IDecl->ivar_empty()
2661 ? IDecl->ivar_size()
2662 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002663 if (NumIvars > 0) {
2664 static bool objc_ivar = false;
2665 if (!objc_ivar) {
2666 /* struct _objc_ivar {
2667 char *ivar_name;
2668 char *ivar_type;
2669 int ivar_offset;
2670 };
2671 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002672 Result += "\nstruct _objc_ivar {\n";
2673 Result += "\tchar *ivar_name;\n";
2674 Result += "\tchar *ivar_type;\n";
2675 Result += "\tint ivar_offset;\n";
2676 Result += "};\n";
2677
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002678 objc_ivar = true;
2679 }
2680
Steve Naroff946a6932008-03-11 00:12:29 +00002681 /* struct {
2682 int ivar_count;
2683 struct _objc_ivar ivar_list[nIvars];
2684 };
2685 */
2686 Result += "\nstatic struct {\n";
2687 Result += "\tint ivar_count;\n";
2688 Result += "\tstruct _objc_ivar ivar_list[";
2689 Result += utostr(NumIvars);
2690 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002691 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002692 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002693 "{\n\t";
2694 Result += utostr(NumIvars);
2695 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002696
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002697 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002698 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002699 IVI = IDecl->ivar_begin();
2700 IVE = IDecl->ivar_end();
2701 } else {
2702 IVI = CDecl->ivar_begin();
2703 IVE = CDecl->ivar_end();
2704 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002705 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002706 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002707 Result += "\", \"";
2708 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002709 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2710 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002711 Result += StrEncoding;
2712 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002713 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002714 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002715 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002716 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002717 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002718 Result += "\", \"";
2719 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002720 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2721 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002722 Result += StrEncoding;
2723 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002724 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002725 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002726 }
2727
2728 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002729 }
2730
2731 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002732 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002733 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002734
2735 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002736 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002737 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002738
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002739 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002740 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002741 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002742 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002743
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002744
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002745 // Declaration of class/meta-class metadata
2746 /* struct _objc_class {
2747 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002748 const char *super_class_name;
2749 char *name;
2750 long version;
2751 long info;
2752 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002753 struct _objc_ivar_list *ivars;
2754 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002755 struct objc_cache *cache;
2756 struct objc_protocol_list *protocols;
2757 const char *ivar_layout;
2758 struct _objc_class_ext *ext;
2759 };
2760 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002761 static bool objc_class = false;
2762 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += "\nstruct _objc_class {\n";
2764 Result += "\tstruct _objc_class *isa;\n";
2765 Result += "\tconst char *super_class_name;\n";
2766 Result += "\tchar *name;\n";
2767 Result += "\tlong version;\n";
2768 Result += "\tlong info;\n";
2769 Result += "\tlong instance_size;\n";
2770 Result += "\tstruct _objc_ivar_list *ivars;\n";
2771 Result += "\tstruct _objc_method_list *methods;\n";
2772 Result += "\tstruct objc_cache *cache;\n";
2773 Result += "\tstruct _objc_protocol_list *protocols;\n";
2774 Result += "\tconst char *ivar_layout;\n";
2775 Result += "\tstruct _objc_class_ext *ext;\n";
2776 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002777 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002778 }
2779
2780 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002781 ObjCInterfaceDecl *RootClass = 0;
2782 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002783 while (SuperClass) {
2784 RootClass = SuperClass;
2785 SuperClass = SuperClass->getSuperClass();
2786 }
2787 SuperClass = CDecl->getSuperClass();
2788
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002789 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2790 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002791 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002792 "{\n\t(struct _objc_class *)\"";
2793 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2794 Result += "\"";
2795
2796 if (SuperClass) {
2797 Result += ", \"";
2798 Result += SuperClass->getName();
2799 Result += "\", \"";
2800 Result += CDecl->getName();
2801 Result += "\"";
2802 }
2803 else {
2804 Result += ", 0, \"";
2805 Result += CDecl->getName();
2806 Result += "\"";
2807 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002808 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002809 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002811 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002812 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002813 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002814 Result += "\n";
2815 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002816 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002817 Result += ", 0\n";
2818 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002819 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002820 Result += CDecl->getName();
2821 Result += ",0,0\n";
2822 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002823 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002824 Result += "\t,0,0,0,0\n";
2825 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002826
2827 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2829 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002830 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002831 "{\n\t&_OBJC_METACLASS_";
2832 Result += CDecl->getName();
2833 if (SuperClass) {
2834 Result += ", \"";
2835 Result += SuperClass->getName();
2836 Result += "\", \"";
2837 Result += CDecl->getName();
2838 Result += "\"";
2839 }
2840 else {
2841 Result += ", 0, \"";
2842 Result += CDecl->getName();
2843 Result += "\"";
2844 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002845 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002846 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002847 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002848 Result += ",0";
2849 else {
2850 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002851 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002852 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002853 if (LangOpts.Microsoft)
2854 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002855 Result += ")";
2856 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002857 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002858 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002859 Result += CDecl->getName();
2860 Result += "\n\t";
2861 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002862 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002863 Result += ",0";
2864 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002865 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002866 Result += CDecl->getName();
2867 Result += ", 0\n\t";
2868 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002869 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002870 Result += ",0,0";
2871 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002872 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002873 Result += CDecl->getName();
2874 Result += ", 0,0\n";
2875 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002876 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002877 Result += ",0,0,0\n";
2878 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002879}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002880
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002881/// RewriteImplementations - This routine rewrites all method implementations
2882/// and emits meta-data.
2883
2884void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002885 int ClsDefCount = ClassImplementation.size();
2886 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002887
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002888 if (ClsDefCount == 0 && CatDefCount == 0)
2889 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002890 // Rewrite implemented methods
2891 for (int i = 0; i < ClsDefCount; i++)
2892 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002893
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002894 for (int i = 0; i < CatDefCount; i++)
2895 RewriteImplementationDecl(CategoryImplementation[i]);
2896
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002897 // This is needed for use of offsetof
2898 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002899
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002900 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002901 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002902 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002903
2904 // For each implemented category, write out all its meta data.
2905 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002906 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002907
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002908 // Write objc_symtab metadata
2909 /*
2910 struct _objc_symtab
2911 {
2912 long sel_ref_cnt;
2913 SEL *refs;
2914 short cls_def_cnt;
2915 short cat_def_cnt;
2916 void *defs[cls_def_cnt + cat_def_cnt];
2917 };
2918 */
2919
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002920 Result += "\nstruct _objc_symtab {\n";
2921 Result += "\tlong sel_ref_cnt;\n";
2922 Result += "\tSEL *refs;\n";
2923 Result += "\tshort cls_def_cnt;\n";
2924 Result += "\tshort cat_def_cnt;\n";
2925 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2926 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002927
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002928 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002929 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 Result += "\t0, 0, " + utostr(ClsDefCount)
2931 + ", " + utostr(CatDefCount) + "\n";
2932 for (int i = 0; i < ClsDefCount; i++) {
2933 Result += "\t,&_OBJC_CLASS_";
2934 Result += ClassImplementation[i]->getName();
2935 Result += "\n";
2936 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002937
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002938 for (int i = 0; i < CatDefCount; i++) {
2939 Result += "\t,&_OBJC_CATEGORY_";
2940 Result += CategoryImplementation[i]->getClassInterface()->getName();
2941 Result += "_";
2942 Result += CategoryImplementation[i]->getName();
2943 Result += "\n";
2944 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002945
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002946 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002947
2948 // Write objc_module metadata
2949
2950 /*
2951 struct _objc_module {
2952 long version;
2953 long size;
2954 const char *name;
2955 struct _objc_symtab *symtab;
2956 }
2957 */
2958
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002959 Result += "\nstruct _objc_module {\n";
2960 Result += "\tlong version;\n";
2961 Result += "\tlong size;\n";
2962 Result += "\tconst char *name;\n";
2963 Result += "\tstruct _objc_symtab *symtab;\n";
2964 Result += "};\n\n";
2965 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002966 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002967 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2968 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002969 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002970
2971 if (LangOpts.Microsoft) {
2972 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2973 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2974 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2975 Result += "&_OBJC_MODULES;\n";
2976 Result += "#pragma data_seg(pop)\n\n";
2977 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002978}
Chris Lattner311ff022007-10-16 22:36:42 +00002979