blob: 178cf4e4cf9f8be5067bdd6932c0a61f8efbe321 [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 Narofff69cc5d2008-01-30 19:17:43 +000038 unsigned RewriteFailedDiag;
39
Chris Lattner01c57482007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000041 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000042 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000045 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
46 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
47 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
49 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000050 llvm::SmallVector<Stmt *, 32> Stmts;
51 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000052 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000053
54 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000055 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056 FunctionDecl *MsgSendStretFunctionDecl;
57 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000058 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000059 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000060 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000061 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000062 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000063 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064
Steve Naroffbeaf2992007-11-03 11:27:19 +000065 // ObjC string constant support.
66 FileVarDecl *ConstantStringClassReference;
67 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000068
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000069 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000070 int BcLabelCount;
71
Steve Naroff874e2322007-11-15 10:28:18 +000072 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000074 RecordDecl *SuperStructDecl;
75
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000076 // Needed for header files being rewritten
77 bool IsHeader;
78
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000079 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000080 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000081 void Initialize(ASTContext &context);
82
Chris Lattner8a12c272007-10-11 18:38:32 +000083
Chris Lattnerf04da132007-10-24 17:06:59 +000084 // Top Level Driver code.
85 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void HandleDeclInMainFile(Decl *D);
Steve Naroff0113c9d2008-01-28 21:34:52 +000087 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000088 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000089 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
90 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000091 }
Chris Lattnerf04da132007-10-24 17:06:59 +000092 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000093
94 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000095 // If replacement succeeded or warning disabled return with no warning.
96 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000097 return;
98
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000099 SourceRange Range = Old->getSourceRange();
100 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
101 0, 0, &Range, 1);
102 }
103
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000104 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000105 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000106 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
107 SilenceRewriteMacroWarning)
108 return;
109
110 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
111 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112
Chris Lattneraadaf782008-01-31 19:51:04 +0000113 void RemoveText(SourceLocation Loc, unsigned StrLen) {
114 // If removal succeeded or warning disabled return with no warning.
115 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
116 return;
117
118 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
119 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000120
Chris Lattneraadaf782008-01-31 19:51:04 +0000121 void ReplaceText(SourceLocation Start, unsigned OrigLength,
122 const char *NewStr, unsigned NewLength) {
123 // If removal succeeded or warning disabled return with no warning.
124 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
125 SilenceRewriteMacroWarning)
126 return;
127
128 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
129 }
130
Chris Lattnerf04da132007-10-24 17:06:59 +0000131 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000132 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000133 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000135 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
136 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000137 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000138 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
139 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
140 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
141 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
142 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
143 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000144 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000145 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000146 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000147 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000148 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000149
Chris Lattnerf04da132007-10-24 17:06:59 +0000150 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000151 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000152 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000153 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000154 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000155 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000156 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000157 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000159 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
161 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
162 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000163 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
164 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000165 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
166 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000167 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000168 Stmt *RewriteBreakStmt(BreakStmt *S);
169 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000170 void SynthCountByEnumWithState(std::string &buf);
171
Steve Naroff09b266e2007-10-30 23:14:51 +0000172 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000173 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000174 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000175 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000176 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000177 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000178 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000180 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000181 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000182
Chris Lattnerf04da132007-10-24 17:06:59 +0000183 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000188 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000189
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
191 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000192 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000193 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000195 const char *ClassName,
196 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000197
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000199 int NumProtocols,
200 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000201 const char *ClassName,
202 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000203 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000204 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
206 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000207 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000208 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000209 };
210}
211
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000212static bool IsHeaderFile(const std::string &Filename) {
213 std::string::size_type DotPos = Filename.rfind('.');
214
215 if (DotPos == std::string::npos) {
216 // no file extension
217 return false;
218 }
219
220 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
221 // C header: .h
222 // C++ header: .hh or .H;
223 return Ext == "h" || Ext == "hh" || Ext == "H";
224}
225
226ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
227 Diagnostic &Diags) {
228 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattnere365c502007-11-30 22:25:36 +0000229}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000230
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000231void RewriteTest::Initialize(ASTContext &context) {
232 Context = &context;
233 SM = &Context->getSourceManager();
234 MsgSendFunctionDecl = 0;
235 MsgSendSuperFunctionDecl = 0;
236 MsgSendStretFunctionDecl = 0;
237 MsgSendSuperStretFunctionDecl = 0;
238 MsgSendFpretFunctionDecl = 0;
239 GetClassFunctionDecl = 0;
240 GetMetaClassFunctionDecl = 0;
241 SelGetUidFunctionDecl = 0;
242 CFStringFunctionDecl = 0;
243 GetProtocolFunctionDecl = 0;
244 ConstantStringClassReference = 0;
245 NSStringRecord = 0;
246 CurMethodDecl = 0;
247 SuperStructDecl = 0;
248 BcLabelCount = 0;
249
250 // Get the ID and start/end of the main file.
251 MainFileID = SM->getMainFileID();
252 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
253 MainFileStart = MainBuf->getBufferStart();
254 MainFileEnd = MainBuf->getBufferEnd();
255
256
257 Rewrite.setSourceMgr(Context->getSourceManager());
258 // declaring objc_selector outside the parameter list removes a silly
259 // scope related warning...
260 const char *s = "#pragma once\n"
261 "struct objc_selector; struct objc_class;\n"
262 "#ifndef OBJC_SUPER\n"
263 "struct objc_super { struct objc_object *o; "
264 "struct objc_object *superClass; };\n"
265 "#define OBJC_SUPER\n"
266 "#endif\n"
267 "#ifndef _REWRITER_typedef_Protocol\n"
268 "typedef struct objc_object Protocol;\n"
269 "#define _REWRITER_typedef_Protocol\n"
270 "#endif\n"
271 "extern struct objc_object *objc_msgSend"
272 "(struct objc_object *, struct objc_selector *, ...);\n"
273 "extern struct objc_object *objc_msgSendSuper"
274 "(struct objc_super *, struct objc_selector *, ...);\n"
275 "extern struct objc_object *objc_msgSend_stret"
276 "(struct objc_object *, struct objc_selector *, ...);\n"
277 "extern struct objc_object *objc_msgSendSuper_stret"
278 "(struct objc_super *, struct objc_selector *, ...);\n"
279 "extern struct objc_object *objc_msgSend_fpret"
280 "(struct objc_object *, struct objc_selector *, ...);\n"
281 "extern struct objc_object *objc_getClass"
282 "(const char *);\n"
283 "extern struct objc_object *objc_getMetaClass"
284 "(const char *);\n"
285 "extern void objc_exception_throw(struct objc_object *);\n"
286 "extern void objc_exception_try_enter(void *);\n"
287 "extern void objc_exception_try_exit(void *);\n"
288 "extern struct objc_object *objc_exception_extract(void *);\n"
289 "extern int objc_exception_match"
290 "(struct objc_class *, struct objc_object *, ...);\n"
291 "extern Protocol *objc_getProtocol(const char *);\n"
292 "#include <objc/objc.h>\n"
293 "#ifndef __FASTENUMERATIONSTATE\n"
294 "struct __objcFastEnumerationState {\n\t"
295 "unsigned long state;\n\t"
296 "id *itemsPtr;\n\t"
297 "unsigned long *mutationsPtr;\n\t"
298 "unsigned long extra[5];\n};\n"
299 "#define __FASTENUMERATIONSTATE\n"
300 "#endif\n";
301 if (IsHeader) {
302 // insert the whole string when rewriting a header file
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000303 InsertText(SourceLocation::getFileLoc(MainFileID, 0), s, strlen(s));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000304 }
305 else {
306 // Not rewriting header, exclude the #pragma once pragma
307 const char *p = s + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000308 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000309 }
310}
311
312
Chris Lattnerf04da132007-10-24 17:06:59 +0000313//===----------------------------------------------------------------------===//
314// Top Level Driver Code
315//===----------------------------------------------------------------------===//
316
Chris Lattner8a12c272007-10-11 18:38:32 +0000317void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000318 // Two cases: either the decl could be in the main file, or it could be in a
319 // #included file. If the former, rewrite it now. If the later, check to see
320 // if we rewrote the #include/#import.
321 SourceLocation Loc = D->getLocation();
322 Loc = SM->getLogicalLoc(Loc);
323
324 // If this is for a builtin, ignore it.
325 if (Loc.isInvalid()) return;
326
Steve Naroffebf2b562007-10-23 23:50:29 +0000327 // Look for built-in declarations that we need to refer during the rewrite.
328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000329 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000330 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
331 // declared in <Foundation/NSString.h>
332 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
333 ConstantStringClassReference = FVD;
334 return;
335 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000337 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000338 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000339 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000340 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000341 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000342 } else if (ObjCForwardProtocolDecl *FP =
343 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000344 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000345 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000346 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000347 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
348 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000349}
350
Chris Lattnerf04da132007-10-24 17:06:59 +0000351/// HandleDeclInMainFile - This is called for each top-level decl defined in the
352/// main file of the input.
353void RewriteTest::HandleDeclInMainFile(Decl *D) {
354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
355 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000356 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000357
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000358 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000359 if (Stmt *Body = MD->getBody()) {
360 //Body->dump();
361 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000362 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000363 CurMethodDecl = 0;
364 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000365 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000366 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000367 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000368 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000369 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000370 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000371 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000372 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000373 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000374 if (VD->getInit())
375 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
376 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000377 // Nothing yet.
378}
379
380RewriteTest::~RewriteTest() {
381 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000382
383 // Rewrite tabs if we care.
384 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000385
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000386 RewriteInclude();
387
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000388 // Rewrite Objective-c meta data*
389 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000390 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000391
Chris Lattnerf04da132007-10-24 17:06:59 +0000392 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
393 // we are done.
394 if (const RewriteBuffer *RewriteBuf =
395 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000396 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000397 std::string S(RewriteBuf->begin(), RewriteBuf->end());
398 printf("%s\n", S.c_str());
399 } else {
400 printf("No changes\n");
401 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000402 // Emit metadata.
403 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000404}
405
Chris Lattnerf04da132007-10-24 17:06:59 +0000406//===----------------------------------------------------------------------===//
407// Syntactic (non-AST) Rewriting Code
408//===----------------------------------------------------------------------===//
409
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000410void RewriteTest::RewriteInclude() {
411 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
412 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
413 const char *MainBufStart = MainBuf.first;
414 const char *MainBufEnd = MainBuf.second;
415 size_t ImportLen = strlen("import");
416 size_t IncludeLen = strlen("include");
417
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000418 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000419 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
420 if (*BufPtr == '#') {
421 if (++BufPtr == MainBufEnd)
422 return;
423 while (*BufPtr == ' ' || *BufPtr == '\t')
424 if (++BufPtr == MainBufEnd)
425 return;
426 if (!strncmp(BufPtr, "import", ImportLen)) {
427 // replace import with include
428 SourceLocation ImportLoc =
429 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000430 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000431 BufPtr += ImportLen;
432 }
433 }
434 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000435}
436
Chris Lattnerf04da132007-10-24 17:06:59 +0000437void RewriteTest::RewriteTabs() {
438 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
439 const char *MainBufStart = MainBuf.first;
440 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000441
Chris Lattnerf04da132007-10-24 17:06:59 +0000442 // Loop over the whole file, looking for tabs.
443 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
444 if (*BufPtr != '\t')
445 continue;
446
447 // Okay, we found a tab. This tab will turn into at least one character,
448 // but it depends on which 'virtual column' it is in. Compute that now.
449 unsigned VCol = 0;
450 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
451 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
452 ++VCol;
453
454 // Okay, now that we know the virtual column, we know how many spaces to
455 // insert. We assume 8-character tab-stops.
456 unsigned Spaces = 8-(VCol & 7);
457
458 // Get the location of the tab.
459 SourceLocation TabLoc =
460 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
461
462 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000463 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000464 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000465}
466
467
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000468void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000469 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000470 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000471
472 // Get the start location and compute the semi location.
473 SourceLocation startLoc = ClassDecl->getLocation();
474 const char *startBuf = SM->getCharacterData(startLoc);
475 const char *semiPtr = strchr(startBuf, ';');
476
477 // Translate to typedef's that forward reference structs with the same name
478 // as the class. As a convenience, we include the original declaration
479 // as a comment.
480 std::string typedefString;
481 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000482 typedefString.append(startBuf, semiPtr-startBuf+1);
483 typedefString += "\n";
484 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000485 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000486 typedefString += "#ifndef _REWRITER_typedef_";
487 typedefString += ForwardDecl->getName();
488 typedefString += "\n";
489 typedefString += "#define _REWRITER_typedef_";
490 typedefString += ForwardDecl->getName();
491 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000492 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000493 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000494 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000495 }
496
497 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000498 ReplaceText(startLoc, semiPtr-startBuf+1,
499 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000500}
501
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000503 SourceLocation LocStart = Method->getLocStart();
504 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000505
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000506 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000507 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000508 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000509 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000510 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000511 }
512}
513
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000515{
516 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000518 SourceLocation Loc = Property->getLocation();
519
Chris Lattneraadaf782008-01-31 19:51:04 +0000520 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000521
522 // FIXME: handle properties that are declared across multiple lines.
523 }
524}
525
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000527 SourceLocation LocStart = CatDecl->getLocStart();
528
529 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000530 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000531
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000532 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000533 E = CatDecl->instmeth_end(); I != E; ++I)
534 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000535 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000536 E = CatDecl->classmeth_end(); I != E; ++I)
537 RewriteMethodDeclaration(*I);
538
Steve Naroff423cb562007-10-30 13:30:57 +0000539 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000540 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000541}
542
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000544 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000545
Steve Naroff752d6ef2007-10-30 16:42:30 +0000546 SourceLocation LocStart = PDecl->getLocStart();
547
548 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000549 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000550
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000551 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000552 E = PDecl->instmeth_end(); I != E; ++I)
553 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000555 E = PDecl->classmeth_end(); I != E; ++I)
556 RewriteMethodDeclaration(*I);
557
Steve Naroff752d6ef2007-10-30 16:42:30 +0000558 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000559 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000560 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000561
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000562 // Must comment out @optional/@required
563 const char *startBuf = SM->getCharacterData(LocStart);
564 const char *endBuf = SM->getCharacterData(LocEnd);
565 for (const char *p = startBuf; p < endBuf; p++) {
566 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
567 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000568 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000569 ReplaceText(OptionalLoc, strlen("@optional"),
570 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000571
572 }
573 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
574 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000575 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000576 ReplaceText(OptionalLoc, strlen("@required"),
577 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000578
579 }
580 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000581}
582
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000584 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000585 if (LocStart.isInvalid())
586 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000587 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000589}
590
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000592 std::string &ResultStr) {
593 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000594 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000595 ResultStr += "id";
596 else
597 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000598 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000599
600 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000601 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000602
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000603 if (OMD->isInstance())
604 NameStr += "_I_";
605 else
606 NameStr += "_C_";
607
608 NameStr += OMD->getClassInterface()->getName();
609 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000610
611 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612 if (ObjCCategoryImplDecl *CID =
613 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000614 NameStr += CID->getName();
615 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000616 }
617 // Append selector names, replacing ':' with '_'
618 const char *selName = OMD->getSelector().getName().c_str();
619 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000620 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000621 else {
622 std::string selString = OMD->getSelector().getName();
623 int len = selString.size();
624 for (int i = 0; i < len; i++)
625 if (selString[i] == ':')
626 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000627 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000628 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000629 // Remember this name for metadata emission
630 MethodInternalNames[OMD] = NameStr;
631 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000632
633 // Rewrite arguments
634 ResultStr += "(";
635
636 // invisible arguments
637 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000639 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000641 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000642 ResultStr += selfTy.getAsString();
643 }
644 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000646
647 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000648 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000649 ResultStr += " _cmd";
650
651 // Method arguments.
652 for (int i = 0; i < OMD->getNumParams(); i++) {
653 ParmVarDecl *PDecl = OMD->getParamDecl(i);
654 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000656 ResultStr += "id";
657 else
658 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000659 ResultStr += " ";
660 ResultStr += PDecl->getName();
661 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000662 if (OMD->isVariadic())
663 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000664 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000665
666}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000667void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
669 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000671 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000672 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000673 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000674 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000675
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000677 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
678 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 ObjCMethodDecl *OMD = *I;
681 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000682 SourceLocation LocStart = OMD->getLocStart();
683 SourceLocation LocEnd = OMD->getBody()->getLocStart();
684
685 const char *startBuf = SM->getCharacterData(LocStart);
686 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000687 ReplaceText(LocStart, endBuf-startBuf,
688 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000689 }
690
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000692 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
693 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000694 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000695 ObjCMethodDecl *OMD = *I;
696 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000697 SourceLocation LocStart = OMD->getLocStart();
698 SourceLocation LocEnd = OMD->getBody()->getLocStart();
699
700 const char *startBuf = SM->getCharacterData(LocStart);
701 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000702 ReplaceText(LocStart, endBuf-startBuf,
703 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000704 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000705 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000706 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000707 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000708 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000709}
710
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000712 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000714 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000715 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000716 ResultStr += ClassDecl->getName();
717 ResultStr += "\n";
718 ResultStr += "#define _REWRITER_typedef_";
719 ResultStr += ClassDecl->getName();
720 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000721 ResultStr += "typedef struct ";
722 ResultStr += ClassDecl->getName();
723 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000724 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000725 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000726
727 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000728 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000729 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000730 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000731
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000732 RewriteProperties(ClassDecl->getNumPropertyDecl(),
733 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000735 E = ClassDecl->instmeth_end(); I != E; ++I)
736 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000737 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000738 E = ClassDecl->classmeth_end(); I != E; ++I)
739 RewriteMethodDeclaration(*I);
740
Steve Naroff2feac5e2007-10-30 03:43:13 +0000741 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000742 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000743}
744
Steve Naroff7e3411b2007-11-15 02:58:25 +0000745Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000747 if (IV->isFreeIvar()) {
748 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
749 IV->getLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000750 ReplaceStmt(IV, Replacement);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000751 delete IV;
752 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000753 } else {
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000754#if 0
755 /// This code is not right. It seems unnecessary. It breaks use of
756 /// ivar reference used as 'receiver' of an expression; as in:
757 /// [newInv->_container addObject:0];
Steve Naroffc2a689b2007-11-15 11:33:00 +0000758 if (CurMethodDecl) {
759 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000760 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000761 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
762 IdentifierInfo *II = intT->getDecl()->getIdentifier();
763 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
764 II, 0);
765 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
766
767 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
768 // Don't forget the parens to enforce the proper binding.
769 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000770 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000771 delete IV->getBase();
772 return PE;
773 }
774 }
775 }
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000776#endif
Steve Naroff7e3411b2007-11-15 02:58:25 +0000777 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000778 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000779}
780
Chris Lattnerf04da132007-10-24 17:06:59 +0000781//===----------------------------------------------------------------------===//
782// Function Body / Expression rewriting
783//===----------------------------------------------------------------------===//
784
Steve Narofff3473a72007-11-09 15:20:18 +0000785Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000786 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
787 isa<DoStmt>(S) || isa<ForStmt>(S))
788 Stmts.push_back(S);
789 else if (isa<ObjCForCollectionStmt>(S)) {
790 Stmts.push_back(S);
791 ObjCBcLabelNo.push_back(++BcLabelCount);
792 }
793
Chris Lattner338d1e22008-01-31 05:10:40 +0000794 SourceLocation OrigStmtEnd = S->getLocEnd();
795
796 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000797 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
798 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000799 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000800 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000801 if (newStmt)
802 *CI = newStmt;
803 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000804
805 // Handle specific things.
806 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
807 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000808
809 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
810 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000811
812 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
813 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000814
Steve Naroffbeaf2992007-11-03 11:27:19 +0000815 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
816 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000817
Steve Naroff934f2762007-10-24 22:48:43 +0000818 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
819 // Before we rewrite it, put the original message expression in a comment.
820 SourceLocation startLoc = MessExpr->getLocStart();
821 SourceLocation endLoc = MessExpr->getLocEnd();
822
823 const char *startBuf = SM->getCharacterData(startLoc);
824 const char *endBuf = SM->getCharacterData(endLoc);
825
826 std::string messString;
827 messString += "// ";
828 messString.append(startBuf, endBuf-startBuf+1);
829 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000830
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000831 // FIXME: Missing definition of
832 // InsertText(clang::SourceLocation, char const*, unsigned int).
833 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000834 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000835 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000836 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000837 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000838
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000839 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
840 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000841
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000842 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
843 return RewriteObjCSynchronizedStmt(StmtTry);
844
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000845 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
846 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000847
848 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
849 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000850
851 if (ObjCForCollectionStmt *StmtForCollection =
852 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000853 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000854 if (BreakStmt *StmtBreakStmt =
855 dyn_cast<BreakStmt>(S))
856 return RewriteBreakStmt(StmtBreakStmt);
857 if (ContinueStmt *StmtContinueStmt =
858 dyn_cast<ContinueStmt>(S))
859 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000860
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000861 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
862 isa<DoStmt>(S) || isa<ForStmt>(S)) {
863 assert(!Stmts.empty() && "Statement stack is empty");
864 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
865 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
866 && "Statement stack mismatch");
867 Stmts.pop_back();
868 }
Steve Naroff874e2322007-11-15 10:28:18 +0000869#if 0
870 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
871 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
872 // Get the new text.
873 std::ostringstream Buf;
874 Replacement->printPretty(Buf);
875 const std::string &Str = Buf.str();
876
877 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000878 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000879 delete S;
880 return Replacement;
881 }
882#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000883 // Return this stmt unmodified.
884 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000885}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000886
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000887/// SynthCountByEnumWithState - To print:
888/// ((unsigned int (*)
889/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
890/// (void *)objc_msgSend)((id)l_collection,
891/// sel_registerName(
892/// "countByEnumeratingWithState:objects:count:"),
893/// &enumState,
894/// (id *)items, (unsigned int)16)
895///
896void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
897 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
898 "id *, unsigned int))(void *)objc_msgSend)";
899 buf += "\n\t\t";
900 buf += "((id)l_collection,\n\t\t";
901 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
902 buf += "\n\t\t";
903 buf += "&enumState, "
904 "(id *)items, (unsigned int)16)";
905}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000906
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000907/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
908/// statement to exit to its outer synthesized loop.
909///
910Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
911 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
912 return S;
913 // replace break with goto __break_label
914 std::string buf;
915
916 SourceLocation startLoc = S->getLocStart();
917 buf = "goto __break_label_";
918 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000919 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000920
921 return 0;
922}
923
924/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
925/// statement to continue with its inner synthesized loop.
926///
927Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
928 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
929 return S;
930 // replace continue with goto __continue_label
931 std::string buf;
932
933 SourceLocation startLoc = S->getLocStart();
934 buf = "goto __continue_label_";
935 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000936 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000937
938 return 0;
939}
940
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000941/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000942/// It rewrites:
943/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000944
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000945/// Into:
946/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000947/// type elem;
948/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000949/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000950/// id l_collection = (id)collection;
951/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
952/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000953/// if (limit) {
954/// unsigned long startMutations = *enumState.mutationsPtr;
955/// do {
956/// unsigned long counter = 0;
957/// do {
958/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000959/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000960/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000961/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000962/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000963/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000964/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
965/// objects:items count:16]);
966/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000967/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000968/// }
969/// else
970/// elem = nil;
971/// }
972///
Chris Lattner338d1e22008-01-31 05:10:40 +0000973Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
974 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000975 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
976 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
977 "ObjCForCollectionStmt Statement stack mismatch");
978 assert(!ObjCBcLabelNo.empty() &&
979 "ObjCForCollectionStmt - Label No stack empty");
980
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000981 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000982 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000983 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000984 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000985 std::string buf;
986 buf = "\n{\n\t";
987 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
988 // type elem;
989 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000990 elementTypeAsString = ElementType.getAsString();
991 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000992 buf += " ";
993 elementName = DS->getDecl()->getName();
994 buf += elementName;
995 buf += ";\n\t";
996 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000997 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000998 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000999 elementTypeAsString = DR->getDecl()->getType().getAsString();
1000 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001001 else
1002 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1003
1004 // struct __objcFastEnumerationState enumState = { 0 };
1005 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1006 // id items[16];
1007 buf += "id items[16];\n\t";
1008 // id l_collection = (id)
1009 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001010 // Find start location of 'collection' the hard way!
1011 const char *startCollectionBuf = startBuf;
1012 startCollectionBuf += 3; // skip 'for'
1013 startCollectionBuf = strchr(startCollectionBuf, '(');
1014 startCollectionBuf++; // skip '('
1015 // find 'in' and skip it.
1016 while (*startCollectionBuf != ' ' ||
1017 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1018 (*(startCollectionBuf+3) != ' ' &&
1019 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1020 startCollectionBuf++;
1021 startCollectionBuf += 3;
1022
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001024 ReplaceText(startLoc, startCollectionBuf - startBuf,
1025 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001026 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001027 SourceLocation rightParenLoc = S->getRParenLoc();
1028 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1029 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001030 buf = ";\n\t";
1031
1032 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1033 // objects:items count:16];
1034 // which is synthesized into:
1035 // unsigned int limit =
1036 // ((unsigned int (*)
1037 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1038 // (void *)objc_msgSend)((id)l_collection,
1039 // sel_registerName(
1040 // "countByEnumeratingWithState:objects:count:"),
1041 // (struct __objcFastEnumerationState *)&state,
1042 // (id *)items, (unsigned int)16);
1043 buf += "unsigned long limit =\n\t\t";
1044 SynthCountByEnumWithState(buf);
1045 buf += ";\n\t";
1046 /// if (limit) {
1047 /// unsigned long startMutations = *enumState.mutationsPtr;
1048 /// do {
1049 /// unsigned long counter = 0;
1050 /// do {
1051 /// if (startMutations != *enumState.mutationsPtr)
1052 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001053 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054 buf += "if (limit) {\n\t";
1055 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1056 buf += "do {\n\t\t";
1057 buf += "unsigned long counter = 0;\n\t\t";
1058 buf += "do {\n\t\t\t";
1059 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1060 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1061 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001062 buf += " = (";
1063 buf += elementTypeAsString;
1064 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001065 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001066 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001068 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001069 /// } while (counter < limit);
1070 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1071 /// objects:items count:16]);
1072 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001073 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001074 /// }
1075 /// else
1076 /// elem = nil;
1077 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001078 ///
1079 buf = ";\n\t";
1080 buf += "__continue_label_";
1081 buf += utostr(ObjCBcLabelNo.back());
1082 buf += ": ;";
1083 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001084 buf += "} while (counter < limit);\n\t";
1085 buf += "} while (limit = ";
1086 SynthCountByEnumWithState(buf);
1087 buf += ");\n\t";
1088 buf += elementName;
1089 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001090 buf += "__break_label_";
1091 buf += utostr(ObjCBcLabelNo.back());
1092 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001093 buf += "}\n\t";
1094 buf += "else\n\t\t";
1095 buf += elementName;
1096 buf += " = nil;\n";
1097 buf += "}\n";
1098 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001099 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001100 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001101 Stmts.pop_back();
1102 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001104}
1105
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001106/// RewriteObjCSynchronizedStmt -
1107/// This routine rewrites @synchronized(expr) stmt;
1108/// into:
1109/// objc_sync_enter(expr);
1110/// @try stmt @finally { objc_sync_exit(expr); }
1111///
1112Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1113 // Get the start location and compute the semi location.
1114 SourceLocation startLoc = S->getLocStart();
1115 const char *startBuf = SM->getCharacterData(startLoc);
1116
1117 assert((*startBuf == '@') && "bogus @synchronized location");
1118
1119 std::string buf;
1120 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001121 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001122 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1123 const char *endBuf = SM->getCharacterData(endLoc);
1124 endBuf++;
1125 const char *rparenBuf = strchr(endBuf, ')');
1126 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1127 buf = ");\n";
1128 // declare a new scope with two variables, _stack and _rethrow.
1129 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1130 buf += "int buf[18/*32-bit i386*/];\n";
1131 buf += "char *pointers[4];} _stack;\n";
1132 buf += "id volatile _rethrow = 0;\n";
1133 buf += "objc_exception_try_enter(&_stack);\n";
1134 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001135 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001136 startLoc = S->getSynchBody()->getLocEnd();
1137 startBuf = SM->getCharacterData(startLoc);
1138
1139 assert((*startBuf == '}') && "bogus @try block");
1140 SourceLocation lastCurlyLoc = startLoc;
1141 buf = "}\nelse {\n";
1142 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1143 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1144 // FIXME: This must be objc_sync_exit(syncExpr);
1145 buf += " objc_sync_exit();\n";
1146 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1147 buf += "}\n";
1148 buf += "}";
1149
Chris Lattneraadaf782008-01-31 19:51:04 +00001150 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001151 return 0;
1152}
1153
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001154Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001155 // Get the start location and compute the semi location.
1156 SourceLocation startLoc = S->getLocStart();
1157 const char *startBuf = SM->getCharacterData(startLoc);
1158
1159 assert((*startBuf == '@') && "bogus @try location");
1160
1161 std::string buf;
1162 // declare a new scope with two variables, _stack and _rethrow.
1163 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1164 buf += "int buf[18/*32-bit i386*/];\n";
1165 buf += "char *pointers[4];} _stack;\n";
1166 buf += "id volatile _rethrow = 0;\n";
1167 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001168 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001169
Chris Lattneraadaf782008-01-31 19:51:04 +00001170 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001171
1172 startLoc = S->getTryBody()->getLocEnd();
1173 startBuf = SM->getCharacterData(startLoc);
1174
1175 assert((*startBuf == '}') && "bogus @try block");
1176
1177 SourceLocation lastCurlyLoc = startLoc;
1178
1179 startLoc = startLoc.getFileLocWithOffset(1);
1180 buf = " /* @catch begin */ else {\n";
1181 buf += " id _caught = objc_exception_extract(&_stack);\n";
1182 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001183 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001184 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1185 buf += " else { /* @catch continue */";
1186
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001187 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001188
1189 bool sawIdTypedCatch = false;
1190 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001191 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001192 while (catchList) {
1193 Stmt *catchStmt = catchList->getCatchParamStmt();
1194
1195 if (catchList == S->getCatchStmts())
1196 buf = "if ("; // we are generating code for the first catch clause
1197 else
1198 buf = "else if (";
1199 startLoc = catchList->getLocStart();
1200 startBuf = SM->getCharacterData(startLoc);
1201
1202 assert((*startBuf == '@') && "bogus @catch location");
1203
1204 const char *lParenLoc = strchr(startBuf, '(');
1205
Steve Naroffbe4b3332008-02-01 22:08:12 +00001206 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001207 // Now rewrite the body...
1208 lastCatchBody = catchList->getCatchBody();
1209 SourceLocation rParenLoc = catchList->getRParenLoc();
1210 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1211 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1212 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1213 assert((*rParenBuf == ')') && "bogus @catch paren location");
1214 assert((*bodyBuf == '{') && "bogus @catch body location");
1215
1216 buf += "1) { id _tmp = _caught;";
1217 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1218 buf.c_str(), buf.size());
1219 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001220 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001222 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001223 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001224 sawIdTypedCatch = true;
1225 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001226 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001227
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001228 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001229 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001230 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001231 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001232 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001233 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001234 }
1235 }
1236 // Now rewrite the body...
1237 lastCatchBody = catchList->getCatchBody();
1238 SourceLocation rParenLoc = catchList->getRParenLoc();
1239 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1240 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1241 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1242 assert((*rParenBuf == ')') && "bogus @catch paren location");
1243 assert((*bodyBuf == '{') && "bogus @catch body location");
1244
1245 buf = " = _caught;";
1246 // Here we replace ") {" with "= _caught;" (which initializes and
1247 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001248 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001249 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001250 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001251 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001252 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001253 catchList = catchList->getNextCatchStmt();
1254 }
1255 // Complete the catch list...
1256 if (lastCatchBody) {
1257 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1258 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1259 assert((*bodyBuf == '}') && "bogus @catch body location");
1260 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1261 buf = " } } /* @catch end */\n";
1262
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001263 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001264
1265 // Set lastCurlyLoc
1266 lastCurlyLoc = lastCatchBody->getLocEnd();
1267 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001268 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001269 startLoc = finalStmt->getLocStart();
1270 startBuf = SM->getCharacterData(startLoc);
1271 assert((*startBuf == '@') && "bogus @finally start");
1272
1273 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001274 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001275
1276 Stmt *body = finalStmt->getFinallyBody();
1277 SourceLocation startLoc = body->getLocStart();
1278 SourceLocation endLoc = body->getLocEnd();
1279 const char *startBuf = SM->getCharacterData(startLoc);
1280 const char *endBuf = SM->getCharacterData(endLoc);
1281 assert((*startBuf == '{') && "bogus @finally body location");
1282 assert((*endBuf == '}') && "bogus @finally body location");
1283
1284 startLoc = startLoc.getFileLocWithOffset(1);
1285 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001286 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001287 endLoc = endLoc.getFileLocWithOffset(-1);
1288 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001289 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001290
1291 // Set lastCurlyLoc
1292 lastCurlyLoc = body->getLocEnd();
1293 }
1294 // Now emit the final closing curly brace...
1295 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1296 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001297 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001298 return 0;
1299}
1300
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001301Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001302 return 0;
1303}
1304
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001305Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001306 return 0;
1307}
1308
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001309// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001310// the throw expression is typically a message expression that's already
1311// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001312Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001313 // Get the start location and compute the semi location.
1314 SourceLocation startLoc = S->getLocStart();
1315 const char *startBuf = SM->getCharacterData(startLoc);
1316
1317 assert((*startBuf == '@') && "bogus @throw location");
1318
1319 std::string buf;
1320 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001321 if (S->getThrowExpr())
1322 buf = "objc_exception_throw(";
1323 else // add an implicit argument
1324 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001325 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001326 const char *semiBuf = strchr(startBuf, ';');
1327 assert((*semiBuf == ';') && "@throw: can't find ';'");
1328 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1329 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001330 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001331 return 0;
1332}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001333
Chris Lattnere64b7772007-10-24 16:57:36 +00001334Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001335 // Create a new string expression.
1336 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001337 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001338 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1339 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001340 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1341 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001342 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001343 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001344
Chris Lattner07506182007-11-30 22:53:43 +00001345 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001346 delete Exp;
1347 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001348}
1349
Steve Naroffb42f8412007-11-05 14:50:49 +00001350Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1351 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1352 // Create a call to sel_registerName("selName").
1353 llvm::SmallVector<Expr*, 8> SelExprs;
1354 QualType argType = Context->getPointerType(Context->CharTy);
1355 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1356 Exp->getSelector().getName().size(),
1357 false, argType, SourceLocation(),
1358 SourceLocation()));
1359 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1360 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001361 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001362 delete Exp;
1363 return SelExp;
1364}
1365
Steve Naroff934f2762007-10-24 22:48:43 +00001366CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1367 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001368 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001369 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001370
1371 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001372 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001373
1374 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001375 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001376 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1377
1378 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001379
Steve Naroff934f2762007-10-24 22:48:43 +00001380 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1381}
1382
Steve Naroffd5255f52007-11-01 13:24:47 +00001383static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1384 const char *&startRef, const char *&endRef) {
1385 while (startBuf < endBuf) {
1386 if (*startBuf == '<')
1387 startRef = startBuf; // mark the start.
1388 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001389 if (startRef && *startRef == '<') {
1390 endRef = startBuf; // mark the end.
1391 return true;
1392 }
1393 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001394 }
1395 startBuf++;
1396 }
1397 return false;
1398}
1399
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001400static void scanToNextArgument(const char *&argRef) {
1401 int angle = 0;
1402 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1403 if (*argRef == '<')
1404 angle++;
1405 else if (*argRef == '>')
1406 angle--;
1407 argRef++;
1408 }
1409 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1410}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001411
Steve Naroffd5255f52007-11-01 13:24:47 +00001412bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001413
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001414 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001415 return true;
1416
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001417 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001418 return true;
1419
Steve Naroffd5255f52007-11-01 13:24:47 +00001420 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001421 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001422 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001423 return true; // we have "Class <Protocol> *".
1424 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001425 return false;
1426}
1427
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001428void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001429 SourceLocation Loc;
1430 QualType Type;
1431 const FunctionTypeProto *proto = 0;
1432 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1433 Loc = VD->getLocation();
1434 Type = VD->getType();
1435 }
1436 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1437 Loc = FD->getLocation();
1438 // Check for ObjC 'id' and class types that have been adorned with protocol
1439 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1440 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1441 assert(funcType && "missing function type");
1442 proto = dyn_cast<FunctionTypeProto>(funcType);
1443 if (!proto)
1444 return;
1445 Type = proto->getResultType();
1446 }
1447 else
1448 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001449
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001450 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001451 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001452
1453 const char *endBuf = SM->getCharacterData(Loc);
1454 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001455 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001456 startBuf--; // scan backward (from the decl location) for return type.
1457 const char *startRef = 0, *endRef = 0;
1458 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1459 // Get the locations of the startRef, endRef.
1460 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1461 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1462 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001463 InsertText(LessLoc, "/*", 2);
1464 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001465 }
1466 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001467 if (!proto)
1468 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001469 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001470 const char *startBuf = SM->getCharacterData(Loc);
1471 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001472 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1473 if (needToScanForQualifiers(proto->getArgType(i))) {
1474 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001475
Steve Naroffd5255f52007-11-01 13:24:47 +00001476 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001477 // scan forward (from the decl location) for argument types.
1478 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001479 const char *startRef = 0, *endRef = 0;
1480 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1481 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001482 SourceLocation LessLoc =
1483 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1484 SourceLocation GreaterLoc =
1485 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001486 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001487 InsertText(LessLoc, "/*", 2);
1488 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001489 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001490 startBuf = ++endBuf;
1491 }
1492 else {
1493 while (*startBuf != ')' && *startBuf != ',')
1494 startBuf++; // scan forward (from the decl location) for argument types.
1495 startBuf++;
1496 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001498}
1499
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001500// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1501void RewriteTest::SynthSelGetUidFunctionDecl() {
1502 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1503 llvm::SmallVector<QualType, 16> ArgTys;
1504 ArgTys.push_back(Context->getPointerType(
1505 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001506 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001507 &ArgTys[0], ArgTys.size(),
1508 false /*isVariadic*/);
1509 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1510 SelGetUidIdent, getFuncType,
1511 FunctionDecl::Extern, false, 0);
1512}
1513
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001514// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1515void RewriteTest::SynthGetProtocolFunctionDecl() {
1516 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1517 llvm::SmallVector<QualType, 16> ArgTys;
1518 ArgTys.push_back(Context->getPointerType(
1519 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001520 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001521 &ArgTys[0], ArgTys.size(),
1522 false /*isVariadic*/);
1523 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1524 SelGetProtoIdent, getFuncType,
1525 FunctionDecl::Extern, false, 0);
1526}
1527
Steve Naroff09b266e2007-10-30 23:14:51 +00001528void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1529 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001530 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001531 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001532 return;
1533 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001534 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001535}
1536
1537// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1538void RewriteTest::SynthMsgSendFunctionDecl() {
1539 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1540 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001541 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001542 assert(!argT.isNull() && "Can't find 'id' type");
1543 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001544 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001545 assert(!argT.isNull() && "Can't find 'SEL' type");
1546 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001547 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001548 &ArgTys[0], ArgTys.size(),
1549 true /*isVariadic*/);
1550 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1551 msgSendIdent, msgSendType,
1552 FunctionDecl::Extern, false, 0);
1553}
1554
Steve Naroff874e2322007-11-15 10:28:18 +00001555// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1556void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1557 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1558 llvm::SmallVector<QualType, 16> ArgTys;
1559 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1560 &Context->Idents.get("objc_super"), 0);
1561 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1562 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1563 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001564 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001565 assert(!argT.isNull() && "Can't find 'SEL' type");
1566 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001567 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001568 &ArgTys[0], ArgTys.size(),
1569 true /*isVariadic*/);
1570 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1571 msgSendIdent, msgSendType,
1572 FunctionDecl::Extern, false, 0);
1573}
1574
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001575// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1576void RewriteTest::SynthMsgSendStretFunctionDecl() {
1577 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1578 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001579 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001580 assert(!argT.isNull() && "Can't find 'id' type");
1581 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001582 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001583 assert(!argT.isNull() && "Can't find 'SEL' type");
1584 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001585 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001586 &ArgTys[0], ArgTys.size(),
1587 true /*isVariadic*/);
1588 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1589 msgSendIdent, msgSendType,
1590 FunctionDecl::Extern, false, 0);
1591}
1592
1593// SynthMsgSendSuperStretFunctionDecl -
1594// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1595void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1596 IdentifierInfo *msgSendIdent =
1597 &Context->Idents.get("objc_msgSendSuper_stret");
1598 llvm::SmallVector<QualType, 16> ArgTys;
1599 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1600 &Context->Idents.get("objc_super"), 0);
1601 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1602 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1603 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001604 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001605 assert(!argT.isNull() && "Can't find 'SEL' type");
1606 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001608 &ArgTys[0], ArgTys.size(),
1609 true /*isVariadic*/);
1610 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1611 msgSendIdent, msgSendType,
1612 FunctionDecl::Extern, false, 0);
1613}
1614
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001615// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1616void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1617 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1618 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001619 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001620 assert(!argT.isNull() && "Can't find 'id' type");
1621 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001622 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001623 assert(!argT.isNull() && "Can't find 'SEL' type");
1624 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001626 &ArgTys[0], ArgTys.size(),
1627 true /*isVariadic*/);
1628 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1629 msgSendIdent, msgSendType,
1630 FunctionDecl::Extern, false, 0);
1631}
1632
Steve Naroff09b266e2007-10-30 23:14:51 +00001633// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1634void RewriteTest::SynthGetClassFunctionDecl() {
1635 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1636 llvm::SmallVector<QualType, 16> ArgTys;
1637 ArgTys.push_back(Context->getPointerType(
1638 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001640 &ArgTys[0], ArgTys.size(),
1641 false /*isVariadic*/);
1642 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1643 getClassIdent, getClassType,
1644 FunctionDecl::Extern, false, 0);
1645}
1646
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001647// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1648void RewriteTest::SynthGetMetaClassFunctionDecl() {
1649 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1650 llvm::SmallVector<QualType, 16> ArgTys;
1651 ArgTys.push_back(Context->getPointerType(
1652 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001653 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001654 &ArgTys[0], ArgTys.size(),
1655 false /*isVariadic*/);
1656 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1657 getClassIdent, getClassType,
1658 FunctionDecl::Extern, false, 0);
1659}
1660
Steve Naroff96984642007-11-08 14:30:50 +00001661// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1662void RewriteTest::SynthCFStringFunctionDecl() {
1663 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1664 llvm::SmallVector<QualType, 16> ArgTys;
1665 ArgTys.push_back(Context->getPointerType(
1666 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001667 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001668 &ArgTys[0], ArgTys.size(),
1669 false /*isVariadic*/);
1670 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1671 getClassIdent, getClassType,
1672 FunctionDecl::Extern, false, 0);
1673}
1674
Steve Naroffbeaf2992007-11-03 11:27:19 +00001675Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001676#if 1
1677 // This rewrite is specific to GCC, which has builtin support for CFString.
1678 if (!CFStringFunctionDecl)
1679 SynthCFStringFunctionDecl();
1680 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1681 llvm::SmallVector<Expr*, 8> StrExpr;
1682 StrExpr.push_back(Exp->getString());
1683 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1684 &StrExpr[0], StrExpr.size());
1685 // cast to NSConstantString *
1686 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001687 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001688 delete Exp;
1689 return cast;
1690#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001691 assert(ConstantStringClassReference && "Can't find constant string reference");
1692 llvm::SmallVector<Expr*, 4> InitExprs;
1693
1694 // Synthesize "(Class)&_NSConstantStringClassReference"
1695 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1696 ConstantStringClassReference->getType(),
1697 SourceLocation());
1698 QualType expType = Context->getPointerType(ClsRef->getType());
1699 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1700 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001701 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001702 SourceLocation());
1703 InitExprs.push_back(cast); // set the 'isa'.
1704 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1705 unsigned IntSize = static_cast<unsigned>(
1706 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1707 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1708 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1709 Exp->getLocStart());
1710 InitExprs.push_back(len); // set "int numBytes".
1711
1712 // struct NSConstantString
1713 QualType CFConstantStrType = Context->getCFConstantStringType();
1714 // (struct NSConstantString) { <exprs from above> }
1715 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1716 &InitExprs[0], InitExprs.size(),
1717 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001718 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001719 // struct NSConstantString *
1720 expType = Context->getPointerType(StrRep->getType());
1721 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1722 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001723 // cast to NSConstantString *
1724 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001725 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001726 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001727 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001728#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001729}
1730
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001731ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001732 // check if we are sending a message to 'super'
1733 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001734 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1735 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1736 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1737 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001738 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001740 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001741 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 if (ObjCInterfaceType *IT =
1743 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001744 if (IT->getDecl() ==
1745 CurMethodDecl->getClassInterface()->getSuperClass())
1746 return IT->getDecl();
1747 }
1748 }
1749 }
1750 }
1751 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001752 }
Steve Naroff874e2322007-11-15 10:28:18 +00001753 }
1754 return 0;
1755}
1756
1757// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1758QualType RewriteTest::getSuperStructType() {
1759 if (!SuperStructDecl) {
1760 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1761 &Context->Idents.get("objc_super"), 0);
1762 QualType FieldTypes[2];
1763
1764 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001765 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001766 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001767 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001768 // Create fields
1769 FieldDecl *FieldDecls[2];
1770
1771 for (unsigned i = 0; i < 2; ++i)
1772 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1773
1774 SuperStructDecl->defineBody(FieldDecls, 4);
1775 }
1776 return Context->getTagDeclType(SuperStructDecl);
1777}
1778
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001779Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001780 if (!SelGetUidFunctionDecl)
1781 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001782 if (!MsgSendFunctionDecl)
1783 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001784 if (!MsgSendSuperFunctionDecl)
1785 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001786 if (!MsgSendStretFunctionDecl)
1787 SynthMsgSendStretFunctionDecl();
1788 if (!MsgSendSuperStretFunctionDecl)
1789 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001790 if (!MsgSendFpretFunctionDecl)
1791 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001792 if (!GetClassFunctionDecl)
1793 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001794 if (!GetMetaClassFunctionDecl)
1795 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001796
Steve Naroff874e2322007-11-15 10:28:18 +00001797 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001798 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1799 // May need to use objc_msgSend_stret() as well.
1800 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001802 QualType resultType = mDecl->getResultType();
1803 if (resultType.getCanonicalType()->isStructureType()
1804 || resultType.getCanonicalType()->isUnionType())
1805 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001806 else if (resultType.getCanonicalType()->isRealFloatingType())
1807 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001808 }
Steve Naroff874e2322007-11-15 10:28:18 +00001809
Steve Naroff934f2762007-10-24 22:48:43 +00001810 // Synthesize a call to objc_msgSend().
1811 llvm::SmallVector<Expr*, 8> MsgExprs;
1812 IdentifierInfo *clsName = Exp->getClassName();
1813
1814 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1815 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001816 if (!strcmp(clsName->getName(), "super")) {
1817 MsgSendFlavor = MsgSendSuperFunctionDecl;
1818 if (MsgSendStretFlavor)
1819 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1820 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1821
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001823 CurMethodDecl->getClassInterface()->getSuperClass();
1824
1825 llvm::SmallVector<Expr*, 4> InitExprs;
1826
1827 // set the receiver to self, the first argument to all methods.
1828 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001829 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001830 SourceLocation()));
1831 llvm::SmallVector<Expr*, 8> ClsExprs;
1832 QualType argType = Context->getPointerType(Context->CharTy);
1833 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1834 SuperDecl->getIdentifier()->getLength(),
1835 false, argType, SourceLocation(),
1836 SourceLocation()));
1837 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1838 &ClsExprs[0],
1839 ClsExprs.size());
1840 // To turn off a warning, type-cast to 'id'
1841 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001842 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001843 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1844 // struct objc_super
1845 QualType superType = getSuperStructType();
1846 // (struct objc_super) { <exprs from above> }
1847 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1848 &InitExprs[0], InitExprs.size(),
1849 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001850 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001851 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001852 // struct objc_super *
1853 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1854 Context->getPointerType(SuperRep->getType()),
1855 SourceLocation());
1856 MsgExprs.push_back(Unop);
1857 } else {
1858 llvm::SmallVector<Expr*, 8> ClsExprs;
1859 QualType argType = Context->getPointerType(Context->CharTy);
1860 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1861 clsName->getLength(),
1862 false, argType, SourceLocation(),
1863 SourceLocation()));
1864 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1865 &ClsExprs[0],
1866 ClsExprs.size());
1867 MsgExprs.push_back(Cls);
1868 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001869 } else { // instance message.
1870 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001871
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001872 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001873 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001874 if (MsgSendStretFlavor)
1875 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001876 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1877
1878 llvm::SmallVector<Expr*, 4> InitExprs;
1879
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001880 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001882 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001883
1884 llvm::SmallVector<Expr*, 8> ClsExprs;
1885 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001886 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1887 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001888 false, argType, SourceLocation(),
1889 SourceLocation()));
1890 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001891 &ClsExprs[0],
1892 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001893 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001894 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001895 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001896 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001897 // struct objc_super
1898 QualType superType = getSuperStructType();
1899 // (struct objc_super) { <exprs from above> }
1900 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1901 &InitExprs[0], InitExprs.size(),
1902 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001903 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001904 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001905 // struct objc_super *
1906 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1907 Context->getPointerType(SuperRep->getType()),
1908 SourceLocation());
1909 MsgExprs.push_back(Unop);
1910 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001911 // Remove all type-casts because it may contain objc-style types; e.g.
1912 // Foo<Proto> *.
1913 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1914 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001915 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001916 MsgExprs.push_back(recExpr);
1917 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001918 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001919 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001920 llvm::SmallVector<Expr*, 8> SelExprs;
1921 QualType argType = Context->getPointerType(Context->CharTy);
1922 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1923 Exp->getSelector().getName().size(),
1924 false, argType, SourceLocation(),
1925 SourceLocation()));
1926 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1927 &SelExprs[0], SelExprs.size());
1928 MsgExprs.push_back(SelExp);
1929
1930 // Now push any user supplied arguments.
1931 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001932 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001933 // Make all implicit casts explicit...ICE comes in handy:-)
1934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1935 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1937 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001938 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001939 }
1940 // Make id<P...> cast into an 'id' cast.
1941 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001942 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001943 while ((CE = dyn_cast<CastExpr>(userExpr)))
1944 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001945 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001946 userExpr, SourceLocation());
1947 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001948 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001949 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001950 // We've transferred the ownership to MsgExprs. Null out the argument in
1951 // the original expression, since we will delete it below.
1952 Exp->setArg(i, 0);
1953 }
Steve Naroffab972d32007-11-04 22:37:50 +00001954 // Generate the funky cast.
1955 CastExpr *cast;
1956 llvm::SmallVector<QualType, 8> ArgTypes;
1957 QualType returnType;
1958
1959 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001960 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1961 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1962 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 ArgTypes.push_back(Context->getObjCIdType());
1964 ArgTypes.push_back(Context->getObjCSelType());
1965 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001966 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001967 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001968 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1969 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001970 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001971 ArgTypes.push_back(t);
1972 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001973 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1974 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001975 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001977 }
1978 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001979 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001980
1981 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001982 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1983 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001984
1985 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1986 // If we don't do this cast, we get the following bizarre warning/note:
1987 // xx.m:13: warning: function called through a non-compatible type
1988 // xx.m:13: note: if this code is reached, the program will abort
1989 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1990 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001991
Steve Naroffab972d32007-11-04 22:37:50 +00001992 // Now do the "normal" pointer to function cast.
1993 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001994 &ArgTypes[0], ArgTypes.size(),
1995 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001996 castType = Context->getPointerType(castType);
1997 cast = new CastExpr(castType, cast, SourceLocation());
1998
1999 // Don't forget the parens to enforce the proper binding.
2000 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2001
2002 const FunctionType *FT = msgSendType->getAsFunctionType();
2003 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2004 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002005 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002006 if (MsgSendStretFlavor) {
2007 // We have the method which returns a struct/union. Must also generate
2008 // call to objc_msgSend_stret and hang both varieties on a conditional
2009 // expression which dictate which one to envoke depending on size of
2010 // method's return type.
2011
2012 // Create a reference to the objc_msgSend_stret() declaration.
2013 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2014 SourceLocation());
2015 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2016 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2017 SourceLocation());
2018 // Now do the "normal" pointer to function cast.
2019 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002020 &ArgTypes[0], ArgTypes.size(),
2021 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002022 castType = Context->getPointerType(castType);
2023 cast = new CastExpr(castType, cast, SourceLocation());
2024
2025 // Don't forget the parens to enforce the proper binding.
2026 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2027
2028 FT = msgSendType->getAsFunctionType();
2029 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2030 FT->getResultType(), SourceLocation());
2031
2032 // Build sizeof(returnType)
2033 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2034 returnType, Context->getSizeType(),
2035 SourceLocation(), SourceLocation());
2036 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2037 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2038 // For X86 it is more complicated and some kind of target specific routine
2039 // is needed to decide what to do.
2040 unsigned IntSize = static_cast<unsigned>(
2041 Context->getTypeSize(Context->IntTy, SourceLocation()));
2042
2043 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2044 Context->IntTy,
2045 SourceLocation());
2046 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2047 BinaryOperator::LE,
2048 Context->IntTy,
2049 SourceLocation());
2050 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2051 ConditionalOperator *CondExpr =
2052 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002053 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002054 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002055 return ReplacingStmt;
2056}
2057
2058Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2059 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002060 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002061 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002062
Chris Lattnere64b7772007-10-24 16:57:36 +00002063 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002064 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002065}
2066
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002067/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2068/// call to objc_getProtocol("proto-name").
2069Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2070 if (!GetProtocolFunctionDecl)
2071 SynthGetProtocolFunctionDecl();
2072 // Create a call to objc_getProtocol("ProtocolName").
2073 llvm::SmallVector<Expr*, 8> ProtoExprs;
2074 QualType argType = Context->getPointerType(Context->CharTy);
2075 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2076 strlen(Exp->getProtocol()->getName()),
2077 false, argType, SourceLocation(),
2078 SourceLocation()));
2079 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2080 &ProtoExprs[0],
2081 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002082 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002083 delete Exp;
2084 return ProtoExp;
2085
2086}
2087
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002089/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002090void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002091 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2093 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002094 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002096 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002098 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002099 SourceLocation LocStart = CDecl->getLocStart();
2100 SourceLocation LocEnd = CDecl->getLocEnd();
2101
2102 const char *startBuf = SM->getCharacterData(LocStart);
2103 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002104 // If no ivars and no root or if its root, directly or indirectly,
2105 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002106 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002107 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002108 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002109 return;
2110 }
2111
2112 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002113 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002114 Result += "\nstruct ";
2115 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002116
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002117 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002118 const char *cursor = strchr(startBuf, '{');
2119 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002120 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002121
2122 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002123 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002124 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002125 Result = "\n struct ";
2126 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002127 // Note: We don't name the field decl. This simplifies the "codegen" for
2128 // accessing a superclasses instance variables (and is similar to what gcc
2129 // does internally). The unnamed struct field feature is enabled with
2130 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2131 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002132 Result += ";\n";
2133
2134 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002135 SourceLocation OnePastCurly =
2136 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2137 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002138 }
2139 cursor++; // past '{'
2140
2141 // Now comment out any visibility specifiers.
2142 while (cursor < endBuf) {
2143 if (*cursor == '@') {
2144 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002145 // Skip whitespace.
2146 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2147 /*scan*/;
2148
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002149 // FIXME: presence of @public, etc. inside comment results in
2150 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002151 if (!strncmp(cursor, "public", strlen("public")) ||
2152 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002153 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002154 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002155 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002156 // FIXME: If there are cases where '<' is used in ivar declaration part
2157 // of user code, then scan the ivar list and use needToScanForQualifiers
2158 // for type checking.
2159 else if (*cursor == '<') {
2160 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002161 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002162 cursor = strchr(cursor, '>');
2163 cursor++;
2164 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002165 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002166 }
Steve Narofffea763e82007-11-14 19:25:57 +00002167 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002168 }
Steve Narofffea763e82007-11-14 19:25:57 +00002169 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002170 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002171 } else { // we don't have any instance variables - insert super struct.
2172 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2173 Result += " {\n struct ";
2174 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002175 // Note: We don't name the field decl. This simplifies the "codegen" for
2176 // accessing a superclasses instance variables (and is similar to what gcc
2177 // does internally). The unnamed struct field feature is enabled with
2178 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2179 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002180 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002181 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002182 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002183 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002184 if (!ObjCSynthesizedStructs.insert(CDecl))
2185 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002186}
2187
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002188// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002189/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002191 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002192 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002193 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002194 const char *ClassName,
2195 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002196 if (MethodBegin == MethodEnd) return;
2197
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002198 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002199 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002200 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002201 SEL _cmd;
2202 char *method_types;
2203 void *_imp;
2204 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002205 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002206 Result += "\nstruct _objc_method {\n";
2207 Result += "\tSEL _cmd;\n";
2208 Result += "\tchar *method_types;\n";
2209 Result += "\tvoid *_imp;\n";
2210 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002211
2212 /* struct _objc_method_list {
2213 struct _objc_method_list *next_method;
2214 int method_count;
2215 struct _objc_method method_list[];
2216 }
2217 */
2218 Result += "\nstruct _objc_method_list {\n";
2219 Result += "\tstruct _objc_method_list *next_method;\n";
2220 Result += "\tint method_count;\n";
2221 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002222 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002223 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002224
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002225 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002226 Result += "\nstatic struct _objc_method_list _OBJC_";
2227 Result += prefix;
2228 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2229 Result += "_METHODS_";
2230 Result += ClassName;
2231 Result += " __attribute__ ((section (\"__OBJC, __";
2232 Result += IsInstanceMethod ? "inst" : "cls";
2233 Result += "_meth\")))= ";
2234 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002235
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002236 Result += "\t,{{(SEL)\"";
2237 Result += (*MethodBegin)->getSelector().getName().c_str();
2238 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002240 Result += "\", \"";
2241 Result += MethodTypeString;
2242 Result += "\", ";
2243 Result += MethodInternalNames[*MethodBegin];
2244 Result += "}\n";
2245 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2246 Result += "\t ,{(SEL)\"";
2247 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002248 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002250 Result += "\", \"";
2251 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002252 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002253 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002254 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002255 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002256 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002257}
2258
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002259/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2260void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002261 int NumProtocols,
2262 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002263 const char *ClassName,
2264 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002265 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002266 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002267 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002268 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002269 // Output struct protocol_methods holder of method selector and type.
2270 if (!objc_protocol_methods &&
2271 (PDecl->getNumInstanceMethods() > 0
2272 || PDecl->getNumClassMethods() > 0)) {
2273 /* struct protocol_methods {
2274 SEL _cmd;
2275 char *method_types;
2276 }
2277 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002278 Result += "\nstruct protocol_methods {\n";
2279 Result += "\tSEL _cmd;\n";
2280 Result += "\tchar *method_types;\n";
2281 Result += "};\n";
2282
2283 /* struct _objc_protocol_method_list {
2284 int protocol_method_count;
2285 struct protocol_methods protocols[];
2286 }
2287 */
2288 Result += "\nstruct _objc_protocol_method_list {\n";
2289 Result += "\tint protocol_method_count;\n";
2290 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002291 objc_protocol_methods = true;
2292 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002293
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002294 int NumMethods = PDecl->getNumInstanceMethods();
2295 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002296 Result += "\nstatic struct _objc_protocol_method_list "
2297 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2298 Result += PDecl->getName();
2299 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2300 "{\n\t" + utostr(NumMethods) + "\n";
2301
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002302 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002303 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002304 E = PDecl->instmeth_end(); I != E; ++I) {
2305 if (I == PDecl->instmeth_begin())
2306 Result += "\t ,{{(SEL)\"";
2307 else
2308 Result += "\t ,{(SEL)\"";
2309 Result += (*I)->getSelector().getName().c_str();
2310 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002311 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002312 Result += "\", \"";
2313 Result += MethodTypeString;
2314 Result += "\"}\n";
2315 }
2316 Result += "\t }\n};\n";
2317 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002318
2319 // Output class methods declared in this protocol.
2320 NumMethods = PDecl->getNumClassMethods();
2321 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002322 Result += "\nstatic struct _objc_protocol_method_list "
2323 "_OBJC_PROTOCOL_CLASS_METHODS_";
2324 Result += PDecl->getName();
2325 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2326 "{\n\t";
2327 Result += utostr(NumMethods);
2328 Result += "\n";
2329
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002330 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002331 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002332 E = PDecl->classmeth_end(); I != E; ++I) {
2333 if (I == PDecl->classmeth_begin())
2334 Result += "\t ,{{(SEL)\"";
2335 else
2336 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002337 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002338 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002340 Result += "\", \"";
2341 Result += MethodTypeString;
2342 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002343 }
2344 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002345 }
2346 // Output:
2347 /* struct _objc_protocol {
2348 // Objective-C 1.0 extensions
2349 struct _objc_protocol_extension *isa;
2350 char *protocol_name;
2351 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002352 struct _objc_protocol_method_list *instance_methods;
2353 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002354 };
2355 */
2356 static bool objc_protocol = false;
2357 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002358 Result += "\nstruct _objc_protocol {\n";
2359 Result += "\tstruct _objc_protocol_extension *isa;\n";
2360 Result += "\tchar *protocol_name;\n";
2361 Result += "\tstruct _objc_protocol **protocol_list;\n";
2362 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2363 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2364 Result += "};\n";
2365
2366 /* struct _objc_protocol_list {
2367 struct _objc_protocol_list *next;
2368 int protocol_count;
2369 struct _objc_protocol *class_protocols[];
2370 }
2371 */
2372 Result += "\nstruct _objc_protocol_list {\n";
2373 Result += "\tstruct _objc_protocol_list *next;\n";
2374 Result += "\tint protocol_count;\n";
2375 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2376 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002377 objc_protocol = true;
2378 }
2379
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002380 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2381 Result += PDecl->getName();
2382 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2383 "{\n\t0, \"";
2384 Result += PDecl->getName();
2385 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002386 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002387 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2388 Result += PDecl->getName();
2389 Result += ", ";
2390 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002391 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002392 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002393 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002394 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2395 Result += PDecl->getName();
2396 Result += "\n";
2397 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002398 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002399 Result += "0\n";
2400 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002401 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002402 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002403 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2404 Result += prefix;
2405 Result += "_PROTOCOLS_";
2406 Result += ClassName;
2407 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2408 "{\n\t0, ";
2409 Result += utostr(NumProtocols);
2410 Result += "\n";
2411
2412 Result += "\t,{&_OBJC_PROTOCOL_";
2413 Result += Protocols[0]->getName();
2414 Result += " \n";
2415
2416 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002417 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002418 Result += "\t ,&_OBJC_PROTOCOL_";
2419 Result += PDecl->getName();
2420 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002421 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002422 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002423 }
2424}
2425
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002426/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002427/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002430 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002431 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002432 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002433 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2434 CDecl = CDecl->getNextClassCategory())
2435 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2436 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002437
Chris Lattnereb44eee2007-12-23 01:40:15 +00002438 std::string FullCategoryName = ClassDecl->getName();
2439 FullCategoryName += '_';
2440 FullCategoryName += IDecl->getName();
2441
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002442 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002444 true, "CATEGORY_", FullCategoryName.c_str(),
2445 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002446
2447 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002448 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002449 false, "CATEGORY_", FullCategoryName.c_str(),
2450 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002451
2452 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002453 // Null CDecl is case of a category implementation with no category interface
2454 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002456 CDecl->getNumReferencedProtocols(),
2457 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002458 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002459
2460 /* struct _objc_category {
2461 char *category_name;
2462 char *class_name;
2463 struct _objc_method_list *instance_methods;
2464 struct _objc_method_list *class_methods;
2465 struct _objc_protocol_list *protocols;
2466 // Objective-C 1.0 extensions
2467 uint32_t size; // sizeof (struct _objc_category)
2468 struct _objc_property_list *instance_properties; // category's own
2469 // @property decl.
2470 };
2471 */
2472
2473 static bool objc_category = false;
2474 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002475 Result += "\nstruct _objc_category {\n";
2476 Result += "\tchar *category_name;\n";
2477 Result += "\tchar *class_name;\n";
2478 Result += "\tstruct _objc_method_list *instance_methods;\n";
2479 Result += "\tstruct _objc_method_list *class_methods;\n";
2480 Result += "\tstruct _objc_protocol_list *protocols;\n";
2481 Result += "\tunsigned int size;\n";
2482 Result += "\tstruct _objc_property_list *instance_properties;\n";
2483 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002484 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002485 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002486 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2487 Result += FullCategoryName;
2488 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2489 Result += IDecl->getName();
2490 Result += "\"\n\t, \"";
2491 Result += ClassDecl->getName();
2492 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002493
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002494 if (IDecl->getNumInstanceMethods() > 0) {
2495 Result += "\t, (struct _objc_method_list *)"
2496 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2497 Result += FullCategoryName;
2498 Result += "\n";
2499 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002500 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002501 Result += "\t, 0\n";
2502 if (IDecl->getNumClassMethods() > 0) {
2503 Result += "\t, (struct _objc_method_list *)"
2504 "&_OBJC_CATEGORY_CLASS_METHODS_";
2505 Result += FullCategoryName;
2506 Result += "\n";
2507 }
2508 else
2509 Result += "\t, 0\n";
2510
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002511 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002512 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2513 Result += FullCategoryName;
2514 Result += "\n";
2515 }
2516 else
2517 Result += "\t, 0\n";
2518 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002519}
2520
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002521/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2522/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2524 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002525 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002526 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002527 Result += IDecl->getName();
2528 Result += ", ";
2529 Result += ivar->getName();
2530 Result += ")";
2531}
2532
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002533//===----------------------------------------------------------------------===//
2534// Meta Data Emission
2535//===----------------------------------------------------------------------===//
2536
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002537void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002538 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002539 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002541 // Explictly declared @interface's are already synthesized.
2542 if (CDecl->ImplicitInterfaceDecl()) {
2543 // FIXME: Implementation of a class with no @interface (legacy) doese not
2544 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002546 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002547
Chris Lattnerbe6df082007-12-12 07:56:42 +00002548 // Build _objc_ivar_list metadata for classes ivars if needed
2549 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2550 ? IDecl->getImplDeclNumIvars()
2551 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002552 if (NumIvars > 0) {
2553 static bool objc_ivar = false;
2554 if (!objc_ivar) {
2555 /* struct _objc_ivar {
2556 char *ivar_name;
2557 char *ivar_type;
2558 int ivar_offset;
2559 };
2560 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002561 Result += "\nstruct _objc_ivar {\n";
2562 Result += "\tchar *ivar_name;\n";
2563 Result += "\tchar *ivar_type;\n";
2564 Result += "\tint ivar_offset;\n";
2565 Result += "};\n";
2566
2567 /* struct _objc_ivar_list {
2568 int ivar_count;
2569 struct _objc_ivar ivar_list[];
2570 };
2571 */
2572 Result += "\nstruct _objc_ivar_list {\n";
2573 Result += "\tint ivar_count;\n";
2574 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002575 objc_ivar = true;
2576 }
2577
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002578 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2579 Result += IDecl->getName();
2580 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2581 "{\n\t";
2582 Result += utostr(NumIvars);
2583 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002584
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002585 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002586 if (IDecl->getImplDeclNumIvars() > 0) {
2587 IVI = IDecl->ivar_begin();
2588 IVE = IDecl->ivar_end();
2589 } else {
2590 IVI = CDecl->ivar_begin();
2591 IVE = CDecl->ivar_end();
2592 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002593 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002594 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002595 Result += "\", \"";
2596 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002597 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2598 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002599 Result += StrEncoding;
2600 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002601 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002602 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002603 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002604 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002605 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002606 Result += "\", \"";
2607 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002608 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2609 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002610 Result += StrEncoding;
2611 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002612 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002613 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002614 }
2615
2616 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002617 }
2618
2619 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002620 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002621 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002622
2623 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002624 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002625 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002626
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002627 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002628 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002629 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002630 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002631
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002632
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002633 // Declaration of class/meta-class metadata
2634 /* struct _objc_class {
2635 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002636 const char *super_class_name;
2637 char *name;
2638 long version;
2639 long info;
2640 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002641 struct _objc_ivar_list *ivars;
2642 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002643 struct objc_cache *cache;
2644 struct objc_protocol_list *protocols;
2645 const char *ivar_layout;
2646 struct _objc_class_ext *ext;
2647 };
2648 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002649 static bool objc_class = false;
2650 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002651 Result += "\nstruct _objc_class {\n";
2652 Result += "\tstruct _objc_class *isa;\n";
2653 Result += "\tconst char *super_class_name;\n";
2654 Result += "\tchar *name;\n";
2655 Result += "\tlong version;\n";
2656 Result += "\tlong info;\n";
2657 Result += "\tlong instance_size;\n";
2658 Result += "\tstruct _objc_ivar_list *ivars;\n";
2659 Result += "\tstruct _objc_method_list *methods;\n";
2660 Result += "\tstruct objc_cache *cache;\n";
2661 Result += "\tstruct _objc_protocol_list *protocols;\n";
2662 Result += "\tconst char *ivar_layout;\n";
2663 Result += "\tstruct _objc_class_ext *ext;\n";
2664 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002665 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002666 }
2667
2668 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002669 ObjCInterfaceDecl *RootClass = 0;
2670 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002671 while (SuperClass) {
2672 RootClass = SuperClass;
2673 SuperClass = SuperClass->getSuperClass();
2674 }
2675 SuperClass = CDecl->getSuperClass();
2676
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002677 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2678 Result += CDecl->getName();
2679 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2680 "{\n\t(struct _objc_class *)\"";
2681 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2682 Result += "\"";
2683
2684 if (SuperClass) {
2685 Result += ", \"";
2686 Result += SuperClass->getName();
2687 Result += "\", \"";
2688 Result += CDecl->getName();
2689 Result += "\"";
2690 }
2691 else {
2692 Result += ", 0, \"";
2693 Result += CDecl->getName();
2694 Result += "\"";
2695 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002696 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002697 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002698 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002699 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002700 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002701 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002702 Result += "\n";
2703 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002704 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002705 Result += ", 0\n";
2706 if (CDecl->getNumIntfRefProtocols() > 0) {
2707 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2708 Result += CDecl->getName();
2709 Result += ",0,0\n";
2710 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002711 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002712 Result += "\t,0,0,0,0\n";
2713 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002714
2715 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002716 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2717 Result += CDecl->getName();
2718 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2719 "{\n\t&_OBJC_METACLASS_";
2720 Result += CDecl->getName();
2721 if (SuperClass) {
2722 Result += ", \"";
2723 Result += SuperClass->getName();
2724 Result += "\", \"";
2725 Result += CDecl->getName();
2726 Result += "\"";
2727 }
2728 else {
2729 Result += ", 0, \"";
2730 Result += CDecl->getName();
2731 Result += "\"";
2732 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002733 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002734 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002735 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002736 Result += ",0";
2737 else {
2738 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002739 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002740 Result += CDecl->getName();
2741 Result += ")";
2742 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002743 if (NumIvars > 0) {
2744 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2745 Result += CDecl->getName();
2746 Result += "\n\t";
2747 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002748 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002749 Result += ",0";
2750 if (IDecl->getNumInstanceMethods() > 0) {
2751 Result += ", &_OBJC_INSTANCE_METHODS_";
2752 Result += CDecl->getName();
2753 Result += ", 0\n\t";
2754 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002755 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002756 Result += ",0,0";
2757 if (CDecl->getNumIntfRefProtocols() > 0) {
2758 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2759 Result += CDecl->getName();
2760 Result += ", 0,0\n";
2761 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002762 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += ",0,0,0\n";
2764 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002765}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002766
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002767/// RewriteImplementations - This routine rewrites all method implementations
2768/// and emits meta-data.
2769
2770void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002771 int ClsDefCount = ClassImplementation.size();
2772 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002773
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002774 if (ClsDefCount == 0 && CatDefCount == 0)
2775 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002776 // Rewrite implemented methods
2777 for (int i = 0; i < ClsDefCount; i++)
2778 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002779
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002780 for (int i = 0; i < CatDefCount; i++)
2781 RewriteImplementationDecl(CategoryImplementation[i]);
2782
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002783 // This is needed for use of offsetof
2784 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002785
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002787 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002788 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002789
2790 // For each implemented category, write out all its meta data.
2791 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002792 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002793
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002794 // Write objc_symtab metadata
2795 /*
2796 struct _objc_symtab
2797 {
2798 long sel_ref_cnt;
2799 SEL *refs;
2800 short cls_def_cnt;
2801 short cat_def_cnt;
2802 void *defs[cls_def_cnt + cat_def_cnt];
2803 };
2804 */
2805
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002806 Result += "\nstruct _objc_symtab {\n";
2807 Result += "\tlong sel_ref_cnt;\n";
2808 Result += "\tSEL *refs;\n";
2809 Result += "\tshort cls_def_cnt;\n";
2810 Result += "\tshort cat_def_cnt;\n";
2811 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2812 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002813
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002814 Result += "static struct _objc_symtab "
2815 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2816 Result += "\t0, 0, " + utostr(ClsDefCount)
2817 + ", " + utostr(CatDefCount) + "\n";
2818 for (int i = 0; i < ClsDefCount; i++) {
2819 Result += "\t,&_OBJC_CLASS_";
2820 Result += ClassImplementation[i]->getName();
2821 Result += "\n";
2822 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002823
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002824 for (int i = 0; i < CatDefCount; i++) {
2825 Result += "\t,&_OBJC_CATEGORY_";
2826 Result += CategoryImplementation[i]->getClassInterface()->getName();
2827 Result += "_";
2828 Result += CategoryImplementation[i]->getName();
2829 Result += "\n";
2830 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002831
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002833
2834 // Write objc_module metadata
2835
2836 /*
2837 struct _objc_module {
2838 long version;
2839 long size;
2840 const char *name;
2841 struct _objc_symtab *symtab;
2842 }
2843 */
2844
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002845 Result += "\nstruct _objc_module {\n";
2846 Result += "\tlong version;\n";
2847 Result += "\tlong size;\n";
2848 Result += "\tconst char *name;\n";
2849 Result += "\tstruct _objc_symtab *symtab;\n";
2850 Result += "};\n\n";
2851 Result += "static struct _objc_module "
2852 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002853 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2854 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002856
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002857}
Chris Lattner311ff022007-10-16 22:36:42 +00002858