blob: b111e09a32b42e0a2aeafe6dcef4940bc46ba380 [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 Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000043 llvm::SmallVector<Stmt *, 32> Stmts;
44 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000045
46 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000047 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000048 FunctionDecl *MsgSendStretFunctionDecl;
49 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000050 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000051 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000052 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000053 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000054 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000055 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 // ObjC string constant support.
58 FileVarDecl *ConstantStringClassReference;
59 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000060
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000061 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000062 int BcLabelCount;
63
Steve Naroff874e2322007-11-15 10:28:18 +000064 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000065 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 RecordDecl *SuperStructDecl;
67
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000068 // Needed for header files being rewritten
69 bool IsHeader;
70
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000071 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000072 public:
Ted Kremenek95041a22007-12-19 22:51:13 +000073 void Initialize(ASTContext &context) {
Chris Lattner01c57482007-10-17 22:35:30 +000074 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000075 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000076 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000077 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000078 MsgSendStretFunctionDecl = 0;
79 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000080 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000081 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000082 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000083 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000084 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000085 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000086 ConstantStringClassReference = 0;
87 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000088 CurMethodDecl = 0;
89 SuperStructDecl = 0;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000090 BcLabelCount = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000091
Chris Lattner26de4652007-12-02 01:13:47 +000092 // Get the ID and start/end of the main file.
Ted Kremenek95041a22007-12-19 22:51:13 +000093 MainFileID = SM->getMainFileID();
Chris Lattner26de4652007-12-02 01:13:47 +000094 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
95 MainFileStart = MainBuf->getBufferStart();
96 MainFileEnd = MainBuf->getBufferEnd();
97
98
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000099 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +0000100 // declaring objc_selector outside the parameter list removes a silly
101 // scope related warning...
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000102 const char *s = "#pragma once\n"
103 "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000104 "#ifndef OBJC_SUPER\n"
105 "struct objc_super { struct objc_object *o; "
106 "struct objc_object *superClass; };\n"
107 "#define OBJC_SUPER\n"
108 "#endif\n"
109 "#ifndef _REWRITER_typedef_Protocol\n"
110 "typedef struct objc_object Protocol;\n"
111 "#define _REWRITER_typedef_Protocol\n"
112 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000113 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000114 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000115 "extern struct objc_object *objc_msgSendSuper"
116 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000117 "extern struct objc_object *objc_msgSend_stret"
118 "(struct objc_object *, struct objc_selector *, ...);\n"
119 "extern struct objc_object *objc_msgSendSuper_stret"
120 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000121 "extern struct objc_object *objc_msgSend_fpret"
122 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000123 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000124 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000125 "extern struct objc_object *objc_getMetaClass"
126 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000127 "extern void objc_exception_throw(struct objc_object *);\n"
128 "extern void objc_exception_try_enter(void *);\n"
129 "extern void objc_exception_try_exit(void *);\n"
130 "extern struct objc_object *objc_exception_extract(void *);\n"
131 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000132 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000133 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000134 "#include <objc/objc.h>\n"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000135 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000136 "struct __objcFastEnumerationState {\n\t"
137 "unsigned long state;\n\t"
138 "id *itemsPtr;\n\t"
139 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahanian88007422008-01-10 23:04:06 +0000140 "unsigned long extra[5];\n};\n"
141 "#define __FASTENUMERATIONSTATE\n"
142 "#endif\n";
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000143 if (IsHeader) {
144 // insert the whole string when rewriting a header file
145 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
146 s, strlen(s));
147 }
148 else {
149 // Not rewriting header, exclude the #pragma once pragma
150 const char *p = s + strlen("#pragma once\n");
151 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
152 p, strlen(p));
153 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000154 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000155
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // Top Level Driver code.
157 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000158 void HandleDeclInMainFile(Decl *D);
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000159 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {IsHeader = isHeader;}
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 ~RewriteTest();
161
162 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000163 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000164 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000166 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
167 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000168 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000169 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
170 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
171 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
172 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
173 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
174 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000175 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000176 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000177 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000178 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000179 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000180
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000182 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000183 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000184 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000185 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000186 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000187 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000188 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000189 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
190 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
191 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
192 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000193 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000194 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
195 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000196 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000197 Stmt *RewriteBreakStmt(BreakStmt *S);
198 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000199 void SynthCountByEnumWithState(std::string &buf);
200
Steve Naroff09b266e2007-10-30 23:14:51 +0000201 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000202 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000203 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000204 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000205 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000206 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000207 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000208 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000209 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000210 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000211
Chris Lattnerf04da132007-10-24 17:06:59 +0000212 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000213 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000214 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000215
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000217 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000218
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
220 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000221 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000222 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000223 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000224 const char *ClassName,
225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228 int NumProtocols,
229 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000230 const char *ClassName,
231 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000232 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000233 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000234 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
235 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000236 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000237 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000238 };
239}
240
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000241static bool IsHeaderFile(const std::string &Filename) {
242 std::string::size_type DotPos = Filename.rfind('.');
243
244 if (DotPos == std::string::npos) {
245 // no file extension
246 return false;
247 }
248
249 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
250 // C header: .h
251 // C++ header: .hh or .H;
252 return Ext == "h" || Ext == "hh" || Ext == "H";
253}
254
255ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
256 Diagnostic &Diags) {
257 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattnere365c502007-11-30 22:25:36 +0000258}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260//===----------------------------------------------------------------------===//
261// Top Level Driver Code
262//===----------------------------------------------------------------------===//
263
Chris Lattner8a12c272007-10-11 18:38:32 +0000264void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000265 // Two cases: either the decl could be in the main file, or it could be in a
266 // #included file. If the former, rewrite it now. If the later, check to see
267 // if we rewrote the #include/#import.
268 SourceLocation Loc = D->getLocation();
269 Loc = SM->getLogicalLoc(Loc);
270
271 // If this is for a builtin, ignore it.
272 if (Loc.isInvalid()) return;
273
Steve Naroffebf2b562007-10-23 23:50:29 +0000274 // Look for built-in declarations that we need to refer during the rewrite.
275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000276 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000277 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
278 // declared in <Foundation/NSString.h>
279 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
280 ConstantStringClassReference = FVD;
281 return;
282 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000284 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000286 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000288 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 } else if (ObjCForwardProtocolDecl *FP =
290 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000291 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000292 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000294 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
295 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000296}
297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298/// HandleDeclInMainFile - This is called for each top-level decl defined in the
299/// main file of the input.
300void RewriteTest::HandleDeclInMainFile(Decl *D) {
301 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
302 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000303 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000304
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000306 if (Stmt *Body = MD->getBody()) {
307 //Body->dump();
308 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000309 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000310 CurMethodDecl = 0;
311 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000312 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000313 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000314 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000315 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000316 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000317 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000318 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000319 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000320 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000321 if (VD->getInit())
322 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
323 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000324 // Nothing yet.
325}
326
327RewriteTest::~RewriteTest() {
328 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000329
330 // Rewrite tabs if we care.
331 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000332
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000333 RewriteInclude();
334
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000335 // Rewrite Objective-c meta data*
336 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000337 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000338
Chris Lattnerf04da132007-10-24 17:06:59 +0000339 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
340 // we are done.
341 if (const RewriteBuffer *RewriteBuf =
342 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000343 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000344 std::string S(RewriteBuf->begin(), RewriteBuf->end());
345 printf("%s\n", S.c_str());
346 } else {
347 printf("No changes\n");
348 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000349 // Emit metadata.
350 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000351}
352
Chris Lattnerf04da132007-10-24 17:06:59 +0000353//===----------------------------------------------------------------------===//
354// Syntactic (non-AST) Rewriting Code
355//===----------------------------------------------------------------------===//
356
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000357void RewriteTest::RewriteInclude() {
358 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
359 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
360 const char *MainBufStart = MainBuf.first;
361 const char *MainBufEnd = MainBuf.second;
362 size_t ImportLen = strlen("import");
363 size_t IncludeLen = strlen("include");
364
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000365 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000366 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
367 if (*BufPtr == '#') {
368 if (++BufPtr == MainBufEnd)
369 return;
370 while (*BufPtr == ' ' || *BufPtr == '\t')
371 if (++BufPtr == MainBufEnd)
372 return;
373 if (!strncmp(BufPtr, "import", ImportLen)) {
374 // replace import with include
375 SourceLocation ImportLoc =
376 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
377 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
378 BufPtr += ImportLen;
379 }
380 }
381 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000382}
383
Chris Lattnerf04da132007-10-24 17:06:59 +0000384void RewriteTest::RewriteTabs() {
385 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
386 const char *MainBufStart = MainBuf.first;
387 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000388
Chris Lattnerf04da132007-10-24 17:06:59 +0000389 // Loop over the whole file, looking for tabs.
390 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
391 if (*BufPtr != '\t')
392 continue;
393
394 // Okay, we found a tab. This tab will turn into at least one character,
395 // but it depends on which 'virtual column' it is in. Compute that now.
396 unsigned VCol = 0;
397 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
398 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
399 ++VCol;
400
401 // Okay, now that we know the virtual column, we know how many spaces to
402 // insert. We assume 8-character tab-stops.
403 unsigned Spaces = 8-(VCol & 7);
404
405 // Get the location of the tab.
406 SourceLocation TabLoc =
407 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
408
409 // Rewrite the single tab character into a sequence of spaces.
410 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
411 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000412}
413
414
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000416 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000417 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000418
419 // Get the start location and compute the semi location.
420 SourceLocation startLoc = ClassDecl->getLocation();
421 const char *startBuf = SM->getCharacterData(startLoc);
422 const char *semiPtr = strchr(startBuf, ';');
423
424 // Translate to typedef's that forward reference structs with the same name
425 // as the class. As a convenience, we include the original declaration
426 // as a comment.
427 std::string typedefString;
428 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000429 typedefString.append(startBuf, semiPtr-startBuf+1);
430 typedefString += "\n";
431 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000432 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000433 typedefString += "#ifndef _REWRITER_typedef_";
434 typedefString += ForwardDecl->getName();
435 typedefString += "\n";
436 typedefString += "#define _REWRITER_typedef_";
437 typedefString += ForwardDecl->getName();
438 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000439 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000440 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000441 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000442 }
443
444 // Replace the @class with typedefs corresponding to the classes.
445 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
446 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000447}
448
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000449void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000450 SourceLocation LocStart = Method->getLocStart();
451 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000452
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000453 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
454 Rewrite.InsertText(LocStart, "/* ", 3);
455 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
456 } else {
457 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000458 }
459}
460
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000461void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000462{
463 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000464 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000465 SourceLocation Loc = Property->getLocation();
466
467 Rewrite.ReplaceText(Loc, 0, "// ", 3);
468
469 // FIXME: handle properties that are declared across multiple lines.
470 }
471}
472
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000473void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000474 SourceLocation LocStart = CatDecl->getLocStart();
475
476 // FIXME: handle category headers that are declared across multiple lines.
477 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
478
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000479 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000480 E = CatDecl->instmeth_end(); I != E; ++I)
481 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000482 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000483 E = CatDecl->classmeth_end(); I != E; ++I)
484 RewriteMethodDeclaration(*I);
485
Steve Naroff423cb562007-10-30 13:30:57 +0000486 // Lastly, comment out the @end.
487 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
488}
489
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000490void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000491 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000492
Steve Naroff752d6ef2007-10-30 16:42:30 +0000493 SourceLocation LocStart = PDecl->getLocStart();
494
495 // FIXME: handle protocol headers that are declared across multiple lines.
496 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
497
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000498 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000499 E = PDecl->instmeth_end(); I != E; ++I)
500 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000501 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000502 E = PDecl->classmeth_end(); I != E; ++I)
503 RewriteMethodDeclaration(*I);
504
Steve Naroff752d6ef2007-10-30 16:42:30 +0000505 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000506 SourceLocation LocEnd = PDecl->getAtEndLoc();
507 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000508
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000509 // Must comment out @optional/@required
510 const char *startBuf = SM->getCharacterData(LocStart);
511 const char *endBuf = SM->getCharacterData(LocEnd);
512 for (const char *p = startBuf; p < endBuf; p++) {
513 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
514 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000515 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000516 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
517 CommentedOptional.c_str(), CommentedOptional.size());
518
519 }
520 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
521 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000522 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000523 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
524 CommentedRequired.c_str(), CommentedRequired.size());
525
526 }
527 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000528}
529
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000530void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000531 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000532 if (LocStart.isInvalid())
533 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000534 // FIXME: handle forward protocol that are declared across multiple lines.
535 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
536}
537
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000539 std::string &ResultStr) {
540 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000541 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000542 ResultStr += "id";
543 else
544 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000545 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000546
547 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000548 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000549
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000550 if (OMD->isInstance())
551 NameStr += "_I_";
552 else
553 NameStr += "_C_";
554
555 NameStr += OMD->getClassInterface()->getName();
556 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557
558 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000559 if (ObjCCategoryImplDecl *CID =
560 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000561 NameStr += CID->getName();
562 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000563 }
564 // Append selector names, replacing ':' with '_'
565 const char *selName = OMD->getSelector().getName().c_str();
566 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000567 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000568 else {
569 std::string selString = OMD->getSelector().getName();
570 int len = selString.size();
571 for (int i = 0; i < len; i++)
572 if (selString[i] == ':')
573 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000574 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000575 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000576 // Remember this name for metadata emission
577 MethodInternalNames[OMD] = NameStr;
578 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000579
580 // Rewrite arguments
581 ResultStr += "(";
582
583 // invisible arguments
584 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000586 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000587 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000588 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000589 ResultStr += selfTy.getAsString();
590 }
591 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000593
594 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000596 ResultStr += " _cmd";
597
598 // Method arguments.
599 for (int i = 0; i < OMD->getNumParams(); i++) {
600 ParmVarDecl *PDecl = OMD->getParamDecl(i);
601 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000602 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000603 ResultStr += "id";
604 else
605 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000606 ResultStr += " ";
607 ResultStr += PDecl->getName();
608 }
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000609 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000610
611}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000612void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000613 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
614 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000615
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000616 if (IMD)
617 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
618 else
619 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000620
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000621 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000622 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
623 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000624 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000625 ObjCMethodDecl *OMD = *I;
626 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000627 SourceLocation LocStart = OMD->getLocStart();
628 SourceLocation LocEnd = OMD->getBody()->getLocStart();
629
630 const char *startBuf = SM->getCharacterData(LocStart);
631 const char *endBuf = SM->getCharacterData(LocEnd);
632 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
633 ResultStr.c_str(), ResultStr.size());
634 }
635
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000636 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000637 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
638 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000639 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 ObjCMethodDecl *OMD = *I;
641 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000642 SourceLocation LocStart = OMD->getLocStart();
643 SourceLocation LocEnd = OMD->getBody()->getLocStart();
644
645 const char *startBuf = SM->getCharacterData(LocStart);
646 const char *endBuf = SM->getCharacterData(LocEnd);
647 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
648 ResultStr.c_str(), ResultStr.size());
649 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000650 if (IMD)
651 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
652 else
653 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000654}
655
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000656void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000657 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000658 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000659 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000660 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000661 ResultStr += ClassDecl->getName();
662 ResultStr += "\n";
663 ResultStr += "#define _REWRITER_typedef_";
664 ResultStr += ClassDecl->getName();
665 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000666 ResultStr += "typedef struct ";
667 ResultStr += ClassDecl->getName();
668 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000669 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000670 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000671
672 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000674 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000676
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000677 RewriteProperties(ClassDecl->getNumPropertyDecl(),
678 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000679 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000680 E = ClassDecl->instmeth_end(); I != E; ++I)
681 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000682 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000683 E = ClassDecl->classmeth_end(); I != E; ++I)
684 RewriteMethodDeclaration(*I);
685
Steve Naroff2feac5e2007-10-30 03:43:13 +0000686 // Lastly, comment out the @end.
687 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000688}
689
Steve Naroff7e3411b2007-11-15 02:58:25 +0000690Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000692 if (IV->isFreeIvar()) {
693 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
694 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000695 if (Rewrite.ReplaceStmt(IV, Replacement)) {
696 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000697 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
698 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000699 SourceRange Range = IV->getSourceRange();
700 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000701 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000702 delete IV;
703 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000704 } else {
705 if (CurMethodDecl) {
706 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000708 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
709 IdentifierInfo *II = intT->getDecl()->getIdentifier();
710 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
711 II, 0);
712 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
713
714 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
715 // Don't forget the parens to enforce the proper binding.
716 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000717 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
718 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000719 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
720 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000721 SourceRange Range = IV->getBase()->getSourceRange();
722 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000723 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000724 delete IV->getBase();
725 return PE;
726 }
727 }
728 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000729 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000730 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000731}
732
Chris Lattnerf04da132007-10-24 17:06:59 +0000733//===----------------------------------------------------------------------===//
734// Function Body / Expression rewriting
735//===----------------------------------------------------------------------===//
736
Steve Narofff3473a72007-11-09 15:20:18 +0000737Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000738 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
739 isa<DoStmt>(S) || isa<ForStmt>(S))
740 Stmts.push_back(S);
741 else if (isa<ObjCForCollectionStmt>(S)) {
742 Stmts.push_back(S);
743 ObjCBcLabelNo.push_back(++BcLabelCount);
744 }
745
Chris Lattner311ff022007-10-16 22:36:42 +0000746 // Otherwise, just rewrite all children.
747 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
748 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000749 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000750 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000751 if (newStmt)
752 *CI = newStmt;
753 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000754
755 // Handle specific things.
756 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
757 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000758
759 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
760 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000761
762 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
763 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000764
765 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
766 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000767
Steve Naroff934f2762007-10-24 22:48:43 +0000768 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
769 // Before we rewrite it, put the original message expression in a comment.
770 SourceLocation startLoc = MessExpr->getLocStart();
771 SourceLocation endLoc = MessExpr->getLocEnd();
772
773 const char *startBuf = SM->getCharacterData(startLoc);
774 const char *endBuf = SM->getCharacterData(endLoc);
775
776 std::string messString;
777 messString += "// ";
778 messString.append(startBuf, endBuf-startBuf+1);
779 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000780
Steve Naroff934f2762007-10-24 22:48:43 +0000781 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
782 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
783 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000784 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000785 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000786 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000787
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000788 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
789 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000790
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000791 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
792 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000793
794 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
795 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000796
797 if (ObjCForCollectionStmt *StmtForCollection =
798 dyn_cast<ObjCForCollectionStmt>(S))
799 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000800 if (BreakStmt *StmtBreakStmt =
801 dyn_cast<BreakStmt>(S))
802 return RewriteBreakStmt(StmtBreakStmt);
803 if (ContinueStmt *StmtContinueStmt =
804 dyn_cast<ContinueStmt>(S))
805 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000806
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000807 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
808 isa<DoStmt>(S) || isa<ForStmt>(S)) {
809 assert(!Stmts.empty() && "Statement stack is empty");
810 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
811 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
812 && "Statement stack mismatch");
813 Stmts.pop_back();
814 }
Steve Naroff874e2322007-11-15 10:28:18 +0000815#if 0
816 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
817 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
818 // Get the new text.
819 std::ostringstream Buf;
820 Replacement->printPretty(Buf);
821 const std::string &Str = Buf.str();
822
823 printf("CAST = %s\n", &Str[0]);
824 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
825 delete S;
826 return Replacement;
827 }
828#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000829 // Return this stmt unmodified.
830 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000831}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000832
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000833/// SynthCountByEnumWithState - To print:
834/// ((unsigned int (*)
835/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
836/// (void *)objc_msgSend)((id)l_collection,
837/// sel_registerName(
838/// "countByEnumeratingWithState:objects:count:"),
839/// &enumState,
840/// (id *)items, (unsigned int)16)
841///
842void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
843 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
844 "id *, unsigned int))(void *)objc_msgSend)";
845 buf += "\n\t\t";
846 buf += "((id)l_collection,\n\t\t";
847 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
848 buf += "\n\t\t";
849 buf += "&enumState, "
850 "(id *)items, (unsigned int)16)";
851}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000852
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000853/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
854/// statement to exit to its outer synthesized loop.
855///
856Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
857 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
858 return S;
859 // replace break with goto __break_label
860 std::string buf;
861
862 SourceLocation startLoc = S->getLocStart();
863 buf = "goto __break_label_";
864 buf += utostr(ObjCBcLabelNo.back());
865 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
866
867 return 0;
868}
869
870/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
871/// statement to continue with its inner synthesized loop.
872///
873Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
874 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
875 return S;
876 // replace continue with goto __continue_label
877 std::string buf;
878
879 SourceLocation startLoc = S->getLocStart();
880 buf = "goto __continue_label_";
881 buf += utostr(ObjCBcLabelNo.back());
882 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
883
884 return 0;
885}
886
Fariborz Jahaniane84b0402008-01-09 01:25:54 +0000887/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000888/// It rewrites:
889/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000890
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000891/// Into:
892/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000893/// type elem;
894/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000895/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000896/// id l_collection = (id)collection;
897/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
898/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000899/// if (limit) {
900/// unsigned long startMutations = *enumState.mutationsPtr;
901/// do {
902/// unsigned long counter = 0;
903/// do {
904/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000905/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000906/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000907/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000908/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000909/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000910/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
911/// objects:items count:16]);
912/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000913/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000914/// }
915/// else
916/// elem = nil;
917/// }
918///
919Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000920 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
921 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
922 "ObjCForCollectionStmt Statement stack mismatch");
923 assert(!ObjCBcLabelNo.empty() &&
924 "ObjCForCollectionStmt - Label No stack empty");
925
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000926 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000927 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000928 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000929 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000930 std::string buf;
931 buf = "\n{\n\t";
932 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
933 // type elem;
934 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000935 elementTypeAsString = ElementType.getAsString();
936 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000937 buf += " ";
938 elementName = DS->getDecl()->getName();
939 buf += elementName;
940 buf += ";\n\t";
941 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000942 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000943 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000944 elementTypeAsString = DR->getDecl()->getType().getAsString();
945 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000946 else
947 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
948
949 // struct __objcFastEnumerationState enumState = { 0 };
950 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
951 // id items[16];
952 buf += "id items[16];\n\t";
953 // id l_collection = (id)
954 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +0000955 // Find start location of 'collection' the hard way!
956 const char *startCollectionBuf = startBuf;
957 startCollectionBuf += 3; // skip 'for'
958 startCollectionBuf = strchr(startCollectionBuf, '(');
959 startCollectionBuf++; // skip '('
960 // find 'in' and skip it.
961 while (*startCollectionBuf != ' ' ||
962 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
963 (*(startCollectionBuf+3) != ' ' &&
964 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
965 startCollectionBuf++;
966 startCollectionBuf += 3;
967
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000968 // Replace: "for (type element in" with string constructed thus far.
969 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
970 buf.c_str(), buf.size());
971 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +0000972 SourceLocation rightParenLoc = S->getRParenLoc();
973 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
974 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000975 buf = ";\n\t";
976
977 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
978 // objects:items count:16];
979 // which is synthesized into:
980 // unsigned int limit =
981 // ((unsigned int (*)
982 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
983 // (void *)objc_msgSend)((id)l_collection,
984 // sel_registerName(
985 // "countByEnumeratingWithState:objects:count:"),
986 // (struct __objcFastEnumerationState *)&state,
987 // (id *)items, (unsigned int)16);
988 buf += "unsigned long limit =\n\t\t";
989 SynthCountByEnumWithState(buf);
990 buf += ";\n\t";
991 /// if (limit) {
992 /// unsigned long startMutations = *enumState.mutationsPtr;
993 /// do {
994 /// unsigned long counter = 0;
995 /// do {
996 /// if (startMutations != *enumState.mutationsPtr)
997 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000998 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000999 buf += "if (limit) {\n\t";
1000 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1001 buf += "do {\n\t\t";
1002 buf += "unsigned long counter = 0;\n\t\t";
1003 buf += "do {\n\t\t\t";
1004 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1005 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1006 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001007 buf += " = (";
1008 buf += elementTypeAsString;
1009 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001010 // Replace ')' in for '(' type elem in collection ')' with all of these.
1011 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1012
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001013 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001014 /// } while (counter < limit);
1015 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1016 /// objects:items count:16]);
1017 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001018 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001019 /// }
1020 /// else
1021 /// elem = nil;
1022 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001023 ///
1024 buf = ";\n\t";
1025 buf += "__continue_label_";
1026 buf += utostr(ObjCBcLabelNo.back());
1027 buf += ": ;";
1028 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001029 buf += "} while (counter < limit);\n\t";
1030 buf += "} while (limit = ";
1031 SynthCountByEnumWithState(buf);
1032 buf += ");\n\t";
1033 buf += elementName;
1034 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001035 buf += "__break_label_";
1036 buf += utostr(ObjCBcLabelNo.back());
1037 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001038 buf += "}\n\t";
1039 buf += "else\n\t\t";
1040 buf += elementName;
1041 buf += " = nil;\n";
1042 buf += "}\n";
1043 // Insert all these *after* the statement body.
1044 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1045 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1046 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1047 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001048 Stmts.pop_back();
1049 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001050
1051 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001052}
1053
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001054Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001055 // Get the start location and compute the semi location.
1056 SourceLocation startLoc = S->getLocStart();
1057 const char *startBuf = SM->getCharacterData(startLoc);
1058
1059 assert((*startBuf == '@') && "bogus @try location");
1060
1061 std::string buf;
1062 // declare a new scope with two variables, _stack and _rethrow.
1063 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1064 buf += "int buf[18/*32-bit i386*/];\n";
1065 buf += "char *pointers[4];} _stack;\n";
1066 buf += "id volatile _rethrow = 0;\n";
1067 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001068 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001069
1070 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1071
1072 startLoc = S->getTryBody()->getLocEnd();
1073 startBuf = SM->getCharacterData(startLoc);
1074
1075 assert((*startBuf == '}') && "bogus @try block");
1076
1077 SourceLocation lastCurlyLoc = startLoc;
1078
1079 startLoc = startLoc.getFileLocWithOffset(1);
1080 buf = " /* @catch begin */ else {\n";
1081 buf += " id _caught = objc_exception_extract(&_stack);\n";
1082 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001083 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001084 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1085 buf += " else { /* @catch continue */";
1086
Chris Lattner28d1fe82007-11-08 04:41:51 +00001087 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001088
1089 bool sawIdTypedCatch = false;
1090 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001091 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001092 while (catchList) {
1093 Stmt *catchStmt = catchList->getCatchParamStmt();
1094
1095 if (catchList == S->getCatchStmts())
1096 buf = "if ("; // we are generating code for the first catch clause
1097 else
1098 buf = "else if (";
1099 startLoc = catchList->getLocStart();
1100 startBuf = SM->getCharacterData(startLoc);
1101
1102 assert((*startBuf == '@') && "bogus @catch location");
1103
1104 const char *lParenLoc = strchr(startBuf, '(');
1105
1106 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1107 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001108 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001109 buf += "1) { ";
1110 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1111 buf.c_str(), buf.size());
1112 sawIdTypedCatch = true;
1113 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001114 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001115
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001116 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001117 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001118 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001119 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001120 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +00001121 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1122 buf.c_str(), buf.size());
1123 }
1124 }
1125 // Now rewrite the body...
1126 lastCatchBody = catchList->getCatchBody();
1127 SourceLocation rParenLoc = catchList->getRParenLoc();
1128 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1129 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1130 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1131 assert((*rParenBuf == ')') && "bogus @catch paren location");
1132 assert((*bodyBuf == '{') && "bogus @catch body location");
1133
1134 buf = " = _caught;";
1135 // Here we replace ") {" with "= _caught;" (which initializes and
1136 // declares the @catch parameter).
1137 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1138 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001139 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001140 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001141 }
Steve Naroff75730982007-11-07 04:08:17 +00001142 catchList = catchList->getNextCatchStmt();
1143 }
1144 // Complete the catch list...
1145 if (lastCatchBody) {
1146 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1147 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1148 assert((*bodyBuf == '}') && "bogus @catch body location");
1149 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1150 buf = " } } /* @catch end */\n";
1151
Chris Lattner28d1fe82007-11-08 04:41:51 +00001152 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001153
1154 // Set lastCurlyLoc
1155 lastCurlyLoc = lastCatchBody->getLocEnd();
1156 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001157 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001158 startLoc = finalStmt->getLocStart();
1159 startBuf = SM->getCharacterData(startLoc);
1160 assert((*startBuf == '@') && "bogus @finally start");
1161
1162 buf = "/* @finally */";
1163 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1164
1165 Stmt *body = finalStmt->getFinallyBody();
1166 SourceLocation startLoc = body->getLocStart();
1167 SourceLocation endLoc = body->getLocEnd();
1168 const char *startBuf = SM->getCharacterData(startLoc);
1169 const char *endBuf = SM->getCharacterData(endLoc);
1170 assert((*startBuf == '{') && "bogus @finally body location");
1171 assert((*endBuf == '}') && "bogus @finally body location");
1172
1173 startLoc = startLoc.getFileLocWithOffset(1);
1174 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001175 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001176 endLoc = endLoc.getFileLocWithOffset(-1);
1177 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001178 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001179
1180 // Set lastCurlyLoc
1181 lastCurlyLoc = body->getLocEnd();
1182 }
1183 // Now emit the final closing curly brace...
1184 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1185 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001186 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001187 return 0;
1188}
1189
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001191 return 0;
1192}
1193
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001195 return 0;
1196}
1197
Steve Naroff2bd03922007-11-07 15:32:26 +00001198// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1199// the throw expression is typically a message expression that's already
1200// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001202 // Get the start location and compute the semi location.
1203 SourceLocation startLoc = S->getLocStart();
1204 const char *startBuf = SM->getCharacterData(startLoc);
1205
1206 assert((*startBuf == '@') && "bogus @throw location");
1207
1208 std::string buf;
1209 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001210 if (S->getThrowExpr())
1211 buf = "objc_exception_throw(";
1212 else // add an implicit argument
1213 buf = "objc_exception_throw(_caught";
Steve Naroff2bd03922007-11-07 15:32:26 +00001214 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1215 const char *semiBuf = strchr(startBuf, ';');
1216 assert((*semiBuf == ';') && "@throw: can't find ';'");
1217 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1218 buf = ");";
1219 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1220 return 0;
1221}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001222
Chris Lattnere64b7772007-10-24 16:57:36 +00001223Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001224 // Create a new string expression.
1225 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001226 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001227 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001228 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1229 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001230 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +00001231 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1232 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001233 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1234 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +00001235 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001236 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +00001237 }
1238
Chris Lattner07506182007-11-30 22:53:43 +00001239 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001240 delete Exp;
1241 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001242}
1243
Steve Naroffb42f8412007-11-05 14:50:49 +00001244Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1245 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1246 // Create a call to sel_registerName("selName").
1247 llvm::SmallVector<Expr*, 8> SelExprs;
1248 QualType argType = Context->getPointerType(Context->CharTy);
1249 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1250 Exp->getSelector().getName().size(),
1251 false, argType, SourceLocation(),
1252 SourceLocation()));
1253 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1254 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001255 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1256 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001257 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1258 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001259 SourceRange Range = Exp->getSourceRange();
1260 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001261 }
Steve Naroffb42f8412007-11-05 14:50:49 +00001262 delete Exp;
1263 return SelExp;
1264}
1265
Steve Naroff934f2762007-10-24 22:48:43 +00001266CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1267 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001268 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001269 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001270
1271 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001272 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001273
1274 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001275 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001276 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1277
1278 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001279
Steve Naroff934f2762007-10-24 22:48:43 +00001280 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1281}
1282
Steve Naroffd5255f52007-11-01 13:24:47 +00001283static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1284 const char *&startRef, const char *&endRef) {
1285 while (startBuf < endBuf) {
1286 if (*startBuf == '<')
1287 startRef = startBuf; // mark the start.
1288 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001289 if (startRef && *startRef == '<') {
1290 endRef = startBuf; // mark the end.
1291 return true;
1292 }
1293 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001294 }
1295 startBuf++;
1296 }
1297 return false;
1298}
1299
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001300static void scanToNextArgument(const char *&argRef) {
1301 int angle = 0;
1302 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1303 if (*argRef == '<')
1304 angle++;
1305 else if (*argRef == '>')
1306 angle--;
1307 argRef++;
1308 }
1309 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1310}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001311
Steve Naroffd5255f52007-11-01 13:24:47 +00001312bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001313
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001314 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001315 return true;
1316
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001317 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001318 return true;
1319
Steve Naroffd5255f52007-11-01 13:24:47 +00001320 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001321 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001322 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001323 return true; // we have "Class <Protocol> *".
1324 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001325 return false;
1326}
1327
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001328void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001329 SourceLocation Loc;
1330 QualType Type;
1331 const FunctionTypeProto *proto = 0;
1332 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1333 Loc = VD->getLocation();
1334 Type = VD->getType();
1335 }
1336 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1337 Loc = FD->getLocation();
1338 // Check for ObjC 'id' and class types that have been adorned with protocol
1339 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1340 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1341 assert(funcType && "missing function type");
1342 proto = dyn_cast<FunctionTypeProto>(funcType);
1343 if (!proto)
1344 return;
1345 Type = proto->getResultType();
1346 }
1347 else
1348 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001349
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001350 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001351 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001352
1353 const char *endBuf = SM->getCharacterData(Loc);
1354 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001355 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001356 startBuf--; // scan backward (from the decl location) for return type.
1357 const char *startRef = 0, *endRef = 0;
1358 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1359 // Get the locations of the startRef, endRef.
1360 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1361 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1362 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001363 Rewrite.InsertText(LessLoc, "/*", 2);
1364 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001365 }
1366 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001367 if (!proto)
1368 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001369 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001370 const char *startBuf = SM->getCharacterData(Loc);
1371 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001372 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1373 if (needToScanForQualifiers(proto->getArgType(i))) {
1374 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001375
Steve Naroffd5255f52007-11-01 13:24:47 +00001376 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001377 // scan forward (from the decl location) for argument types.
1378 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001379 const char *startRef = 0, *endRef = 0;
1380 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1381 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001382 SourceLocation LessLoc =
1383 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1384 SourceLocation GreaterLoc =
1385 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001386 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001387 Rewrite.InsertText(LessLoc, "/*", 2);
1388 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001389 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001390 startBuf = ++endBuf;
1391 }
1392 else {
1393 while (*startBuf != ')' && *startBuf != ',')
1394 startBuf++; // scan forward (from the decl location) for argument types.
1395 startBuf++;
1396 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001397 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001398}
1399
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001400// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1401void RewriteTest::SynthSelGetUidFunctionDecl() {
1402 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1403 llvm::SmallVector<QualType, 16> ArgTys;
1404 ArgTys.push_back(Context->getPointerType(
1405 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001406 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001407 &ArgTys[0], ArgTys.size(),
1408 false /*isVariadic*/);
1409 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1410 SelGetUidIdent, getFuncType,
1411 FunctionDecl::Extern, false, 0);
1412}
1413
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001414// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1415void RewriteTest::SynthGetProtocolFunctionDecl() {
1416 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1417 llvm::SmallVector<QualType, 16> ArgTys;
1418 ArgTys.push_back(Context->getPointerType(
1419 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001420 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001421 &ArgTys[0], ArgTys.size(),
1422 false /*isVariadic*/);
1423 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1424 SelGetProtoIdent, getFuncType,
1425 FunctionDecl::Extern, false, 0);
1426}
1427
Steve Naroff09b266e2007-10-30 23:14:51 +00001428void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1429 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001430 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001431 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001432 return;
1433 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001434 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001435}
1436
1437// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1438void RewriteTest::SynthMsgSendFunctionDecl() {
1439 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1440 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001441 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001442 assert(!argT.isNull() && "Can't find 'id' type");
1443 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001444 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001445 assert(!argT.isNull() && "Can't find 'SEL' type");
1446 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001447 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001448 &ArgTys[0], ArgTys.size(),
1449 true /*isVariadic*/);
1450 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1451 msgSendIdent, msgSendType,
1452 FunctionDecl::Extern, false, 0);
1453}
1454
Steve Naroff874e2322007-11-15 10:28:18 +00001455// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1456void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1457 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1458 llvm::SmallVector<QualType, 16> ArgTys;
1459 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1460 &Context->Idents.get("objc_super"), 0);
1461 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1462 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1463 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001464 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001465 assert(!argT.isNull() && "Can't find 'SEL' type");
1466 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001467 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001468 &ArgTys[0], ArgTys.size(),
1469 true /*isVariadic*/);
1470 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1471 msgSendIdent, msgSendType,
1472 FunctionDecl::Extern, false, 0);
1473}
1474
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001475// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1476void RewriteTest::SynthMsgSendStretFunctionDecl() {
1477 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1478 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001479 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001480 assert(!argT.isNull() && "Can't find 'id' type");
1481 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001482 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001483 assert(!argT.isNull() && "Can't find 'SEL' type");
1484 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001485 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001486 &ArgTys[0], ArgTys.size(),
1487 true /*isVariadic*/);
1488 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1489 msgSendIdent, msgSendType,
1490 FunctionDecl::Extern, false, 0);
1491}
1492
1493// SynthMsgSendSuperStretFunctionDecl -
1494// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1495void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1496 IdentifierInfo *msgSendIdent =
1497 &Context->Idents.get("objc_msgSendSuper_stret");
1498 llvm::SmallVector<QualType, 16> ArgTys;
1499 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1500 &Context->Idents.get("objc_super"), 0);
1501 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1502 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1503 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001504 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001505 assert(!argT.isNull() && "Can't find 'SEL' type");
1506 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001507 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001508 &ArgTys[0], ArgTys.size(),
1509 true /*isVariadic*/);
1510 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1511 msgSendIdent, msgSendType,
1512 FunctionDecl::Extern, false, 0);
1513}
1514
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001515// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1516void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1517 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1518 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001519 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001520 assert(!argT.isNull() && "Can't find 'id' type");
1521 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001522 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001523 assert(!argT.isNull() && "Can't find 'SEL' type");
1524 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001525 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001526 &ArgTys[0], ArgTys.size(),
1527 true /*isVariadic*/);
1528 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1529 msgSendIdent, msgSendType,
1530 FunctionDecl::Extern, false, 0);
1531}
1532
Steve Naroff09b266e2007-10-30 23:14:51 +00001533// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1534void RewriteTest::SynthGetClassFunctionDecl() {
1535 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1536 llvm::SmallVector<QualType, 16> ArgTys;
1537 ArgTys.push_back(Context->getPointerType(
1538 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001539 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001540 &ArgTys[0], ArgTys.size(),
1541 false /*isVariadic*/);
1542 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1543 getClassIdent, getClassType,
1544 FunctionDecl::Extern, false, 0);
1545}
1546
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001547// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1548void RewriteTest::SynthGetMetaClassFunctionDecl() {
1549 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1550 llvm::SmallVector<QualType, 16> ArgTys;
1551 ArgTys.push_back(Context->getPointerType(
1552 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001553 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001554 &ArgTys[0], ArgTys.size(),
1555 false /*isVariadic*/);
1556 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1557 getClassIdent, getClassType,
1558 FunctionDecl::Extern, false, 0);
1559}
1560
Steve Naroff96984642007-11-08 14:30:50 +00001561// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1562void RewriteTest::SynthCFStringFunctionDecl() {
1563 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1564 llvm::SmallVector<QualType, 16> ArgTys;
1565 ArgTys.push_back(Context->getPointerType(
1566 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001567 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001568 &ArgTys[0], ArgTys.size(),
1569 false /*isVariadic*/);
1570 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1571 getClassIdent, getClassType,
1572 FunctionDecl::Extern, false, 0);
1573}
1574
Steve Naroffbeaf2992007-11-03 11:27:19 +00001575Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001576#if 1
1577 // This rewrite is specific to GCC, which has builtin support for CFString.
1578 if (!CFStringFunctionDecl)
1579 SynthCFStringFunctionDecl();
1580 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1581 llvm::SmallVector<Expr*, 8> StrExpr;
1582 StrExpr.push_back(Exp->getString());
1583 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1584 &StrExpr[0], StrExpr.size());
1585 // cast to NSConstantString *
1586 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001587 if (Rewrite.ReplaceStmt(Exp, cast)) {
1588 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001589 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1590 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001591 SourceRange Range = Exp->getSourceRange();
1592 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001593 }
Steve Naroff96984642007-11-08 14:30:50 +00001594 delete Exp;
1595 return cast;
1596#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001597 assert(ConstantStringClassReference && "Can't find constant string reference");
1598 llvm::SmallVector<Expr*, 4> InitExprs;
1599
1600 // Synthesize "(Class)&_NSConstantStringClassReference"
1601 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1602 ConstantStringClassReference->getType(),
1603 SourceLocation());
1604 QualType expType = Context->getPointerType(ClsRef->getType());
1605 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1606 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001608 SourceLocation());
1609 InitExprs.push_back(cast); // set the 'isa'.
1610 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1611 unsigned IntSize = static_cast<unsigned>(
1612 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1613 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1614 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1615 Exp->getLocStart());
1616 InitExprs.push_back(len); // set "int numBytes".
1617
1618 // struct NSConstantString
1619 QualType CFConstantStrType = Context->getCFConstantStringType();
1620 // (struct NSConstantString) { <exprs from above> }
1621 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1622 &InitExprs[0], InitExprs.size(),
1623 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001624 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001625 // struct NSConstantString *
1626 expType = Context->getPointerType(StrRep->getType());
1627 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1628 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001629 // cast to NSConstantString *
1630 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001631 Rewrite.ReplaceStmt(Exp, cast);
1632 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001633 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001634#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001635}
1636
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001637ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001638 // check if we are sending a message to 'super'
1639 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001640 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1641 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1642 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1643 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001644 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001645 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001646 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001647 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001648 if (ObjCInterfaceType *IT =
1649 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001650 if (IT->getDecl() ==
1651 CurMethodDecl->getClassInterface()->getSuperClass())
1652 return IT->getDecl();
1653 }
1654 }
1655 }
1656 }
1657 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001658 }
Steve Naroff874e2322007-11-15 10:28:18 +00001659 }
1660 return 0;
1661}
1662
1663// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1664QualType RewriteTest::getSuperStructType() {
1665 if (!SuperStructDecl) {
1666 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1667 &Context->Idents.get("objc_super"), 0);
1668 QualType FieldTypes[2];
1669
1670 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001672 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001673 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001674 // Create fields
1675 FieldDecl *FieldDecls[2];
1676
1677 for (unsigned i = 0; i < 2; ++i)
1678 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1679
1680 SuperStructDecl->defineBody(FieldDecls, 4);
1681 }
1682 return Context->getTagDeclType(SuperStructDecl);
1683}
1684
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001685Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001686 if (!SelGetUidFunctionDecl)
1687 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001688 if (!MsgSendFunctionDecl)
1689 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001690 if (!MsgSendSuperFunctionDecl)
1691 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001692 if (!MsgSendStretFunctionDecl)
1693 SynthMsgSendStretFunctionDecl();
1694 if (!MsgSendSuperStretFunctionDecl)
1695 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001696 if (!MsgSendFpretFunctionDecl)
1697 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001698 if (!GetClassFunctionDecl)
1699 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001700 if (!GetMetaClassFunctionDecl)
1701 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001702
Steve Naroff874e2322007-11-15 10:28:18 +00001703 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001704 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1705 // May need to use objc_msgSend_stret() as well.
1706 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001707 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001708 QualType resultType = mDecl->getResultType();
1709 if (resultType.getCanonicalType()->isStructureType()
1710 || resultType.getCanonicalType()->isUnionType())
1711 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001712 else if (resultType.getCanonicalType()->isRealFloatingType())
1713 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001714 }
Steve Naroff874e2322007-11-15 10:28:18 +00001715
Steve Naroff934f2762007-10-24 22:48:43 +00001716 // Synthesize a call to objc_msgSend().
1717 llvm::SmallVector<Expr*, 8> MsgExprs;
1718 IdentifierInfo *clsName = Exp->getClassName();
1719
1720 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1721 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001722 if (!strcmp(clsName->getName(), "super")) {
1723 MsgSendFlavor = MsgSendSuperFunctionDecl;
1724 if (MsgSendStretFlavor)
1725 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1726 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1727
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001728 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001729 CurMethodDecl->getClassInterface()->getSuperClass();
1730
1731 llvm::SmallVector<Expr*, 4> InitExprs;
1732
1733 // set the receiver to self, the first argument to all methods.
1734 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001735 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001736 SourceLocation()));
1737 llvm::SmallVector<Expr*, 8> ClsExprs;
1738 QualType argType = Context->getPointerType(Context->CharTy);
1739 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1740 SuperDecl->getIdentifier()->getLength(),
1741 false, argType, SourceLocation(),
1742 SourceLocation()));
1743 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1744 &ClsExprs[0],
1745 ClsExprs.size());
1746 // To turn off a warning, type-cast to 'id'
1747 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001748 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001749 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1750 // struct objc_super
1751 QualType superType = getSuperStructType();
1752 // (struct objc_super) { <exprs from above> }
1753 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1754 &InitExprs[0], InitExprs.size(),
1755 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001756 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001757 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001758 // struct objc_super *
1759 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1760 Context->getPointerType(SuperRep->getType()),
1761 SourceLocation());
1762 MsgExprs.push_back(Unop);
1763 } else {
1764 llvm::SmallVector<Expr*, 8> ClsExprs;
1765 QualType argType = Context->getPointerType(Context->CharTy);
1766 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1767 clsName->getLength(),
1768 false, argType, SourceLocation(),
1769 SourceLocation()));
1770 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1771 &ClsExprs[0],
1772 ClsExprs.size());
1773 MsgExprs.push_back(Cls);
1774 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001775 } else { // instance message.
1776 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001777
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001778 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001779 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001780 if (MsgSendStretFlavor)
1781 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001782 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1783
1784 llvm::SmallVector<Expr*, 4> InitExprs;
1785
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001786 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001787 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001788 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001789
1790 llvm::SmallVector<Expr*, 8> ClsExprs;
1791 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001792 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1793 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001794 false, argType, SourceLocation(),
1795 SourceLocation()));
1796 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001797 &ClsExprs[0],
1798 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001799 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001800 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001802 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001803 // struct objc_super
1804 QualType superType = getSuperStructType();
1805 // (struct objc_super) { <exprs from above> }
1806 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1807 &InitExprs[0], InitExprs.size(),
1808 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001809 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001810 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001811 // struct objc_super *
1812 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1813 Context->getPointerType(SuperRep->getType()),
1814 SourceLocation());
1815 MsgExprs.push_back(Unop);
1816 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001817 // Remove all type-casts because it may contain objc-style types; e.g.
1818 // Foo<Proto> *.
1819 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1820 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001821 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001822 MsgExprs.push_back(recExpr);
1823 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001824 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001825 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001826 llvm::SmallVector<Expr*, 8> SelExprs;
1827 QualType argType = Context->getPointerType(Context->CharTy);
1828 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1829 Exp->getSelector().getName().size(),
1830 false, argType, SourceLocation(),
1831 SourceLocation()));
1832 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1833 &SelExprs[0], SelExprs.size());
1834 MsgExprs.push_back(SelExp);
1835
1836 // Now push any user supplied arguments.
1837 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001838 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001839 // Make all implicit casts explicit...ICE comes in handy:-)
1840 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1841 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001842 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1843 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001844 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001845 }
1846 // Make id<P...> cast into an 'id' cast.
1847 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001849 while ((CE = dyn_cast<CastExpr>(userExpr)))
1850 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001851 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001852 userExpr, SourceLocation());
1853 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001854 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001855 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001856 // We've transferred the ownership to MsgExprs. Null out the argument in
1857 // the original expression, since we will delete it below.
1858 Exp->setArg(i, 0);
1859 }
Steve Naroffab972d32007-11-04 22:37:50 +00001860 // Generate the funky cast.
1861 CastExpr *cast;
1862 llvm::SmallVector<QualType, 8> ArgTypes;
1863 QualType returnType;
1864
1865 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001866 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1867 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1868 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001869 ArgTypes.push_back(Context->getObjCIdType());
1870 ArgTypes.push_back(Context->getObjCSelType());
1871 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001872 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001873 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001874 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1875 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001876 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001877 ArgTypes.push_back(t);
1878 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001879 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1880 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001881 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001883 }
1884 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001885 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001886
1887 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001888 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1889 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001890
1891 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1892 // If we don't do this cast, we get the following bizarre warning/note:
1893 // xx.m:13: warning: function called through a non-compatible type
1894 // xx.m:13: note: if this code is reached, the program will abort
1895 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1896 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001897
Steve Naroffab972d32007-11-04 22:37:50 +00001898 // Now do the "normal" pointer to function cast.
1899 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001900 &ArgTypes[0], ArgTypes.size(),
1901 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001902 castType = Context->getPointerType(castType);
1903 cast = new CastExpr(castType, cast, SourceLocation());
1904
1905 // Don't forget the parens to enforce the proper binding.
1906 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1907
1908 const FunctionType *FT = msgSendType->getAsFunctionType();
1909 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1910 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001911 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001912 if (MsgSendStretFlavor) {
1913 // We have the method which returns a struct/union. Must also generate
1914 // call to objc_msgSend_stret and hang both varieties on a conditional
1915 // expression which dictate which one to envoke depending on size of
1916 // method's return type.
1917
1918 // Create a reference to the objc_msgSend_stret() declaration.
1919 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1920 SourceLocation());
1921 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1922 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1923 SourceLocation());
1924 // Now do the "normal" pointer to function cast.
1925 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001926 &ArgTypes[0], ArgTypes.size(),
1927 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001928 castType = Context->getPointerType(castType);
1929 cast = new CastExpr(castType, cast, SourceLocation());
1930
1931 // Don't forget the parens to enforce the proper binding.
1932 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1933
1934 FT = msgSendType->getAsFunctionType();
1935 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1936 FT->getResultType(), SourceLocation());
1937
1938 // Build sizeof(returnType)
1939 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1940 returnType, Context->getSizeType(),
1941 SourceLocation(), SourceLocation());
1942 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1943 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1944 // For X86 it is more complicated and some kind of target specific routine
1945 // is needed to decide what to do.
1946 unsigned IntSize = static_cast<unsigned>(
1947 Context->getTypeSize(Context->IntTy, SourceLocation()));
1948
1949 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1950 Context->IntTy,
1951 SourceLocation());
1952 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1953 BinaryOperator::LE,
1954 Context->IntTy,
1955 SourceLocation());
1956 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1957 ConditionalOperator *CondExpr =
1958 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001959 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001960 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001961 return ReplacingStmt;
1962}
1963
1964Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1965 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00001966 // Now do the actual rewrite.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001967 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroff5ca40202007-12-19 14:32:56 +00001968 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001969 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1970 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001971 SourceRange Range = Exp->getSourceRange();
1972 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001973 }
Steve Naroff934f2762007-10-24 22:48:43 +00001974
Chris Lattnere64b7772007-10-24 16:57:36 +00001975 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001976 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00001977}
1978
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001979/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1980/// call to objc_getProtocol("proto-name").
1981Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1982 if (!GetProtocolFunctionDecl)
1983 SynthGetProtocolFunctionDecl();
1984 // Create a call to objc_getProtocol("ProtocolName").
1985 llvm::SmallVector<Expr*, 8> ProtoExprs;
1986 QualType argType = Context->getPointerType(Context->CharTy);
1987 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1988 strlen(Exp->getProtocol()->getName()),
1989 false, argType, SourceLocation(),
1990 SourceLocation()));
1991 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1992 &ProtoExprs[0],
1993 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001994 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1995 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001996 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1997 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001998 SourceRange Range = Exp->getSourceRange();
1999 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00002000 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002001 delete Exp;
2002 return ProtoExp;
2003
2004}
2005
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002006/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002007/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002009 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2011 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002012 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002014 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002016 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002017 SourceLocation LocStart = CDecl->getLocStart();
2018 SourceLocation LocEnd = CDecl->getLocEnd();
2019
2020 const char *startBuf = SM->getCharacterData(LocStart);
2021 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002022 // If no ivars and no root or if its root, directly or indirectly,
2023 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002025 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2026 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2027 Result.c_str(), Result.size());
2028 return;
2029 }
2030
2031 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002033 Result += "\nstruct ";
2034 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002035
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002036 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002037 const char *cursor = strchr(startBuf, '{');
2038 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002039 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002040
2041 // rewrite the original header *without* disturbing the '{'
2042 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2043 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002044 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002045 Result = "\n struct ";
2046 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002047 // Note: We don't name the field decl. This simplifies the "codegen" for
2048 // accessing a superclasses instance variables (and is similar to what gcc
2049 // does internally). The unnamed struct field feature is enabled with
2050 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2051 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002052 Result += ";\n";
2053
2054 // insert the super class structure definition.
2055 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2056 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2057 }
2058 cursor++; // past '{'
2059
2060 // Now comment out any visibility specifiers.
2061 while (cursor < endBuf) {
2062 if (*cursor == '@') {
2063 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002064 // Skip whitespace.
2065 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2066 /*scan*/;
2067
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002068 // FIXME: presence of @public, etc. inside comment results in
2069 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002070 if (!strncmp(cursor, "public", strlen("public")) ||
2071 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002072 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00002073 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002074 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002075 // FIXME: If there are cases where '<' is used in ivar declaration part
2076 // of user code, then scan the ivar list and use needToScanForQualifiers
2077 // for type checking.
2078 else if (*cursor == '<') {
2079 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2080 Rewrite.InsertText(atLoc, "/* ", 3);
2081 cursor = strchr(cursor, '>');
2082 cursor++;
2083 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2084 Rewrite.InsertText(atLoc, " */", 3);
2085 }
Steve Narofffea763e82007-11-14 19:25:57 +00002086 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002087 }
Steve Narofffea763e82007-11-14 19:25:57 +00002088 // Don't forget to add a ';'!!
2089 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2090 } else { // we don't have any instance variables - insert super struct.
2091 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2092 Result += " {\n struct ";
2093 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00002094 // Note: We don't name the field decl. This simplifies the "codegen" for
2095 // accessing a superclasses instance variables (and is similar to what gcc
2096 // does internally). The unnamed struct field feature is enabled with
2097 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2098 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002099 Result += ";\n};\n";
2100 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2101 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002102 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002103 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002104 if (!ObjCSynthesizedStructs.insert(CDecl))
2105 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002106}
2107
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002108// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002109/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002111 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002112 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002113 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002114 const char *ClassName,
2115 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002116 if (MethodBegin == MethodEnd) return;
2117
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002118 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002119 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002120 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002121 SEL _cmd;
2122 char *method_types;
2123 void *_imp;
2124 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002125 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002126 Result += "\nstruct _objc_method {\n";
2127 Result += "\tSEL _cmd;\n";
2128 Result += "\tchar *method_types;\n";
2129 Result += "\tvoid *_imp;\n";
2130 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002131
2132 /* struct _objc_method_list {
2133 struct _objc_method_list *next_method;
2134 int method_count;
2135 struct _objc_method method_list[];
2136 }
2137 */
2138 Result += "\nstruct _objc_method_list {\n";
2139 Result += "\tstruct _objc_method_list *next_method;\n";
2140 Result += "\tint method_count;\n";
2141 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002142 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002143 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002144
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002145 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002146 Result += "\nstatic struct _objc_method_list _OBJC_";
2147 Result += prefix;
2148 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2149 Result += "_METHODS_";
2150 Result += ClassName;
2151 Result += " __attribute__ ((section (\"__OBJC, __";
2152 Result += IsInstanceMethod ? "inst" : "cls";
2153 Result += "_meth\")))= ";
2154 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002155
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002156 Result += "\t,{{(SEL)\"";
2157 Result += (*MethodBegin)->getSelector().getName().c_str();
2158 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002160 Result += "\", \"";
2161 Result += MethodTypeString;
2162 Result += "\", ";
2163 Result += MethodInternalNames[*MethodBegin];
2164 Result += "}\n";
2165 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2166 Result += "\t ,{(SEL)\"";
2167 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002168 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002170 Result += "\", \"";
2171 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002172 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002173 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002174 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002175 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002176 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002177}
2178
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002179/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2180void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002181 int NumProtocols,
2182 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002183 const char *ClassName,
2184 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002185 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002186 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002187 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002188 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002189 // Output struct protocol_methods holder of method selector and type.
2190 if (!objc_protocol_methods &&
2191 (PDecl->getNumInstanceMethods() > 0
2192 || PDecl->getNumClassMethods() > 0)) {
2193 /* struct protocol_methods {
2194 SEL _cmd;
2195 char *method_types;
2196 }
2197 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002198 Result += "\nstruct protocol_methods {\n";
2199 Result += "\tSEL _cmd;\n";
2200 Result += "\tchar *method_types;\n";
2201 Result += "};\n";
2202
2203 /* struct _objc_protocol_method_list {
2204 int protocol_method_count;
2205 struct protocol_methods protocols[];
2206 }
2207 */
2208 Result += "\nstruct _objc_protocol_method_list {\n";
2209 Result += "\tint protocol_method_count;\n";
2210 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002211 objc_protocol_methods = true;
2212 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002213
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002214 int NumMethods = PDecl->getNumInstanceMethods();
2215 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002216 Result += "\nstatic struct _objc_protocol_method_list "
2217 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2218 Result += PDecl->getName();
2219 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2220 "{\n\t" + utostr(NumMethods) + "\n";
2221
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002222 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002224 E = PDecl->instmeth_end(); I != E; ++I) {
2225 if (I == PDecl->instmeth_begin())
2226 Result += "\t ,{{(SEL)\"";
2227 else
2228 Result += "\t ,{(SEL)\"";
2229 Result += (*I)->getSelector().getName().c_str();
2230 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002231 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002232 Result += "\", \"";
2233 Result += MethodTypeString;
2234 Result += "\"}\n";
2235 }
2236 Result += "\t }\n};\n";
2237 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002238
2239 // Output class methods declared in this protocol.
2240 NumMethods = PDecl->getNumClassMethods();
2241 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002242 Result += "\nstatic struct _objc_protocol_method_list "
2243 "_OBJC_PROTOCOL_CLASS_METHODS_";
2244 Result += PDecl->getName();
2245 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2246 "{\n\t";
2247 Result += utostr(NumMethods);
2248 Result += "\n";
2249
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002250 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002252 E = PDecl->classmeth_end(); I != E; ++I) {
2253 if (I == PDecl->classmeth_begin())
2254 Result += "\t ,{{(SEL)\"";
2255 else
2256 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002257 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002258 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002259 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002260 Result += "\", \"";
2261 Result += MethodTypeString;
2262 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002263 }
2264 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002265 }
2266 // Output:
2267 /* struct _objc_protocol {
2268 // Objective-C 1.0 extensions
2269 struct _objc_protocol_extension *isa;
2270 char *protocol_name;
2271 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002272 struct _objc_protocol_method_list *instance_methods;
2273 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002274 };
2275 */
2276 static bool objc_protocol = false;
2277 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002278 Result += "\nstruct _objc_protocol {\n";
2279 Result += "\tstruct _objc_protocol_extension *isa;\n";
2280 Result += "\tchar *protocol_name;\n";
2281 Result += "\tstruct _objc_protocol **protocol_list;\n";
2282 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2283 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2284 Result += "};\n";
2285
2286 /* struct _objc_protocol_list {
2287 struct _objc_protocol_list *next;
2288 int protocol_count;
2289 struct _objc_protocol *class_protocols[];
2290 }
2291 */
2292 Result += "\nstruct _objc_protocol_list {\n";
2293 Result += "\tstruct _objc_protocol_list *next;\n";
2294 Result += "\tint protocol_count;\n";
2295 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2296 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002297 objc_protocol = true;
2298 }
2299
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002300 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2301 Result += PDecl->getName();
2302 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2303 "{\n\t0, \"";
2304 Result += PDecl->getName();
2305 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002306 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002307 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2308 Result += PDecl->getName();
2309 Result += ", ";
2310 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002311 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002312 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002313 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002314 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2315 Result += PDecl->getName();
2316 Result += "\n";
2317 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002318 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002319 Result += "0\n";
2320 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002321 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002322 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002323 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2324 Result += prefix;
2325 Result += "_PROTOCOLS_";
2326 Result += ClassName;
2327 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2328 "{\n\t0, ";
2329 Result += utostr(NumProtocols);
2330 Result += "\n";
2331
2332 Result += "\t,{&_OBJC_PROTOCOL_";
2333 Result += Protocols[0]->getName();
2334 Result += " \n";
2335
2336 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002337 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002338 Result += "\t ,&_OBJC_PROTOCOL_";
2339 Result += PDecl->getName();
2340 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002341 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002342 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002343 }
2344}
2345
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002346/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002347/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002349 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002351 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002352 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002353 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2354 CDecl = CDecl->getNextClassCategory())
2355 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2356 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002357
Chris Lattnereb44eee2007-12-23 01:40:15 +00002358 std::string FullCategoryName = ClassDecl->getName();
2359 FullCategoryName += '_';
2360 FullCategoryName += IDecl->getName();
2361
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002362 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002364 true, "CATEGORY_", FullCategoryName.c_str(),
2365 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002366
2367 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002368 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002369 false, "CATEGORY_", FullCategoryName.c_str(),
2370 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002371
2372 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002373 // Null CDecl is case of a category implementation with no category interface
2374 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002376 CDecl->getNumReferencedProtocols(),
2377 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002378 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002379
2380 /* struct _objc_category {
2381 char *category_name;
2382 char *class_name;
2383 struct _objc_method_list *instance_methods;
2384 struct _objc_method_list *class_methods;
2385 struct _objc_protocol_list *protocols;
2386 // Objective-C 1.0 extensions
2387 uint32_t size; // sizeof (struct _objc_category)
2388 struct _objc_property_list *instance_properties; // category's own
2389 // @property decl.
2390 };
2391 */
2392
2393 static bool objc_category = false;
2394 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 Result += "\nstruct _objc_category {\n";
2396 Result += "\tchar *category_name;\n";
2397 Result += "\tchar *class_name;\n";
2398 Result += "\tstruct _objc_method_list *instance_methods;\n";
2399 Result += "\tstruct _objc_method_list *class_methods;\n";
2400 Result += "\tstruct _objc_protocol_list *protocols;\n";
2401 Result += "\tunsigned int size;\n";
2402 Result += "\tstruct _objc_property_list *instance_properties;\n";
2403 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002404 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002405 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002406 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2407 Result += FullCategoryName;
2408 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2409 Result += IDecl->getName();
2410 Result += "\"\n\t, \"";
2411 Result += ClassDecl->getName();
2412 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002414 if (IDecl->getNumInstanceMethods() > 0) {
2415 Result += "\t, (struct _objc_method_list *)"
2416 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2417 Result += FullCategoryName;
2418 Result += "\n";
2419 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002420 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002421 Result += "\t, 0\n";
2422 if (IDecl->getNumClassMethods() > 0) {
2423 Result += "\t, (struct _objc_method_list *)"
2424 "&_OBJC_CATEGORY_CLASS_METHODS_";
2425 Result += FullCategoryName;
2426 Result += "\n";
2427 }
2428 else
2429 Result += "\t, 0\n";
2430
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002431 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002432 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2433 Result += FullCategoryName;
2434 Result += "\n";
2435 }
2436 else
2437 Result += "\t, 0\n";
2438 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002439}
2440
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002441/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2442/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2444 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002445 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002446 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002447 Result += IDecl->getName();
2448 Result += ", ";
2449 Result += ivar->getName();
2450 Result += ")";
2451}
2452
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002453//===----------------------------------------------------------------------===//
2454// Meta Data Emission
2455//===----------------------------------------------------------------------===//
2456
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002458 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002460
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002461 // Explictly declared @interface's are already synthesized.
2462 if (CDecl->ImplicitInterfaceDecl()) {
2463 // FIXME: Implementation of a class with no @interface (legacy) doese not
2464 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002466 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002467
Chris Lattnerbe6df082007-12-12 07:56:42 +00002468 // Build _objc_ivar_list metadata for classes ivars if needed
2469 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2470 ? IDecl->getImplDeclNumIvars()
2471 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002472 if (NumIvars > 0) {
2473 static bool objc_ivar = false;
2474 if (!objc_ivar) {
2475 /* struct _objc_ivar {
2476 char *ivar_name;
2477 char *ivar_type;
2478 int ivar_offset;
2479 };
2480 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002481 Result += "\nstruct _objc_ivar {\n";
2482 Result += "\tchar *ivar_name;\n";
2483 Result += "\tchar *ivar_type;\n";
2484 Result += "\tint ivar_offset;\n";
2485 Result += "};\n";
2486
2487 /* struct _objc_ivar_list {
2488 int ivar_count;
2489 struct _objc_ivar ivar_list[];
2490 };
2491 */
2492 Result += "\nstruct _objc_ivar_list {\n";
2493 Result += "\tint ivar_count;\n";
2494 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002495 objc_ivar = true;
2496 }
2497
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002498 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2499 Result += IDecl->getName();
2500 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2501 "{\n\t";
2502 Result += utostr(NumIvars);
2503 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002504
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002506 if (IDecl->getImplDeclNumIvars() > 0) {
2507 IVI = IDecl->ivar_begin();
2508 IVE = IDecl->ivar_end();
2509 } else {
2510 IVI = CDecl->ivar_begin();
2511 IVE = CDecl->ivar_end();
2512 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002513 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002514 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002515 Result += "\", \"";
2516 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002517 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002518 Result += StrEncoding;
2519 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002520 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002521 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002522 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002523 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002524 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002525 Result += "\", \"";
2526 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002527 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002528 Result += StrEncoding;
2529 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002530 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002531 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002532 }
2533
2534 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002535 }
2536
2537 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002538 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002539 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002540
2541 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002543 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002545 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002547 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002548 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002549
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002550
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002551 // Declaration of class/meta-class metadata
2552 /* struct _objc_class {
2553 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002554 const char *super_class_name;
2555 char *name;
2556 long version;
2557 long info;
2558 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002559 struct _objc_ivar_list *ivars;
2560 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002561 struct objc_cache *cache;
2562 struct objc_protocol_list *protocols;
2563 const char *ivar_layout;
2564 struct _objc_class_ext *ext;
2565 };
2566 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002567 static bool objc_class = false;
2568 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002569 Result += "\nstruct _objc_class {\n";
2570 Result += "\tstruct _objc_class *isa;\n";
2571 Result += "\tconst char *super_class_name;\n";
2572 Result += "\tchar *name;\n";
2573 Result += "\tlong version;\n";
2574 Result += "\tlong info;\n";
2575 Result += "\tlong instance_size;\n";
2576 Result += "\tstruct _objc_ivar_list *ivars;\n";
2577 Result += "\tstruct _objc_method_list *methods;\n";
2578 Result += "\tstruct objc_cache *cache;\n";
2579 Result += "\tstruct _objc_protocol_list *protocols;\n";
2580 Result += "\tconst char *ivar_layout;\n";
2581 Result += "\tstruct _objc_class_ext *ext;\n";
2582 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002583 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002584 }
2585
2586 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002587 ObjCInterfaceDecl *RootClass = 0;
2588 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002589 while (SuperClass) {
2590 RootClass = SuperClass;
2591 SuperClass = SuperClass->getSuperClass();
2592 }
2593 SuperClass = CDecl->getSuperClass();
2594
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002595 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2596 Result += CDecl->getName();
2597 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2598 "{\n\t(struct _objc_class *)\"";
2599 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2600 Result += "\"";
2601
2602 if (SuperClass) {
2603 Result += ", \"";
2604 Result += SuperClass->getName();
2605 Result += "\", \"";
2606 Result += CDecl->getName();
2607 Result += "\"";
2608 }
2609 else {
2610 Result += ", 0, \"";
2611 Result += CDecl->getName();
2612 Result += "\"";
2613 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002614 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002615 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002616 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002617 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002618 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002619 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002620 Result += "\n";
2621 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002622 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002623 Result += ", 0\n";
2624 if (CDecl->getNumIntfRefProtocols() > 0) {
2625 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2626 Result += CDecl->getName();
2627 Result += ",0,0\n";
2628 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002629 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002630 Result += "\t,0,0,0,0\n";
2631 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002632
2633 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002634 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2635 Result += CDecl->getName();
2636 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2637 "{\n\t&_OBJC_METACLASS_";
2638 Result += CDecl->getName();
2639 if (SuperClass) {
2640 Result += ", \"";
2641 Result += SuperClass->getName();
2642 Result += "\", \"";
2643 Result += CDecl->getName();
2644 Result += "\"";
2645 }
2646 else {
2647 Result += ", 0, \"";
2648 Result += CDecl->getName();
2649 Result += "\"";
2650 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002651 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002652 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002653 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002654 Result += ",0";
2655 else {
2656 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002657 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002658 Result += CDecl->getName();
2659 Result += ")";
2660 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002661 if (NumIvars > 0) {
2662 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2663 Result += CDecl->getName();
2664 Result += "\n\t";
2665 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002666 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002667 Result += ",0";
2668 if (IDecl->getNumInstanceMethods() > 0) {
2669 Result += ", &_OBJC_INSTANCE_METHODS_";
2670 Result += CDecl->getName();
2671 Result += ", 0\n\t";
2672 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002673 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002674 Result += ",0,0";
2675 if (CDecl->getNumIntfRefProtocols() > 0) {
2676 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2677 Result += CDecl->getName();
2678 Result += ", 0,0\n";
2679 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002680 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002681 Result += ",0,0,0\n";
2682 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002683}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002684
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002685/// RewriteImplementations - This routine rewrites all method implementations
2686/// and emits meta-data.
2687
2688void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002689 int ClsDefCount = ClassImplementation.size();
2690 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002691
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002692 if (ClsDefCount == 0 && CatDefCount == 0)
2693 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002694 // Rewrite implemented methods
2695 for (int i = 0; i < ClsDefCount; i++)
2696 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002697
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002698 for (int i = 0; i < CatDefCount; i++)
2699 RewriteImplementationDecl(CategoryImplementation[i]);
2700
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002701 // This is needed for use of offsetof
2702 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002703
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002704 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002705 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002706 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002707
2708 // For each implemented category, write out all its meta data.
2709 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002710 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002711
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002712 // Write objc_symtab metadata
2713 /*
2714 struct _objc_symtab
2715 {
2716 long sel_ref_cnt;
2717 SEL *refs;
2718 short cls_def_cnt;
2719 short cat_def_cnt;
2720 void *defs[cls_def_cnt + cat_def_cnt];
2721 };
2722 */
2723
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002724 Result += "\nstruct _objc_symtab {\n";
2725 Result += "\tlong sel_ref_cnt;\n";
2726 Result += "\tSEL *refs;\n";
2727 Result += "\tshort cls_def_cnt;\n";
2728 Result += "\tshort cat_def_cnt;\n";
2729 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2730 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002731
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002732 Result += "static struct _objc_symtab "
2733 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2734 Result += "\t0, 0, " + utostr(ClsDefCount)
2735 + ", " + utostr(CatDefCount) + "\n";
2736 for (int i = 0; i < ClsDefCount; i++) {
2737 Result += "\t,&_OBJC_CLASS_";
2738 Result += ClassImplementation[i]->getName();
2739 Result += "\n";
2740 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002741
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 for (int i = 0; i < CatDefCount; i++) {
2743 Result += "\t,&_OBJC_CATEGORY_";
2744 Result += CategoryImplementation[i]->getClassInterface()->getName();
2745 Result += "_";
2746 Result += CategoryImplementation[i]->getName();
2747 Result += "\n";
2748 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002749
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002750 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002751
2752 // Write objc_module metadata
2753
2754 /*
2755 struct _objc_module {
2756 long version;
2757 long size;
2758 const char *name;
2759 struct _objc_symtab *symtab;
2760 }
2761 */
2762
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += "\nstruct _objc_module {\n";
2764 Result += "\tlong version;\n";
2765 Result += "\tlong size;\n";
2766 Result += "\tconst char *name;\n";
2767 Result += "\tstruct _objc_symtab *symtab;\n";
2768 Result += "};\n\n";
2769 Result += "static struct _objc_module "
2770 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002771 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2772 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002773 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002774
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002775}
Chris Lattner311ff022007-10-16 22:36:42 +00002776