blob: 2b48a635873001b853f5e315e2bc742fec1e711d [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"
Steve Naroff874e2322007-11-15 10:28:18 +000026#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000027using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000029
Steve Naroff0113c9d2008-01-28 21:34:52 +000030static llvm::cl::opt<bool>
31SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
32 llvm::cl::desc("Silence ObjC rewriting warnings"));
33
Chris Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
40
Chris Lattner01c57482007-10-17 22:35:30 +000041 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000042 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000043 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
50 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000051 llvm::SmallVector<Stmt *, 32> Stmts;
52 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000053 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000054
55 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000056 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000057 FunctionDecl *MsgSendStretFunctionDecl;
58 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000059 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000061 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000062 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000063 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000064 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065
Steve Naroffbeaf2992007-11-03 11:27:19 +000066 // ObjC string constant support.
67 FileVarDecl *ConstantStringClassReference;
68 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000069
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000070 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000071 int BcLabelCount;
72
Steve Naroff874e2322007-11-15 10:28:18 +000073 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000075 RecordDecl *SuperStructDecl;
76
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000077 // Needed for header files being rewritten
78 bool IsHeader;
79
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000080 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000081 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000082 void Initialize(ASTContext &context);
83
Chris Lattner8a12c272007-10-11 18:38:32 +000084
Chris Lattnerf04da132007-10-24 17:06:59 +000085 // Top Level Driver code.
86 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000087 void HandleDeclInMainFile(Decl *D);
Steve Naroff4f943c22008-03-10 20:43:59 +000088 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
89 Diags(D), LangOpts(LOpts) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000090 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000091 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
92 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000093 }
Chris Lattnerf04da132007-10-24 17:06:59 +000094 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000095
96 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000097 // If replacement succeeded or warning disabled return with no warning.
98 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000099 return;
100
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000101 SourceRange Range = Old->getSourceRange();
102 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
103 0, 0, &Range, 1);
104 }
105
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000106 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000107 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000108 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
109 SilenceRewriteMacroWarning)
110 return;
111
112 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
113 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000114
Chris Lattneraadaf782008-01-31 19:51:04 +0000115 void RemoveText(SourceLocation Loc, unsigned StrLen) {
116 // If removal succeeded or warning disabled return with no warning.
117 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
118 return;
119
120 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
121 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000122
Chris Lattneraadaf782008-01-31 19:51:04 +0000123 void ReplaceText(SourceLocation Start, unsigned OrigLength,
124 const char *NewStr, unsigned NewLength) {
125 // If removal succeeded or warning disabled return with no warning.
126 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
127 SilenceRewriteMacroWarning)
128 return;
129
130 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
131 }
132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000134 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000135 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000136 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000137 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
138 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000139 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000140 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
141 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
142 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
143 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
144 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
145 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000146 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000147 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000148 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000150 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000151
Chris Lattnerf04da132007-10-24 17:06:59 +0000152 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000153 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000154 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000155 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000156 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000158 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000159 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000161 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000162 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
163 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
164 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000165 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
166 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000169 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000170 Stmt *RewriteBreakStmt(BreakStmt *S);
171 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000172 void SynthCountByEnumWithState(std::string &buf);
173
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000175 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000176 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000177 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000178 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000179 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000180 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000181 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000182 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000183 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000186 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000187 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000188
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000189 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000190 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000191
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
193 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000194 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000195 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000196 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000197 const char *ClassName,
198 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000199
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201 int NumProtocols,
202 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000203 const char *ClassName,
204 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000206 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
208 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000209 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000210 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000211 };
212}
213
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000214static bool IsHeaderFile(const std::string &Filename) {
215 std::string::size_type DotPos = Filename.rfind('.');
216
217 if (DotPos == std::string::npos) {
218 // no file extension
219 return false;
220 }
221
222 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
223 // C header: .h
224 // C++ header: .hh or .H;
225 return Ext == "h" || Ext == "hh" || Ext == "H";
226}
227
228ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000229 Diagnostic &Diags,
230 const LangOptions &LOpts) {
231 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000232}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000233
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000234void RewriteTest::Initialize(ASTContext &context) {
235 Context = &context;
236 SM = &Context->getSourceManager();
237 MsgSendFunctionDecl = 0;
238 MsgSendSuperFunctionDecl = 0;
239 MsgSendStretFunctionDecl = 0;
240 MsgSendSuperStretFunctionDecl = 0;
241 MsgSendFpretFunctionDecl = 0;
242 GetClassFunctionDecl = 0;
243 GetMetaClassFunctionDecl = 0;
244 SelGetUidFunctionDecl = 0;
245 CFStringFunctionDecl = 0;
246 GetProtocolFunctionDecl = 0;
247 ConstantStringClassReference = 0;
248 NSStringRecord = 0;
249 CurMethodDecl = 0;
250 SuperStructDecl = 0;
251 BcLabelCount = 0;
252
253 // Get the ID and start/end of the main file.
254 MainFileID = SM->getMainFileID();
255 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
256 MainFileStart = MainBuf->getBufferStart();
257 MainFileEnd = MainBuf->getBufferEnd();
258
259
260 Rewrite.setSourceMgr(Context->getSourceManager());
261 // declaring objc_selector outside the parameter list removes a silly
262 // scope related warning...
263 const char *s = "#pragma once\n"
264 "struct objc_selector; struct objc_class;\n"
265 "#ifndef OBJC_SUPER\n"
266 "struct objc_super { struct objc_object *o; "
267 "struct objc_object *superClass; };\n"
268 "#define OBJC_SUPER\n"
269 "#endif\n"
270 "#ifndef _REWRITER_typedef_Protocol\n"
271 "typedef struct objc_object Protocol;\n"
272 "#define _REWRITER_typedef_Protocol\n"
273 "#endif\n"
274 "extern struct objc_object *objc_msgSend"
275 "(struct objc_object *, struct objc_selector *, ...);\n"
276 "extern struct objc_object *objc_msgSendSuper"
277 "(struct objc_super *, struct objc_selector *, ...);\n"
278 "extern struct objc_object *objc_msgSend_stret"
279 "(struct objc_object *, struct objc_selector *, ...);\n"
280 "extern struct objc_object *objc_msgSendSuper_stret"
281 "(struct objc_super *, struct objc_selector *, ...);\n"
282 "extern struct objc_object *objc_msgSend_fpret"
283 "(struct objc_object *, struct objc_selector *, ...);\n"
284 "extern struct objc_object *objc_getClass"
285 "(const char *);\n"
286 "extern struct objc_object *objc_getMetaClass"
287 "(const char *);\n"
288 "extern void objc_exception_throw(struct objc_object *);\n"
289 "extern void objc_exception_try_enter(void *);\n"
290 "extern void objc_exception_try_exit(void *);\n"
291 "extern struct objc_object *objc_exception_extract(void *);\n"
292 "extern int objc_exception_match"
293 "(struct objc_class *, struct objc_object *, ...);\n"
294 "extern Protocol *objc_getProtocol(const char *);\n"
295 "#include <objc/objc.h>\n"
296 "#ifndef __FASTENUMERATIONSTATE\n"
297 "struct __objcFastEnumerationState {\n\t"
298 "unsigned long state;\n\t"
299 "id *itemsPtr;\n\t"
300 "unsigned long *mutationsPtr;\n\t"
301 "unsigned long extra[5];\n};\n"
302 "#define __FASTENUMERATIONSTATE\n"
303 "#endif\n";
Steve Naroff4f943c22008-03-10 20:43:59 +0000304 if (LangOpts.Microsoft) {
305 std::string S = s;
306 S += "#define __attribute__(X)\n";
307 s = S.c_str();
308 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000309 if (IsHeader) {
310 // insert the whole string when rewriting a header file
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000311 InsertText(SourceLocation::getFileLoc(MainFileID, 0), s, strlen(s));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000312 }
313 else {
314 // Not rewriting header, exclude the #pragma once pragma
315 const char *p = s + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000316 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000317 }
318}
319
320
Chris Lattnerf04da132007-10-24 17:06:59 +0000321//===----------------------------------------------------------------------===//
322// Top Level Driver Code
323//===----------------------------------------------------------------------===//
324
Chris Lattner8a12c272007-10-11 18:38:32 +0000325void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000326 // Two cases: either the decl could be in the main file, or it could be in a
327 // #included file. If the former, rewrite it now. If the later, check to see
328 // if we rewrote the #include/#import.
329 SourceLocation Loc = D->getLocation();
330 Loc = SM->getLogicalLoc(Loc);
331
332 // If this is for a builtin, ignore it.
333 if (Loc.isInvalid()) return;
334
Steve Naroffebf2b562007-10-23 23:50:29 +0000335 // Look for built-in declarations that we need to refer during the rewrite.
336 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000337 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000338 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
339 // declared in <Foundation/NSString.h>
340 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
341 ConstantStringClassReference = FVD;
342 return;
343 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000344 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000345 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000346 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000347 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000348 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000349 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000350 } else if (ObjCForwardProtocolDecl *FP =
351 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000352 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000353 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000354 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000355 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
356 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000357}
358
Chris Lattnerf04da132007-10-24 17:06:59 +0000359/// HandleDeclInMainFile - This is called for each top-level decl defined in the
360/// main file of the input.
361void RewriteTest::HandleDeclInMainFile(Decl *D) {
362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
363 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000364 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000365
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000366 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000367 if (Stmt *Body = MD->getBody()) {
368 //Body->dump();
369 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000370 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000371 CurMethodDecl = 0;
372 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000373 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000374 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000375 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000377 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000379 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000380 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000381 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000382 if (VD->getInit())
383 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
384 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000385 // Nothing yet.
386}
387
388RewriteTest::~RewriteTest() {
389 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000390
391 // Rewrite tabs if we care.
392 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000393
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000394 RewriteInclude();
395
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000396 // Rewrite Objective-c meta data*
397 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000398 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000399
Chris Lattnerf04da132007-10-24 17:06:59 +0000400 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
401 // we are done.
402 if (const RewriteBuffer *RewriteBuf =
403 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000404 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000405 std::string S(RewriteBuf->begin(), RewriteBuf->end());
406 printf("%s\n", S.c_str());
407 } else {
408 printf("No changes\n");
409 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000410 // Emit metadata.
411 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000412}
413
Chris Lattnerf04da132007-10-24 17:06:59 +0000414//===----------------------------------------------------------------------===//
415// Syntactic (non-AST) Rewriting Code
416//===----------------------------------------------------------------------===//
417
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000418void RewriteTest::RewriteInclude() {
419 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
420 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
421 const char *MainBufStart = MainBuf.first;
422 const char *MainBufEnd = MainBuf.second;
423 size_t ImportLen = strlen("import");
424 size_t IncludeLen = strlen("include");
425
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000426 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000427 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
428 if (*BufPtr == '#') {
429 if (++BufPtr == MainBufEnd)
430 return;
431 while (*BufPtr == ' ' || *BufPtr == '\t')
432 if (++BufPtr == MainBufEnd)
433 return;
434 if (!strncmp(BufPtr, "import", ImportLen)) {
435 // replace import with include
436 SourceLocation ImportLoc =
437 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000438 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000439 BufPtr += ImportLen;
440 }
441 }
442 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000443}
444
Chris Lattnerf04da132007-10-24 17:06:59 +0000445void RewriteTest::RewriteTabs() {
446 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
447 const char *MainBufStart = MainBuf.first;
448 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000449
Chris Lattnerf04da132007-10-24 17:06:59 +0000450 // Loop over the whole file, looking for tabs.
451 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
452 if (*BufPtr != '\t')
453 continue;
454
455 // Okay, we found a tab. This tab will turn into at least one character,
456 // but it depends on which 'virtual column' it is in. Compute that now.
457 unsigned VCol = 0;
458 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
459 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
460 ++VCol;
461
462 // Okay, now that we know the virtual column, we know how many spaces to
463 // insert. We assume 8-character tab-stops.
464 unsigned Spaces = 8-(VCol & 7);
465
466 // Get the location of the tab.
467 SourceLocation TabLoc =
468 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
469
470 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000471 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000472 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000473}
474
475
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000476void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000477 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000478 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000479
480 // Get the start location and compute the semi location.
481 SourceLocation startLoc = ClassDecl->getLocation();
482 const char *startBuf = SM->getCharacterData(startLoc);
483 const char *semiPtr = strchr(startBuf, ';');
484
485 // Translate to typedef's that forward reference structs with the same name
486 // as the class. As a convenience, we include the original declaration
487 // as a comment.
488 std::string typedefString;
489 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000490 typedefString.append(startBuf, semiPtr-startBuf+1);
491 typedefString += "\n";
492 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000493 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000494 typedefString += "#ifndef _REWRITER_typedef_";
495 typedefString += ForwardDecl->getName();
496 typedefString += "\n";
497 typedefString += "#define _REWRITER_typedef_";
498 typedefString += ForwardDecl->getName();
499 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000500 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000501 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000502 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000503 }
504
505 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000506 ReplaceText(startLoc, semiPtr-startBuf+1,
507 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000508}
509
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000510void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000511 SourceLocation LocStart = Method->getLocStart();
512 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000513
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000514 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000515 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000516 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000517 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000518 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000519 }
520}
521
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000522void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000523{
524 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000525 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000526 SourceLocation Loc = Property->getLocation();
527
Chris Lattneraadaf782008-01-31 19:51:04 +0000528 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000529
530 // FIXME: handle properties that are declared across multiple lines.
531 }
532}
533
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000534void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000535 SourceLocation LocStart = CatDecl->getLocStart();
536
537 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000538 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000539
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000540 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000541 E = CatDecl->instmeth_end(); I != E; ++I)
542 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000544 E = CatDecl->classmeth_end(); I != E; ++I)
545 RewriteMethodDeclaration(*I);
546
Steve Naroff423cb562007-10-30 13:30:57 +0000547 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000548 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000549}
550
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000551void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000552 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000553
Steve Naroff752d6ef2007-10-30 16:42:30 +0000554 SourceLocation LocStart = PDecl->getLocStart();
555
556 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000557 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000558
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000559 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000560 E = PDecl->instmeth_end(); I != E; ++I)
561 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000562 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000563 E = PDecl->classmeth_end(); I != E; ++I)
564 RewriteMethodDeclaration(*I);
565
Steve Naroff752d6ef2007-10-30 16:42:30 +0000566 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000567 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000568 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000569
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000570 // Must comment out @optional/@required
571 const char *startBuf = SM->getCharacterData(LocStart);
572 const char *endBuf = SM->getCharacterData(LocEnd);
573 for (const char *p = startBuf; p < endBuf; p++) {
574 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
575 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000576 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000577 ReplaceText(OptionalLoc, strlen("@optional"),
578 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000579
580 }
581 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
582 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000583 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000584 ReplaceText(OptionalLoc, strlen("@required"),
585 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000586
587 }
588 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000589}
590
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000592 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000593 if (LocStart.isInvalid())
594 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000595 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000596 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000597}
598
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000599void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000600 std::string &ResultStr) {
601 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000602 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000603 ResultStr += "id";
604 else
605 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000606 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000607
608 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000609 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000610
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000611 if (OMD->isInstance())
612 NameStr += "_I_";
613 else
614 NameStr += "_C_";
615
616 NameStr += OMD->getClassInterface()->getName();
617 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000618
619 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000620 if (ObjCCategoryImplDecl *CID =
621 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000622 NameStr += CID->getName();
623 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000624 }
625 // Append selector names, replacing ':' with '_'
626 const char *selName = OMD->getSelector().getName().c_str();
627 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000628 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000629 else {
630 std::string selString = OMD->getSelector().getName();
631 int len = selString.size();
632 for (int i = 0; i < len; i++)
633 if (selString[i] == ':')
634 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000635 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000636 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000637 // Remember this name for metadata emission
638 MethodInternalNames[OMD] = NameStr;
639 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000640
641 // Rewrite arguments
642 ResultStr += "(";
643
644 // invisible arguments
645 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000646 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000647 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000648 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000649 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000650 ResultStr += selfTy.getAsString();
651 }
652 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000653 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000654
655 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000656 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000657 ResultStr += " _cmd";
658
659 // Method arguments.
660 for (int i = 0; i < OMD->getNumParams(); i++) {
661 ParmVarDecl *PDecl = OMD->getParamDecl(i);
662 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000664 ResultStr += "id";
665 else
666 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000667 ResultStr += " ";
668 ResultStr += PDecl->getName();
669 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000670 if (OMD->isVariadic())
671 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000672 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000673
674}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000675void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
677 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000678
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000679 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000680 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000681 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000682 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000683
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000685 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
686 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000687 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 ObjCMethodDecl *OMD = *I;
689 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690 SourceLocation LocStart = OMD->getLocStart();
691 SourceLocation LocEnd = OMD->getBody()->getLocStart();
692
693 const char *startBuf = SM->getCharacterData(LocStart);
694 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000695 ReplaceText(LocStart, endBuf-startBuf,
696 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000697 }
698
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000699 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000700 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
701 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 ObjCMethodDecl *OMD = *I;
704 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000705 SourceLocation LocStart = OMD->getLocStart();
706 SourceLocation LocEnd = OMD->getBody()->getLocStart();
707
708 const char *startBuf = SM->getCharacterData(LocStart);
709 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000710 ReplaceText(LocStart, endBuf-startBuf,
711 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000712 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000713 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000714 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000715 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000716 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717}
718
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000719void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000720 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000721 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000722 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000723 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000724 ResultStr += ClassDecl->getName();
725 ResultStr += "\n";
726 ResultStr += "#define _REWRITER_typedef_";
727 ResultStr += ClassDecl->getName();
728 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000729 ResultStr += "typedef struct ";
730 ResultStr += ClassDecl->getName();
731 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000732 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000733 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000734
735 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000737 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000739
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000740 RewriteProperties(ClassDecl->getNumPropertyDecl(),
741 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000743 E = ClassDecl->instmeth_end(); I != E; ++I)
744 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000745 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000746 E = ClassDecl->classmeth_end(); I != E; ++I)
747 RewriteMethodDeclaration(*I);
748
Steve Naroff2feac5e2007-10-30 03:43:13 +0000749 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000750 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000751}
752
Steve Naroff7e3411b2007-11-15 02:58:25 +0000753Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000755 if (IV->isFreeIvar()) {
756 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
Eli Friedman51019072008-02-06 22:48:16 +0000757 IV->getLocation(), D->getType());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000758 ReplaceStmt(IV, Replacement);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000759 delete IV;
760 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000761 } else {
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000762#if 0
763 /// This code is not right. It seems unnecessary. It breaks use of
764 /// ivar reference used as 'receiver' of an expression; as in:
765 /// [newInv->_container addObject:0];
Steve Naroffc2a689b2007-11-15 11:33:00 +0000766 if (CurMethodDecl) {
767 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000769 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
770 IdentifierInfo *II = intT->getDecl()->getIdentifier();
771 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
772 II, 0);
773 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
774
775 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
776 // Don't forget the parens to enforce the proper binding.
777 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000778 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000779 delete IV->getBase();
780 return PE;
781 }
782 }
783 }
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000784#endif
Steve Naroff7e3411b2007-11-15 02:58:25 +0000785 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000786 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000787}
788
Chris Lattnerf04da132007-10-24 17:06:59 +0000789//===----------------------------------------------------------------------===//
790// Function Body / Expression rewriting
791//===----------------------------------------------------------------------===//
792
Steve Narofff3473a72007-11-09 15:20:18 +0000793Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000794 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
795 isa<DoStmt>(S) || isa<ForStmt>(S))
796 Stmts.push_back(S);
797 else if (isa<ObjCForCollectionStmt>(S)) {
798 Stmts.push_back(S);
799 ObjCBcLabelNo.push_back(++BcLabelCount);
800 }
801
Chris Lattner338d1e22008-01-31 05:10:40 +0000802 SourceLocation OrigStmtEnd = S->getLocEnd();
803
804 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000805 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
806 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000807 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000808 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000809 if (newStmt)
810 *CI = newStmt;
811 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000812
813 // Handle specific things.
814 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
815 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000816
817 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
818 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000819
820 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
821 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000822
Steve Naroffbeaf2992007-11-03 11:27:19 +0000823 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
824 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000825
Steve Naroff934f2762007-10-24 22:48:43 +0000826 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
827 // Before we rewrite it, put the original message expression in a comment.
828 SourceLocation startLoc = MessExpr->getLocStart();
829 SourceLocation endLoc = MessExpr->getLocEnd();
830
831 const char *startBuf = SM->getCharacterData(startLoc);
832 const char *endBuf = SM->getCharacterData(endLoc);
833
834 std::string messString;
835 messString += "// ";
836 messString.append(startBuf, endBuf-startBuf+1);
837 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000838
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000839 // FIXME: Missing definition of
840 // InsertText(clang::SourceLocation, char const*, unsigned int).
841 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000842 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000843 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000844 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000845 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000846
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000847 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
848 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000849
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000850 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
851 return RewriteObjCSynchronizedStmt(StmtTry);
852
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
854 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000855
856 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
857 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000858
859 if (ObjCForCollectionStmt *StmtForCollection =
860 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000861 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000862 if (BreakStmt *StmtBreakStmt =
863 dyn_cast<BreakStmt>(S))
864 return RewriteBreakStmt(StmtBreakStmt);
865 if (ContinueStmt *StmtContinueStmt =
866 dyn_cast<ContinueStmt>(S))
867 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000868
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000869 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
870 isa<DoStmt>(S) || isa<ForStmt>(S)) {
871 assert(!Stmts.empty() && "Statement stack is empty");
872 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
873 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
874 && "Statement stack mismatch");
875 Stmts.pop_back();
876 }
Steve Naroff874e2322007-11-15 10:28:18 +0000877#if 0
878 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
879 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
880 // Get the new text.
881 std::ostringstream Buf;
882 Replacement->printPretty(Buf);
883 const std::string &Str = Buf.str();
884
885 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000886 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000887 delete S;
888 return Replacement;
889 }
890#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000891 // Return this stmt unmodified.
892 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000893}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000894
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000895/// SynthCountByEnumWithState - To print:
896/// ((unsigned int (*)
897/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
898/// (void *)objc_msgSend)((id)l_collection,
899/// sel_registerName(
900/// "countByEnumeratingWithState:objects:count:"),
901/// &enumState,
902/// (id *)items, (unsigned int)16)
903///
904void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
905 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
906 "id *, unsigned int))(void *)objc_msgSend)";
907 buf += "\n\t\t";
908 buf += "((id)l_collection,\n\t\t";
909 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
910 buf += "\n\t\t";
911 buf += "&enumState, "
912 "(id *)items, (unsigned int)16)";
913}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000914
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000915/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
916/// statement to exit to its outer synthesized loop.
917///
918Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
919 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
920 return S;
921 // replace break with goto __break_label
922 std::string buf;
923
924 SourceLocation startLoc = S->getLocStart();
925 buf = "goto __break_label_";
926 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000927 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000928
929 return 0;
930}
931
932/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
933/// statement to continue with its inner synthesized loop.
934///
935Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
936 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
937 return S;
938 // replace continue with goto __continue_label
939 std::string buf;
940
941 SourceLocation startLoc = S->getLocStart();
942 buf = "goto __continue_label_";
943 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000944 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000945
946 return 0;
947}
948
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000949/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000950/// It rewrites:
951/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000952
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000953/// Into:
954/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000955/// type elem;
956/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000957/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000958/// id l_collection = (id)collection;
959/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
960/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000961/// if (limit) {
962/// unsigned long startMutations = *enumState.mutationsPtr;
963/// do {
964/// unsigned long counter = 0;
965/// do {
966/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000967/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000968/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000969/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000970/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000971/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000972/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
973/// objects:items count:16]);
974/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000975/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000976/// }
977/// else
978/// elem = nil;
979/// }
980///
Chris Lattner338d1e22008-01-31 05:10:40 +0000981Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
982 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000983 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
984 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
985 "ObjCForCollectionStmt Statement stack mismatch");
986 assert(!ObjCBcLabelNo.empty() &&
987 "ObjCForCollectionStmt - Label No stack empty");
988
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000989 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000990 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000991 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000992 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000993 std::string buf;
994 buf = "\n{\n\t";
995 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
996 // type elem;
997 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000998 elementTypeAsString = ElementType.getAsString();
999 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001000 buf += " ";
1001 elementName = DS->getDecl()->getName();
1002 buf += elementName;
1003 buf += ";\n\t";
1004 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001005 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001006 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001007 elementTypeAsString = DR->getDecl()->getType().getAsString();
1008 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001009 else
1010 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1011
1012 // struct __objcFastEnumerationState enumState = { 0 };
1013 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1014 // id items[16];
1015 buf += "id items[16];\n\t";
1016 // id l_collection = (id)
1017 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001018 // Find start location of 'collection' the hard way!
1019 const char *startCollectionBuf = startBuf;
1020 startCollectionBuf += 3; // skip 'for'
1021 startCollectionBuf = strchr(startCollectionBuf, '(');
1022 startCollectionBuf++; // skip '('
1023 // find 'in' and skip it.
1024 while (*startCollectionBuf != ' ' ||
1025 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1026 (*(startCollectionBuf+3) != ' ' &&
1027 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1028 startCollectionBuf++;
1029 startCollectionBuf += 3;
1030
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001031 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001032 ReplaceText(startLoc, startCollectionBuf - startBuf,
1033 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001034 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001035 SourceLocation rightParenLoc = S->getRParenLoc();
1036 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1037 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001038 buf = ";\n\t";
1039
1040 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1041 // objects:items count:16];
1042 // which is synthesized into:
1043 // unsigned int limit =
1044 // ((unsigned int (*)
1045 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1046 // (void *)objc_msgSend)((id)l_collection,
1047 // sel_registerName(
1048 // "countByEnumeratingWithState:objects:count:"),
1049 // (struct __objcFastEnumerationState *)&state,
1050 // (id *)items, (unsigned int)16);
1051 buf += "unsigned long limit =\n\t\t";
1052 SynthCountByEnumWithState(buf);
1053 buf += ";\n\t";
1054 /// if (limit) {
1055 /// unsigned long startMutations = *enumState.mutationsPtr;
1056 /// do {
1057 /// unsigned long counter = 0;
1058 /// do {
1059 /// if (startMutations != *enumState.mutationsPtr)
1060 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001061 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001062 buf += "if (limit) {\n\t";
1063 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1064 buf += "do {\n\t\t";
1065 buf += "unsigned long counter = 0;\n\t\t";
1066 buf += "do {\n\t\t\t";
1067 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1068 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1069 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001070 buf += " = (";
1071 buf += elementTypeAsString;
1072 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001073 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001074 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001076 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001077 /// } while (counter < limit);
1078 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1079 /// objects:items count:16]);
1080 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001081 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001082 /// }
1083 /// else
1084 /// elem = nil;
1085 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001086 ///
1087 buf = ";\n\t";
1088 buf += "__continue_label_";
1089 buf += utostr(ObjCBcLabelNo.back());
1090 buf += ": ;";
1091 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092 buf += "} while (counter < limit);\n\t";
1093 buf += "} while (limit = ";
1094 SynthCountByEnumWithState(buf);
1095 buf += ");\n\t";
1096 buf += elementName;
1097 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001098 buf += "__break_label_";
1099 buf += utostr(ObjCBcLabelNo.back());
1100 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101 buf += "}\n\t";
1102 buf += "else\n\t\t";
1103 buf += elementName;
1104 buf += " = nil;\n";
1105 buf += "}\n";
1106 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001107 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001108 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001109 Stmts.pop_back();
1110 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001111 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001112}
1113
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001114/// RewriteObjCSynchronizedStmt -
1115/// This routine rewrites @synchronized(expr) stmt;
1116/// into:
1117/// objc_sync_enter(expr);
1118/// @try stmt @finally { objc_sync_exit(expr); }
1119///
1120Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1121 // Get the start location and compute the semi location.
1122 SourceLocation startLoc = S->getLocStart();
1123 const char *startBuf = SM->getCharacterData(startLoc);
1124
1125 assert((*startBuf == '@') && "bogus @synchronized location");
1126
1127 std::string buf;
1128 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001129 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001130 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1131 const char *endBuf = SM->getCharacterData(endLoc);
1132 endBuf++;
1133 const char *rparenBuf = strchr(endBuf, ')');
1134 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1135 buf = ");\n";
1136 // declare a new scope with two variables, _stack and _rethrow.
1137 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1138 buf += "int buf[18/*32-bit i386*/];\n";
1139 buf += "char *pointers[4];} _stack;\n";
1140 buf += "id volatile _rethrow = 0;\n";
1141 buf += "objc_exception_try_enter(&_stack);\n";
1142 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001143 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001144 startLoc = S->getSynchBody()->getLocEnd();
1145 startBuf = SM->getCharacterData(startLoc);
1146
1147 assert((*startBuf == '}') && "bogus @try block");
1148 SourceLocation lastCurlyLoc = startLoc;
1149 buf = "}\nelse {\n";
1150 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1151 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1152 // FIXME: This must be objc_sync_exit(syncExpr);
1153 buf += " objc_sync_exit();\n";
1154 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1155 buf += "}\n";
1156 buf += "}";
1157
Chris Lattneraadaf782008-01-31 19:51:04 +00001158 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001159 return 0;
1160}
1161
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001162Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001163 // Get the start location and compute the semi location.
1164 SourceLocation startLoc = S->getLocStart();
1165 const char *startBuf = SM->getCharacterData(startLoc);
1166
1167 assert((*startBuf == '@') && "bogus @try location");
1168
1169 std::string buf;
1170 // declare a new scope with two variables, _stack and _rethrow.
1171 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1172 buf += "int buf[18/*32-bit i386*/];\n";
1173 buf += "char *pointers[4];} _stack;\n";
1174 buf += "id volatile _rethrow = 0;\n";
1175 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001176 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001177
Chris Lattneraadaf782008-01-31 19:51:04 +00001178 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001179
1180 startLoc = S->getTryBody()->getLocEnd();
1181 startBuf = SM->getCharacterData(startLoc);
1182
1183 assert((*startBuf == '}') && "bogus @try block");
1184
1185 SourceLocation lastCurlyLoc = startLoc;
1186
1187 startLoc = startLoc.getFileLocWithOffset(1);
1188 buf = " /* @catch begin */ else {\n";
1189 buf += " id _caught = objc_exception_extract(&_stack);\n";
1190 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001191 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001192 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1193 buf += " else { /* @catch continue */";
1194
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001195 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001196
1197 bool sawIdTypedCatch = false;
1198 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001200 while (catchList) {
1201 Stmt *catchStmt = catchList->getCatchParamStmt();
1202
1203 if (catchList == S->getCatchStmts())
1204 buf = "if ("; // we are generating code for the first catch clause
1205 else
1206 buf = "else if (";
1207 startLoc = catchList->getLocStart();
1208 startBuf = SM->getCharacterData(startLoc);
1209
1210 assert((*startBuf == '@') && "bogus @catch location");
1211
1212 const char *lParenLoc = strchr(startBuf, '(');
1213
Steve Naroffbe4b3332008-02-01 22:08:12 +00001214 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001215 // Now rewrite the body...
1216 lastCatchBody = catchList->getCatchBody();
1217 SourceLocation rParenLoc = catchList->getRParenLoc();
1218 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1219 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1220 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1221 assert((*rParenBuf == ')') && "bogus @catch paren location");
1222 assert((*bodyBuf == '{') && "bogus @catch body location");
1223
1224 buf += "1) { id _tmp = _caught;";
1225 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1226 buf.c_str(), buf.size());
1227 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001228 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001229 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001230 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001231 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001232 sawIdTypedCatch = true;
1233 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001234 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001235
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001236 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001237 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001238 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001239 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001240 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001241 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001242 }
1243 }
1244 // Now rewrite the body...
1245 lastCatchBody = catchList->getCatchBody();
1246 SourceLocation rParenLoc = catchList->getRParenLoc();
1247 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1248 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1249 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1250 assert((*rParenBuf == ')') && "bogus @catch paren location");
1251 assert((*bodyBuf == '{') && "bogus @catch body location");
1252
1253 buf = " = _caught;";
1254 // Here we replace ") {" with "= _caught;" (which initializes and
1255 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001256 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001257 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001258 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001259 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001260 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001261 catchList = catchList->getNextCatchStmt();
1262 }
1263 // Complete the catch list...
1264 if (lastCatchBody) {
1265 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1266 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1267 assert((*bodyBuf == '}') && "bogus @catch body location");
1268 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1269 buf = " } } /* @catch end */\n";
1270
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001271 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001272
1273 // Set lastCurlyLoc
1274 lastCurlyLoc = lastCatchBody->getLocEnd();
1275 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001276 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001277 startLoc = finalStmt->getLocStart();
1278 startBuf = SM->getCharacterData(startLoc);
1279 assert((*startBuf == '@') && "bogus @finally start");
1280
1281 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001282 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001283
1284 Stmt *body = finalStmt->getFinallyBody();
1285 SourceLocation startLoc = body->getLocStart();
1286 SourceLocation endLoc = body->getLocEnd();
1287 const char *startBuf = SM->getCharacterData(startLoc);
1288 const char *endBuf = SM->getCharacterData(endLoc);
1289 assert((*startBuf == '{') && "bogus @finally body location");
1290 assert((*endBuf == '}') && "bogus @finally body location");
1291
1292 startLoc = startLoc.getFileLocWithOffset(1);
1293 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001294 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001295 endLoc = endLoc.getFileLocWithOffset(-1);
1296 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001297 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001298
1299 // Set lastCurlyLoc
1300 lastCurlyLoc = body->getLocEnd();
1301 }
1302 // Now emit the final closing curly brace...
1303 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1304 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001305 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001306 return 0;
1307}
1308
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001309Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001310 return 0;
1311}
1312
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001313Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001314 return 0;
1315}
1316
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001317// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001318// the throw expression is typically a message expression that's already
1319// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001320Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001321 // Get the start location and compute the semi location.
1322 SourceLocation startLoc = S->getLocStart();
1323 const char *startBuf = SM->getCharacterData(startLoc);
1324
1325 assert((*startBuf == '@') && "bogus @throw location");
1326
1327 std::string buf;
1328 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001329 if (S->getThrowExpr())
1330 buf = "objc_exception_throw(";
1331 else // add an implicit argument
1332 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001333 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001334 const char *semiBuf = strchr(startBuf, ';');
1335 assert((*semiBuf == ';') && "@throw: can't find ';'");
1336 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1337 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001338 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001339 return 0;
1340}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001341
Chris Lattnere64b7772007-10-24 16:57:36 +00001342Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001343 // Create a new string expression.
1344 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001345 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001346 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1347 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001348 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1349 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001350 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001351 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001352
Chris Lattner07506182007-11-30 22:53:43 +00001353 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001354 delete Exp;
1355 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001356}
1357
Steve Naroffb42f8412007-11-05 14:50:49 +00001358Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1359 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1360 // Create a call to sel_registerName("selName").
1361 llvm::SmallVector<Expr*, 8> SelExprs;
1362 QualType argType = Context->getPointerType(Context->CharTy);
1363 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1364 Exp->getSelector().getName().size(),
1365 false, argType, SourceLocation(),
1366 SourceLocation()));
1367 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1368 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001369 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001370 delete Exp;
1371 return SelExp;
1372}
1373
Steve Naroff934f2762007-10-24 22:48:43 +00001374CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1375 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001376 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001377 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001378
1379 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001380 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001381
1382 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001383 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001384 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1385
1386 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001387
Steve Naroff934f2762007-10-24 22:48:43 +00001388 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1389}
1390
Steve Naroffd5255f52007-11-01 13:24:47 +00001391static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1392 const char *&startRef, const char *&endRef) {
1393 while (startBuf < endBuf) {
1394 if (*startBuf == '<')
1395 startRef = startBuf; // mark the start.
1396 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001397 if (startRef && *startRef == '<') {
1398 endRef = startBuf; // mark the end.
1399 return true;
1400 }
1401 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001402 }
1403 startBuf++;
1404 }
1405 return false;
1406}
1407
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001408static void scanToNextArgument(const char *&argRef) {
1409 int angle = 0;
1410 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1411 if (*argRef == '<')
1412 angle++;
1413 else if (*argRef == '>')
1414 angle--;
1415 argRef++;
1416 }
1417 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1418}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001419
Steve Naroffd5255f52007-11-01 13:24:47 +00001420bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001421
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001422 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001423 return true;
1424
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001425 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001426 return true;
1427
Steve Naroffd5255f52007-11-01 13:24:47 +00001428 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001429 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001430 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001431 return true; // we have "Class <Protocol> *".
1432 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001433 return false;
1434}
1435
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001437 SourceLocation Loc;
1438 QualType Type;
1439 const FunctionTypeProto *proto = 0;
1440 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1441 Loc = VD->getLocation();
1442 Type = VD->getType();
1443 }
1444 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1445 Loc = FD->getLocation();
1446 // Check for ObjC 'id' and class types that have been adorned with protocol
1447 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1448 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1449 assert(funcType && "missing function type");
1450 proto = dyn_cast<FunctionTypeProto>(funcType);
1451 if (!proto)
1452 return;
1453 Type = proto->getResultType();
1454 }
1455 else
1456 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001457
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001458 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001459 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001460
1461 const char *endBuf = SM->getCharacterData(Loc);
1462 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001463 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001464 startBuf--; // scan backward (from the decl location) for return type.
1465 const char *startRef = 0, *endRef = 0;
1466 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1467 // Get the locations of the startRef, endRef.
1468 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1469 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1470 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001471 InsertText(LessLoc, "/*", 2);
1472 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001473 }
1474 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001475 if (!proto)
1476 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001477 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001478 const char *startBuf = SM->getCharacterData(Loc);
1479 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001480 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1481 if (needToScanForQualifiers(proto->getArgType(i))) {
1482 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001483
Steve Naroffd5255f52007-11-01 13:24:47 +00001484 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001485 // scan forward (from the decl location) for argument types.
1486 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001487 const char *startRef = 0, *endRef = 0;
1488 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1489 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001490 SourceLocation LessLoc =
1491 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1492 SourceLocation GreaterLoc =
1493 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001494 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001495 InsertText(LessLoc, "/*", 2);
1496 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001498 startBuf = ++endBuf;
1499 }
1500 else {
1501 while (*startBuf != ')' && *startBuf != ',')
1502 startBuf++; // scan forward (from the decl location) for argument types.
1503 startBuf++;
1504 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001505 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001506}
1507
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001508// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1509void RewriteTest::SynthSelGetUidFunctionDecl() {
1510 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1511 llvm::SmallVector<QualType, 16> ArgTys;
1512 ArgTys.push_back(Context->getPointerType(
1513 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001514 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001515 &ArgTys[0], ArgTys.size(),
1516 false /*isVariadic*/);
1517 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1518 SelGetUidIdent, getFuncType,
1519 FunctionDecl::Extern, false, 0);
1520}
1521
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001522// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1523void RewriteTest::SynthGetProtocolFunctionDecl() {
1524 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1525 llvm::SmallVector<QualType, 16> ArgTys;
1526 ArgTys.push_back(Context->getPointerType(
1527 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001528 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001529 &ArgTys[0], ArgTys.size(),
1530 false /*isVariadic*/);
1531 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1532 SelGetProtoIdent, getFuncType,
1533 FunctionDecl::Extern, false, 0);
1534}
1535
Steve Naroff09b266e2007-10-30 23:14:51 +00001536void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1537 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001538 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001539 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001540 return;
1541 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001542 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001543}
1544
1545// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1546void RewriteTest::SynthMsgSendFunctionDecl() {
1547 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1548 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001549 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001550 assert(!argT.isNull() && "Can't find 'id' type");
1551 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001552 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001553 assert(!argT.isNull() && "Can't find 'SEL' type");
1554 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001555 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001556 &ArgTys[0], ArgTys.size(),
1557 true /*isVariadic*/);
1558 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1559 msgSendIdent, msgSendType,
1560 FunctionDecl::Extern, false, 0);
1561}
1562
Steve Naroff874e2322007-11-15 10:28:18 +00001563// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1564void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1565 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1566 llvm::SmallVector<QualType, 16> ArgTys;
1567 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1568 &Context->Idents.get("objc_super"), 0);
1569 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1570 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1571 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001572 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001573 assert(!argT.isNull() && "Can't find 'SEL' type");
1574 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001575 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001576 &ArgTys[0], ArgTys.size(),
1577 true /*isVariadic*/);
1578 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1579 msgSendIdent, msgSendType,
1580 FunctionDecl::Extern, false, 0);
1581}
1582
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001583// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1584void RewriteTest::SynthMsgSendStretFunctionDecl() {
1585 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1586 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001587 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001588 assert(!argT.isNull() && "Can't find 'id' type");
1589 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001590 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001591 assert(!argT.isNull() && "Can't find 'SEL' type");
1592 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001593 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001594 &ArgTys[0], ArgTys.size(),
1595 true /*isVariadic*/);
1596 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1597 msgSendIdent, msgSendType,
1598 FunctionDecl::Extern, false, 0);
1599}
1600
1601// SynthMsgSendSuperStretFunctionDecl -
1602// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1603void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1604 IdentifierInfo *msgSendIdent =
1605 &Context->Idents.get("objc_msgSendSuper_stret");
1606 llvm::SmallVector<QualType, 16> ArgTys;
1607 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1608 &Context->Idents.get("objc_super"), 0);
1609 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1610 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1611 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001612 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001613 assert(!argT.isNull() && "Can't find 'SEL' type");
1614 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001615 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001616 &ArgTys[0], ArgTys.size(),
1617 true /*isVariadic*/);
1618 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1619 msgSendIdent, msgSendType,
1620 FunctionDecl::Extern, false, 0);
1621}
1622
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001623// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1624void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1625 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1626 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001627 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001628 assert(!argT.isNull() && "Can't find 'id' type");
1629 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001630 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001631 assert(!argT.isNull() && "Can't find 'SEL' type");
1632 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001633 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001634 &ArgTys[0], ArgTys.size(),
1635 true /*isVariadic*/);
1636 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1637 msgSendIdent, msgSendType,
1638 FunctionDecl::Extern, false, 0);
1639}
1640
Steve Naroff09b266e2007-10-30 23:14:51 +00001641// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1642void RewriteTest::SynthGetClassFunctionDecl() {
1643 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1644 llvm::SmallVector<QualType, 16> ArgTys;
1645 ArgTys.push_back(Context->getPointerType(
1646 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001648 &ArgTys[0], ArgTys.size(),
1649 false /*isVariadic*/);
1650 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1651 getClassIdent, getClassType,
1652 FunctionDecl::Extern, false, 0);
1653}
1654
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001655// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1656void RewriteTest::SynthGetMetaClassFunctionDecl() {
1657 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1658 llvm::SmallVector<QualType, 16> ArgTys;
1659 ArgTys.push_back(Context->getPointerType(
1660 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001661 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001662 &ArgTys[0], ArgTys.size(),
1663 false /*isVariadic*/);
1664 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1665 getClassIdent, getClassType,
1666 FunctionDecl::Extern, false, 0);
1667}
1668
Steve Naroff96984642007-11-08 14:30:50 +00001669// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1670void RewriteTest::SynthCFStringFunctionDecl() {
1671 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1672 llvm::SmallVector<QualType, 16> ArgTys;
1673 ArgTys.push_back(Context->getPointerType(
1674 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001675 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001676 &ArgTys[0], ArgTys.size(),
1677 false /*isVariadic*/);
1678 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1679 getClassIdent, getClassType,
1680 FunctionDecl::Extern, false, 0);
1681}
1682
Steve Naroffbeaf2992007-11-03 11:27:19 +00001683Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001684#if 1
1685 // This rewrite is specific to GCC, which has builtin support for CFString.
1686 if (!CFStringFunctionDecl)
1687 SynthCFStringFunctionDecl();
1688 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1689 llvm::SmallVector<Expr*, 8> StrExpr;
1690 StrExpr.push_back(Exp->getString());
1691 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1692 &StrExpr[0], StrExpr.size());
1693 // cast to NSConstantString *
1694 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001695 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001696 delete Exp;
1697 return cast;
1698#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001699 assert(ConstantStringClassReference && "Can't find constant string reference");
1700 llvm::SmallVector<Expr*, 4> InitExprs;
1701
1702 // Synthesize "(Class)&_NSConstantStringClassReference"
1703 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1704 ConstantStringClassReference->getType(),
1705 SourceLocation());
1706 QualType expType = Context->getPointerType(ClsRef->getType());
1707 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1708 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001709 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001710 SourceLocation());
1711 InitExprs.push_back(cast); // set the 'isa'.
1712 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1713 unsigned IntSize = static_cast<unsigned>(
1714 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1715 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1716 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1717 Exp->getLocStart());
1718 InitExprs.push_back(len); // set "int numBytes".
1719
1720 // struct NSConstantString
1721 QualType CFConstantStrType = Context->getCFConstantStringType();
1722 // (struct NSConstantString) { <exprs from above> }
1723 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1724 &InitExprs[0], InitExprs.size(),
1725 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001726 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001727 // struct NSConstantString *
1728 expType = Context->getPointerType(StrRep->getType());
1729 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1730 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001731 // cast to NSConstantString *
1732 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001733 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001734 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001735 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001736#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001737}
1738
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001740 // check if we are sending a message to 'super'
1741 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001742 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1743 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1744 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1745 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001746 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001747 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001748 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001749 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001750 if (ObjCInterfaceType *IT =
1751 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001752 if (IT->getDecl() ==
1753 CurMethodDecl->getClassInterface()->getSuperClass())
1754 return IT->getDecl();
1755 }
1756 }
1757 }
1758 }
1759 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001760 }
Steve Naroff874e2322007-11-15 10:28:18 +00001761 }
1762 return 0;
1763}
1764
1765// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1766QualType RewriteTest::getSuperStructType() {
1767 if (!SuperStructDecl) {
1768 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1769 &Context->Idents.get("objc_super"), 0);
1770 QualType FieldTypes[2];
1771
1772 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001773 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001774 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001775 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001776 // Create fields
1777 FieldDecl *FieldDecls[2];
1778
1779 for (unsigned i = 0; i < 2; ++i)
1780 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1781
1782 SuperStructDecl->defineBody(FieldDecls, 4);
1783 }
1784 return Context->getTagDeclType(SuperStructDecl);
1785}
1786
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001787Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001788 if (!SelGetUidFunctionDecl)
1789 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001790 if (!MsgSendFunctionDecl)
1791 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001792 if (!MsgSendSuperFunctionDecl)
1793 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001794 if (!MsgSendStretFunctionDecl)
1795 SynthMsgSendStretFunctionDecl();
1796 if (!MsgSendSuperStretFunctionDecl)
1797 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001798 if (!MsgSendFpretFunctionDecl)
1799 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001800 if (!GetClassFunctionDecl)
1801 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001802 if (!GetMetaClassFunctionDecl)
1803 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001804
Steve Naroff874e2322007-11-15 10:28:18 +00001805 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001806 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1807 // May need to use objc_msgSend_stret() as well.
1808 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001809 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001810 QualType resultType = mDecl->getResultType();
1811 if (resultType.getCanonicalType()->isStructureType()
1812 || resultType.getCanonicalType()->isUnionType())
1813 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001814 else if (resultType.getCanonicalType()->isRealFloatingType())
1815 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001816 }
Steve Naroff874e2322007-11-15 10:28:18 +00001817
Steve Naroff934f2762007-10-24 22:48:43 +00001818 // Synthesize a call to objc_msgSend().
1819 llvm::SmallVector<Expr*, 8> MsgExprs;
1820 IdentifierInfo *clsName = Exp->getClassName();
1821
1822 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1823 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001824 if (!strcmp(clsName->getName(), "super")) {
1825 MsgSendFlavor = MsgSendSuperFunctionDecl;
1826 if (MsgSendStretFlavor)
1827 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1828 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1829
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001830 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001831 CurMethodDecl->getClassInterface()->getSuperClass();
1832
1833 llvm::SmallVector<Expr*, 4> InitExprs;
1834
1835 // set the receiver to self, the first argument to all methods.
1836 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001837 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001838 SourceLocation()));
1839 llvm::SmallVector<Expr*, 8> ClsExprs;
1840 QualType argType = Context->getPointerType(Context->CharTy);
1841 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1842 SuperDecl->getIdentifier()->getLength(),
1843 false, argType, SourceLocation(),
1844 SourceLocation()));
1845 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1846 &ClsExprs[0],
1847 ClsExprs.size());
1848 // To turn off a warning, type-cast to 'id'
1849 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001850 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001851 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1852 // struct objc_super
1853 QualType superType = getSuperStructType();
1854 // (struct objc_super) { <exprs from above> }
1855 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1856 &InitExprs[0], InitExprs.size(),
1857 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001858 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001859 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001860 // struct objc_super *
1861 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1862 Context->getPointerType(SuperRep->getType()),
1863 SourceLocation());
1864 MsgExprs.push_back(Unop);
1865 } else {
1866 llvm::SmallVector<Expr*, 8> ClsExprs;
1867 QualType argType = Context->getPointerType(Context->CharTy);
1868 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1869 clsName->getLength(),
1870 false, argType, SourceLocation(),
1871 SourceLocation()));
1872 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1873 &ClsExprs[0],
1874 ClsExprs.size());
1875 MsgExprs.push_back(Cls);
1876 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001877 } else { // instance message.
1878 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001879
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001880 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001881 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001882 if (MsgSendStretFlavor)
1883 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001884 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1885
1886 llvm::SmallVector<Expr*, 4> InitExprs;
1887
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001888 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001889 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001890 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001891
1892 llvm::SmallVector<Expr*, 8> ClsExprs;
1893 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001894 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1895 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001896 false, argType, SourceLocation(),
1897 SourceLocation()));
1898 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001899 &ClsExprs[0],
1900 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001901 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001902 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001903 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001904 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001905 // struct objc_super
1906 QualType superType = getSuperStructType();
1907 // (struct objc_super) { <exprs from above> }
1908 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1909 &InitExprs[0], InitExprs.size(),
1910 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001911 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001912 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001913 // struct objc_super *
1914 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1915 Context->getPointerType(SuperRep->getType()),
1916 SourceLocation());
1917 MsgExprs.push_back(Unop);
1918 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001919 // Remove all type-casts because it may contain objc-style types; e.g.
1920 // Foo<Proto> *.
1921 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1922 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001923 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001924 MsgExprs.push_back(recExpr);
1925 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001926 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001927 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001928 llvm::SmallVector<Expr*, 8> SelExprs;
1929 QualType argType = Context->getPointerType(Context->CharTy);
1930 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1931 Exp->getSelector().getName().size(),
1932 false, argType, SourceLocation(),
1933 SourceLocation()));
1934 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1935 &SelExprs[0], SelExprs.size());
1936 MsgExprs.push_back(SelExp);
1937
1938 // Now push any user supplied arguments.
1939 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001940 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001941 // Make all implicit casts explicit...ICE comes in handy:-)
1942 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1943 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1945 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001946 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001947 }
1948 // Make id<P...> cast into an 'id' cast.
1949 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001950 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001951 while ((CE = dyn_cast<CastExpr>(userExpr)))
1952 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001953 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001954 userExpr, SourceLocation());
1955 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001956 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001957 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001958 // We've transferred the ownership to MsgExprs. Null out the argument in
1959 // the original expression, since we will delete it below.
1960 Exp->setArg(i, 0);
1961 }
Steve Naroffab972d32007-11-04 22:37:50 +00001962 // Generate the funky cast.
1963 CastExpr *cast;
1964 llvm::SmallVector<QualType, 8> ArgTypes;
1965 QualType returnType;
1966
1967 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001968 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1969 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1970 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001971 ArgTypes.push_back(Context->getObjCIdType());
1972 ArgTypes.push_back(Context->getObjCSelType());
1973 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001974 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001975 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1977 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001978 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001979 ArgTypes.push_back(t);
1980 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001981 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1982 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001983 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001985 }
1986 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001987 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001988
1989 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001990 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1991 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001992
1993 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1994 // If we don't do this cast, we get the following bizarre warning/note:
1995 // xx.m:13: warning: function called through a non-compatible type
1996 // xx.m:13: note: if this code is reached, the program will abort
1997 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1998 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001999
Steve Naroffab972d32007-11-04 22:37:50 +00002000 // Now do the "normal" pointer to function cast.
2001 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002002 &ArgTypes[0], ArgTypes.size(),
2003 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002004 castType = Context->getPointerType(castType);
2005 cast = new CastExpr(castType, cast, SourceLocation());
2006
2007 // Don't forget the parens to enforce the proper binding.
2008 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2009
2010 const FunctionType *FT = msgSendType->getAsFunctionType();
2011 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2012 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002013 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002014 if (MsgSendStretFlavor) {
2015 // We have the method which returns a struct/union. Must also generate
2016 // call to objc_msgSend_stret and hang both varieties on a conditional
2017 // expression which dictate which one to envoke depending on size of
2018 // method's return type.
2019
2020 // Create a reference to the objc_msgSend_stret() declaration.
2021 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2022 SourceLocation());
2023 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2024 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2025 SourceLocation());
2026 // Now do the "normal" pointer to function cast.
2027 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002028 &ArgTypes[0], ArgTypes.size(),
2029 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002030 castType = Context->getPointerType(castType);
2031 cast = new CastExpr(castType, cast, SourceLocation());
2032
2033 // Don't forget the parens to enforce the proper binding.
2034 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2035
2036 FT = msgSendType->getAsFunctionType();
2037 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2038 FT->getResultType(), SourceLocation());
2039
2040 // Build sizeof(returnType)
2041 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2042 returnType, Context->getSizeType(),
2043 SourceLocation(), SourceLocation());
2044 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2045 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2046 // For X86 it is more complicated and some kind of target specific routine
2047 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002048 unsigned IntSize =
2049 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2051 Context->IntTy,
2052 SourceLocation());
2053 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2054 BinaryOperator::LE,
2055 Context->IntTy,
2056 SourceLocation());
2057 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2058 ConditionalOperator *CondExpr =
2059 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002060 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002062 return ReplacingStmt;
2063}
2064
2065Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2066 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002067 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002068 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002069
Chris Lattnere64b7772007-10-24 16:57:36 +00002070 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002071 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002072}
2073
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002074/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2075/// call to objc_getProtocol("proto-name").
2076Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2077 if (!GetProtocolFunctionDecl)
2078 SynthGetProtocolFunctionDecl();
2079 // Create a call to objc_getProtocol("ProtocolName").
2080 llvm::SmallVector<Expr*, 8> ProtoExprs;
2081 QualType argType = Context->getPointerType(Context->CharTy);
2082 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2083 strlen(Exp->getProtocol()->getName()),
2084 false, argType, SourceLocation(),
2085 SourceLocation()));
2086 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2087 &ProtoExprs[0],
2088 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002089 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002090 delete Exp;
2091 return ProtoExp;
2092
2093}
2094
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002096/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002098 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2100 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002101 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002102 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002103 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002104 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002105 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002106 SourceLocation LocStart = CDecl->getLocStart();
2107 SourceLocation LocEnd = CDecl->getLocEnd();
2108
2109 const char *startBuf = SM->getCharacterData(LocStart);
2110 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002111 // If no ivars and no root or if its root, directly or indirectly,
2112 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002113 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002114 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002115 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002116 return;
2117 }
2118
2119 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002120 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002121 Result += "\nstruct ";
2122 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002123
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002124 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002125 const char *cursor = strchr(startBuf, '{');
2126 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002127 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002128
2129 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002130 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002132 Result = "\n struct ";
2133 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002134 // Note: We don't name the field decl. This simplifies the "codegen" for
2135 // accessing a superclasses instance variables (and is similar to what gcc
2136 // does internally). The unnamed struct field feature is enabled with
2137 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2138 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002139 Result += ";\n";
2140
2141 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002142 SourceLocation OnePastCurly =
2143 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2144 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002145 }
2146 cursor++; // past '{'
2147
2148 // Now comment out any visibility specifiers.
2149 while (cursor < endBuf) {
2150 if (*cursor == '@') {
2151 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002152 // Skip whitespace.
2153 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2154 /*scan*/;
2155
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002156 // FIXME: presence of @public, etc. inside comment results in
2157 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002158 if (!strncmp(cursor, "public", strlen("public")) ||
2159 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002160 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002161 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002162 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002163 // FIXME: If there are cases where '<' is used in ivar declaration part
2164 // of user code, then scan the ivar list and use needToScanForQualifiers
2165 // for type checking.
2166 else if (*cursor == '<') {
2167 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002168 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002169 cursor = strchr(cursor, '>');
2170 cursor++;
2171 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002172 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002173 }
Steve Narofffea763e82007-11-14 19:25:57 +00002174 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002175 }
Steve Narofffea763e82007-11-14 19:25:57 +00002176 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002177 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002178 } else { // we don't have any instance variables - insert super struct.
2179 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2180 Result += " {\n struct ";
2181 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002182 // Note: We don't name the field decl. This simplifies the "codegen" for
2183 // accessing a superclasses instance variables (and is similar to what gcc
2184 // does internally). The unnamed struct field feature is enabled with
2185 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2186 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002187 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002188 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002189 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002190 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002191 if (!ObjCSynthesizedStructs.insert(CDecl))
2192 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002193}
2194
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002196/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002198 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002199 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002200 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002201 const char *ClassName,
2202 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002203 if (MethodBegin == MethodEnd) return;
2204
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002205 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002206 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002207 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002208 SEL _cmd;
2209 char *method_types;
2210 void *_imp;
2211 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002212 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002213 Result += "\nstruct _objc_method {\n";
2214 Result += "\tSEL _cmd;\n";
2215 Result += "\tchar *method_types;\n";
2216 Result += "\tvoid *_imp;\n";
2217 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002218
2219 /* struct _objc_method_list {
2220 struct _objc_method_list *next_method;
2221 int method_count;
2222 struct _objc_method method_list[];
2223 }
2224 */
2225 Result += "\nstruct _objc_method_list {\n";
2226 Result += "\tstruct _objc_method_list *next_method;\n";
2227 Result += "\tint method_count;\n";
2228 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002229 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002230 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002231
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002232 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002233 Result += "\nstatic struct _objc_method_list _OBJC_";
2234 Result += prefix;
2235 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2236 Result += "_METHODS_";
2237 Result += ClassName;
2238 Result += " __attribute__ ((section (\"__OBJC, __";
2239 Result += IsInstanceMethod ? "inst" : "cls";
2240 Result += "_meth\")))= ";
2241 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002242
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002243 Result += "\t,{{(SEL)\"";
2244 Result += (*MethodBegin)->getSelector().getName().c_str();
2245 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002246 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002247 Result += "\", \"";
2248 Result += MethodTypeString;
2249 Result += "\", ";
2250 Result += MethodInternalNames[*MethodBegin];
2251 Result += "}\n";
2252 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2253 Result += "\t ,{(SEL)\"";
2254 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002255 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002256 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002257 Result += "\", \"";
2258 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002259 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002260 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002261 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002262 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002263 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002264}
2265
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002266/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2267void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002268 int NumProtocols,
2269 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002270 const char *ClassName,
2271 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002272 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002273 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002274 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002275 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002276 // Output struct protocol_methods holder of method selector and type.
2277 if (!objc_protocol_methods &&
2278 (PDecl->getNumInstanceMethods() > 0
2279 || PDecl->getNumClassMethods() > 0)) {
2280 /* struct protocol_methods {
2281 SEL _cmd;
2282 char *method_types;
2283 }
2284 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002285 Result += "\nstruct protocol_methods {\n";
2286 Result += "\tSEL _cmd;\n";
2287 Result += "\tchar *method_types;\n";
2288 Result += "};\n";
2289
2290 /* struct _objc_protocol_method_list {
2291 int protocol_method_count;
2292 struct protocol_methods protocols[];
2293 }
2294 */
2295 Result += "\nstruct _objc_protocol_method_list {\n";
2296 Result += "\tint protocol_method_count;\n";
2297 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002298 objc_protocol_methods = true;
2299 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002300
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002301 int NumMethods = PDecl->getNumInstanceMethods();
2302 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002303 Result += "\nstatic struct _objc_protocol_method_list "
2304 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2305 Result += PDecl->getName();
2306 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2307 "{\n\t" + utostr(NumMethods) + "\n";
2308
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002309 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002310 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002311 E = PDecl->instmeth_end(); I != E; ++I) {
2312 if (I == PDecl->instmeth_begin())
2313 Result += "\t ,{{(SEL)\"";
2314 else
2315 Result += "\t ,{(SEL)\"";
2316 Result += (*I)->getSelector().getName().c_str();
2317 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002318 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002319 Result += "\", \"";
2320 Result += MethodTypeString;
2321 Result += "\"}\n";
2322 }
2323 Result += "\t }\n};\n";
2324 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002325
2326 // Output class methods declared in this protocol.
2327 NumMethods = PDecl->getNumClassMethods();
2328 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002329 Result += "\nstatic struct _objc_protocol_method_list "
2330 "_OBJC_PROTOCOL_CLASS_METHODS_";
2331 Result += PDecl->getName();
2332 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2333 "{\n\t";
2334 Result += utostr(NumMethods);
2335 Result += "\n";
2336
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002337 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002338 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002339 E = PDecl->classmeth_end(); I != E; ++I) {
2340 if (I == PDecl->classmeth_begin())
2341 Result += "\t ,{{(SEL)\"";
2342 else
2343 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002344 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002345 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002346 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002347 Result += "\", \"";
2348 Result += MethodTypeString;
2349 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002350 }
2351 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002352 }
2353 // Output:
2354 /* struct _objc_protocol {
2355 // Objective-C 1.0 extensions
2356 struct _objc_protocol_extension *isa;
2357 char *protocol_name;
2358 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002359 struct _objc_protocol_method_list *instance_methods;
2360 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002361 };
2362 */
2363 static bool objc_protocol = false;
2364 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002365 Result += "\nstruct _objc_protocol {\n";
2366 Result += "\tstruct _objc_protocol_extension *isa;\n";
2367 Result += "\tchar *protocol_name;\n";
2368 Result += "\tstruct _objc_protocol **protocol_list;\n";
2369 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2370 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2371 Result += "};\n";
2372
2373 /* struct _objc_protocol_list {
2374 struct _objc_protocol_list *next;
2375 int protocol_count;
2376 struct _objc_protocol *class_protocols[];
2377 }
2378 */
2379 Result += "\nstruct _objc_protocol_list {\n";
2380 Result += "\tstruct _objc_protocol_list *next;\n";
2381 Result += "\tint protocol_count;\n";
2382 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2383 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002384 objc_protocol = true;
2385 }
2386
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002387 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2388 Result += PDecl->getName();
2389 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2390 "{\n\t0, \"";
2391 Result += PDecl->getName();
2392 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002393 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002394 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2395 Result += PDecl->getName();
2396 Result += ", ";
2397 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002398 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002399 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002400 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002401 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2402 Result += PDecl->getName();
2403 Result += "\n";
2404 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002405 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002406 Result += "0\n";
2407 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002408 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002409 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002410 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2411 Result += prefix;
2412 Result += "_PROTOCOLS_";
2413 Result += ClassName;
2414 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2415 "{\n\t0, ";
2416 Result += utostr(NumProtocols);
2417 Result += "\n";
2418
2419 Result += "\t,{&_OBJC_PROTOCOL_";
2420 Result += Protocols[0]->getName();
2421 Result += " \n";
2422
2423 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002425 Result += "\t ,&_OBJC_PROTOCOL_";
2426 Result += PDecl->getName();
2427 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002428 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002430 }
2431}
2432
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002434/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002436 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002438 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002439 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002440 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2441 CDecl = CDecl->getNextClassCategory())
2442 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2443 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002444
Chris Lattnereb44eee2007-12-23 01:40:15 +00002445 std::string FullCategoryName = ClassDecl->getName();
2446 FullCategoryName += '_';
2447 FullCategoryName += IDecl->getName();
2448
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002449 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002450 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002451 true, "CATEGORY_", FullCategoryName.c_str(),
2452 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002453
2454 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002456 false, "CATEGORY_", FullCategoryName.c_str(),
2457 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002458
2459 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002460 // Null CDecl is case of a category implementation with no category interface
2461 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002463 CDecl->getNumReferencedProtocols(),
2464 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002465 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002466
2467 /* struct _objc_category {
2468 char *category_name;
2469 char *class_name;
2470 struct _objc_method_list *instance_methods;
2471 struct _objc_method_list *class_methods;
2472 struct _objc_protocol_list *protocols;
2473 // Objective-C 1.0 extensions
2474 uint32_t size; // sizeof (struct _objc_category)
2475 struct _objc_property_list *instance_properties; // category's own
2476 // @property decl.
2477 };
2478 */
2479
2480 static bool objc_category = false;
2481 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482 Result += "\nstruct _objc_category {\n";
2483 Result += "\tchar *category_name;\n";
2484 Result += "\tchar *class_name;\n";
2485 Result += "\tstruct _objc_method_list *instance_methods;\n";
2486 Result += "\tstruct _objc_method_list *class_methods;\n";
2487 Result += "\tstruct _objc_protocol_list *protocols;\n";
2488 Result += "\tunsigned int size;\n";
2489 Result += "\tstruct _objc_property_list *instance_properties;\n";
2490 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002491 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002492 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2494 Result += FullCategoryName;
2495 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2496 Result += IDecl->getName();
2497 Result += "\"\n\t, \"";
2498 Result += ClassDecl->getName();
2499 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002500
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002501 if (IDecl->getNumInstanceMethods() > 0) {
2502 Result += "\t, (struct _objc_method_list *)"
2503 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2504 Result += FullCategoryName;
2505 Result += "\n";
2506 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002507 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002508 Result += "\t, 0\n";
2509 if (IDecl->getNumClassMethods() > 0) {
2510 Result += "\t, (struct _objc_method_list *)"
2511 "&_OBJC_CATEGORY_CLASS_METHODS_";
2512 Result += FullCategoryName;
2513 Result += "\n";
2514 }
2515 else
2516 Result += "\t, 0\n";
2517
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002518 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002519 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2520 Result += FullCategoryName;
2521 Result += "\n";
2522 }
2523 else
2524 Result += "\t, 0\n";
2525 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002526}
2527
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002528/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2529/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002530void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2531 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002532 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002533 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002534 Result += IDecl->getName();
2535 Result += ", ";
2536 Result += ivar->getName();
2537 Result += ")";
2538}
2539
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540//===----------------------------------------------------------------------===//
2541// Meta Data Emission
2542//===----------------------------------------------------------------------===//
2543
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002544void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002545 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002547
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002548 // Explictly declared @interface's are already synthesized.
2549 if (CDecl->ImplicitInterfaceDecl()) {
2550 // FIXME: Implementation of a class with no @interface (legacy) doese not
2551 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002552 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002553 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002554
Chris Lattnerbe6df082007-12-12 07:56:42 +00002555 // Build _objc_ivar_list metadata for classes ivars if needed
2556 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2557 ? IDecl->getImplDeclNumIvars()
2558 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002559 if (NumIvars > 0) {
2560 static bool objc_ivar = false;
2561 if (!objc_ivar) {
2562 /* struct _objc_ivar {
2563 char *ivar_name;
2564 char *ivar_type;
2565 int ivar_offset;
2566 };
2567 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002568 Result += "\nstruct _objc_ivar {\n";
2569 Result += "\tchar *ivar_name;\n";
2570 Result += "\tchar *ivar_type;\n";
2571 Result += "\tint ivar_offset;\n";
2572 Result += "};\n";
2573
2574 /* struct _objc_ivar_list {
2575 int ivar_count;
2576 struct _objc_ivar ivar_list[];
2577 };
2578 */
2579 Result += "\nstruct _objc_ivar_list {\n";
2580 Result += "\tint ivar_count;\n";
2581 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002582 objc_ivar = true;
2583 }
2584
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002585 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2586 Result += IDecl->getName();
2587 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2588 "{\n\t";
2589 Result += utostr(NumIvars);
2590 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002591
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002593 if (IDecl->getImplDeclNumIvars() > 0) {
2594 IVI = IDecl->ivar_begin();
2595 IVE = IDecl->ivar_end();
2596 } else {
2597 IVI = CDecl->ivar_begin();
2598 IVE = CDecl->ivar_end();
2599 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002600 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002601 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002602 Result += "\", \"";
2603 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002604 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2605 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002606 Result += StrEncoding;
2607 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002608 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002609 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002610 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002611 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002612 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002613 Result += "\", \"";
2614 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002615 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2616 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002617 Result += StrEncoding;
2618 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002619 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002620 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002621 }
2622
2623 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002624 }
2625
2626 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002628 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002629
2630 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002631 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002632 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002633
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002634 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002635 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002636 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002637 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002638
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002639
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002640 // Declaration of class/meta-class metadata
2641 /* struct _objc_class {
2642 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002643 const char *super_class_name;
2644 char *name;
2645 long version;
2646 long info;
2647 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002648 struct _objc_ivar_list *ivars;
2649 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002650 struct objc_cache *cache;
2651 struct objc_protocol_list *protocols;
2652 const char *ivar_layout;
2653 struct _objc_class_ext *ext;
2654 };
2655 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002656 static bool objc_class = false;
2657 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002658 Result += "\nstruct _objc_class {\n";
2659 Result += "\tstruct _objc_class *isa;\n";
2660 Result += "\tconst char *super_class_name;\n";
2661 Result += "\tchar *name;\n";
2662 Result += "\tlong version;\n";
2663 Result += "\tlong info;\n";
2664 Result += "\tlong instance_size;\n";
2665 Result += "\tstruct _objc_ivar_list *ivars;\n";
2666 Result += "\tstruct _objc_method_list *methods;\n";
2667 Result += "\tstruct objc_cache *cache;\n";
2668 Result += "\tstruct _objc_protocol_list *protocols;\n";
2669 Result += "\tconst char *ivar_layout;\n";
2670 Result += "\tstruct _objc_class_ext *ext;\n";
2671 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002672 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002673 }
2674
2675 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002676 ObjCInterfaceDecl *RootClass = 0;
2677 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002678 while (SuperClass) {
2679 RootClass = SuperClass;
2680 SuperClass = SuperClass->getSuperClass();
2681 }
2682 SuperClass = CDecl->getSuperClass();
2683
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002684 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2685 Result += CDecl->getName();
2686 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2687 "{\n\t(struct _objc_class *)\"";
2688 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2689 Result += "\"";
2690
2691 if (SuperClass) {
2692 Result += ", \"";
2693 Result += SuperClass->getName();
2694 Result += "\", \"";
2695 Result += CDecl->getName();
2696 Result += "\"";
2697 }
2698 else {
2699 Result += ", 0, \"";
2700 Result += CDecl->getName();
2701 Result += "\"";
2702 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002703 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002704 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002705 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002706 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002707 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002708 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002709 Result += "\n";
2710 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002711 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002712 Result += ", 0\n";
2713 if (CDecl->getNumIntfRefProtocols() > 0) {
2714 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2715 Result += CDecl->getName();
2716 Result += ",0,0\n";
2717 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002718 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002719 Result += "\t,0,0,0,0\n";
2720 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002721
2722 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002723 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2724 Result += CDecl->getName();
2725 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2726 "{\n\t&_OBJC_METACLASS_";
2727 Result += CDecl->getName();
2728 if (SuperClass) {
2729 Result += ", \"";
2730 Result += SuperClass->getName();
2731 Result += "\", \"";
2732 Result += CDecl->getName();
2733 Result += "\"";
2734 }
2735 else {
2736 Result += ", 0, \"";
2737 Result += CDecl->getName();
2738 Result += "\"";
2739 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002740 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002741 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002742 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002743 Result += ",0";
2744 else {
2745 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002746 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002747 Result += CDecl->getName();
2748 Result += ")";
2749 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002750 if (NumIvars > 0) {
2751 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2752 Result += CDecl->getName();
2753 Result += "\n\t";
2754 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002755 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002756 Result += ",0";
2757 if (IDecl->getNumInstanceMethods() > 0) {
2758 Result += ", &_OBJC_INSTANCE_METHODS_";
2759 Result += CDecl->getName();
2760 Result += ", 0\n\t";
2761 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002762 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += ",0,0";
2764 if (CDecl->getNumIntfRefProtocols() > 0) {
2765 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2766 Result += CDecl->getName();
2767 Result += ", 0,0\n";
2768 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002769 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002770 Result += ",0,0,0\n";
2771 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002772}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002773
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002774/// RewriteImplementations - This routine rewrites all method implementations
2775/// and emits meta-data.
2776
2777void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002778 int ClsDefCount = ClassImplementation.size();
2779 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002780
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002781 if (ClsDefCount == 0 && CatDefCount == 0)
2782 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002783 // Rewrite implemented methods
2784 for (int i = 0; i < ClsDefCount; i++)
2785 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002786
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002787 for (int i = 0; i < CatDefCount; i++)
2788 RewriteImplementationDecl(CategoryImplementation[i]);
2789
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002790 // This is needed for use of offsetof
2791 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002792
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002793 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002794 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002795 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002796
2797 // For each implemented category, write out all its meta data.
2798 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002799 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002800
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002801 // Write objc_symtab metadata
2802 /*
2803 struct _objc_symtab
2804 {
2805 long sel_ref_cnt;
2806 SEL *refs;
2807 short cls_def_cnt;
2808 short cat_def_cnt;
2809 void *defs[cls_def_cnt + cat_def_cnt];
2810 };
2811 */
2812
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002813 Result += "\nstruct _objc_symtab {\n";
2814 Result += "\tlong sel_ref_cnt;\n";
2815 Result += "\tSEL *refs;\n";
2816 Result += "\tshort cls_def_cnt;\n";
2817 Result += "\tshort cat_def_cnt;\n";
2818 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2819 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002820
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002821 Result += "static struct _objc_symtab "
2822 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2823 Result += "\t0, 0, " + utostr(ClsDefCount)
2824 + ", " + utostr(CatDefCount) + "\n";
2825 for (int i = 0; i < ClsDefCount; i++) {
2826 Result += "\t,&_OBJC_CLASS_";
2827 Result += ClassImplementation[i]->getName();
2828 Result += "\n";
2829 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002830
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002831 for (int i = 0; i < CatDefCount; i++) {
2832 Result += "\t,&_OBJC_CATEGORY_";
2833 Result += CategoryImplementation[i]->getClassInterface()->getName();
2834 Result += "_";
2835 Result += CategoryImplementation[i]->getName();
2836 Result += "\n";
2837 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002838
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002840
2841 // Write objc_module metadata
2842
2843 /*
2844 struct _objc_module {
2845 long version;
2846 long size;
2847 const char *name;
2848 struct _objc_symtab *symtab;
2849 }
2850 */
2851
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002852 Result += "\nstruct _objc_module {\n";
2853 Result += "\tlong version;\n";
2854 Result += "\tlong size;\n";
2855 Result += "\tconst char *name;\n";
2856 Result += "\tstruct _objc_symtab *symtab;\n";
2857 Result += "};\n\n";
2858 Result += "static struct _objc_module "
2859 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002860 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2861 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002862 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002863
2864 if (LangOpts.Microsoft) {
2865 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2866 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2867 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2868 Result += "&_OBJC_MODULES;\n";
2869 Result += "#pragma data_seg(pop)\n\n";
2870 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002871}
Chris Lattner311ff022007-10-16 22:36:42 +00002872