blob: d1c6b9710a6808801e1f96d3c5923cb2125a7d20 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000026#include "llvm/Support/Streams.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000027#include "llvm/System/Path.h"
Steve Naroff0d4e9632008-04-14 22:53:48 +000028#include <sstream>
Chris Lattnerc68ab772008-03-22 00:08:40 +000029#include <fstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Steve Naroff0113c9d2008-01-28 21:34:52 +000033static llvm::cl::opt<bool>
34SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
35 llvm::cl::desc("Silence ObjC rewriting warnings"));
36
Chris Lattner77cd2a02007-10-11 00:43:27 +000037namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000039 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000040 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000041 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000042 unsigned RewriteFailedDiag;
43
Chris Lattner01c57482007-10-17 22:35:30 +000044 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000045 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000046 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000047 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000048 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000049 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000050
Ted Kremeneka526c5c2008-01-07 19:49:32 +000051 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
52 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
53 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000054 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000055 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
56 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000057 llvm::SmallVector<Stmt *, 32> Stmts;
58 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000059 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000083 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
94
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000095 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000096 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000097 void Initialize(ASTContext &context);
98
Chris Lattner8a12c272007-10-11 18:38:32 +000099
Chris Lattnerf04da132007-10-24 17:06:59 +0000100 // Top Level Driver code.
101 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000102 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000103 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000104 Diagnostic &D, const LangOptions &LOpts);
Steve Naroffb29b4272008-04-14 22:03:09 +0000105 ~RewriteObjC();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000106
107 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000108 // If replacement succeeded or warning disabled return with no warning.
109 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000110 return;
111
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112 SourceRange Range = Old->getSourceRange();
113 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
114 0, 0, &Range, 1);
115 }
116
Steve Naroffba92b2e2008-03-27 22:29:16 +0000117 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
118 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000119 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000120 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000121 SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000126
Chris Lattneraadaf782008-01-31 19:51:04 +0000127 void RemoveText(SourceLocation Loc, unsigned StrLen) {
128 // If removal succeeded or warning disabled return with no warning.
129 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
130 return;
131
132 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
133 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000134
Chris Lattneraadaf782008-01-31 19:51:04 +0000135 void ReplaceText(SourceLocation Start, unsigned OrigLength,
136 const char *NewStr, unsigned NewLength) {
137 // If removal succeeded or warning disabled return with no warning.
138 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
139 SilenceRewriteMacroWarning)
140 return;
141
142 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
143 }
144
Chris Lattnerf04da132007-10-24 17:06:59 +0000145 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000146 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000147 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000148 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000149 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
150 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000151 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000152 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
153 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
154 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
155 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
156 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000157 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000158 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000159 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000160 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000161 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000162 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000163 QualType getConstantStringStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000166 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000167 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000168 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000169 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000170 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000171 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000172 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000174 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
176 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
177 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000178 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
179 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000180 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
181 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000182 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000183 Stmt *RewriteBreakStmt(BreakStmt *S);
184 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000185 void SynthCountByEnumWithState(std::string &buf);
186
Steve Naroff09b266e2007-10-30 23:14:51 +0000187 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000188 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000189 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000190 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000191 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000192 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000193 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000194 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000195 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000196 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000203 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000204
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
206 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000207 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000208 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000209 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000210 const char *ClassName,
211 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000212
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000213 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000214 int NumProtocols,
215 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000216 const char *ClassName,
217 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000218 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000219 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000220 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
221 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000222 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000223 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000224 };
225}
226
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000227static bool IsHeaderFile(const std::string &Filename) {
228 std::string::size_type DotPos = Filename.rfind('.');
229
230 if (DotPos == std::string::npos) {
231 // no file extension
232 return false;
233 }
234
235 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
236 // C header: .h
237 // C++ header: .hh or .H;
238 return Ext == "h" || Ext == "hh" || Ext == "H";
239}
240
Steve Naroffb29b4272008-04-14 22:03:09 +0000241RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000242 Diagnostic &D, const LangOptions &LOpts)
243 : Diags(D), LangOpts(LOpts) {
244 IsHeader = IsHeaderFile(inFile);
245 InFileName = inFile;
246 OutFileName = outFile;
247 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
248 "rewriting sub-expression within a macro (may not be correct)");
249}
250
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000251ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000252 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000253 Diagnostic &Diags,
254 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000255 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000256}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000257
Steve Naroffb29b4272008-04-14 22:03:09 +0000258void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000259 Context = &context;
260 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000261 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000262 MsgSendFunctionDecl = 0;
263 MsgSendSuperFunctionDecl = 0;
264 MsgSendStretFunctionDecl = 0;
265 MsgSendSuperStretFunctionDecl = 0;
266 MsgSendFpretFunctionDecl = 0;
267 GetClassFunctionDecl = 0;
268 GetMetaClassFunctionDecl = 0;
269 SelGetUidFunctionDecl = 0;
270 CFStringFunctionDecl = 0;
271 GetProtocolFunctionDecl = 0;
272 ConstantStringClassReference = 0;
273 NSStringRecord = 0;
274 CurMethodDecl = 0;
275 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000276 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000277 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000278 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000280
281 // Get the ID and start/end of the main file.
282 MainFileID = SM->getMainFileID();
283 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
284 MainFileStart = MainBuf->getBufferStart();
285 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000286
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000287 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000288
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000289 // declaring objc_selector outside the parameter list removes a silly
290 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000291 if (IsHeader)
292 Preamble = "#pragma once\n";
293 Preamble += "struct objc_selector; struct objc_class;\n";
294 Preamble += "#ifndef OBJC_SUPER\n";
295 Preamble += "struct objc_super { struct objc_object *object; ";
296 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000297 if (LangOpts.Microsoft) {
298 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000299 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
300 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000301 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000302 Preamble += "};\n";
303 Preamble += "#define OBJC_SUPER\n";
304 Preamble += "#endif\n";
305 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
306 Preamble += "typedef struct objc_object Protocol;\n";
307 Preamble += "#define _REWRITER_typedef_Protocol\n";
308 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000309 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000310 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
311 else
312 Preamble += "#define __OBJC_RW_EXTERN extern\n";
313 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000314 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000315 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000316 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000317 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000318 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000319 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000320 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000321 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000322 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000323 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000324 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000325 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000326 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000327 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
328 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
329 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
330 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
331 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000332 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000333 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000334 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
335 Preamble += "struct __objcFastEnumerationState {\n\t";
336 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000337 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000338 Preamble += "unsigned long *mutationsPtr;\n\t";
339 Preamble += "unsigned long extra[5];\n};\n";
340 Preamble += "#define __FASTENUMERATIONSTATE\n";
341 Preamble += "#endif\n";
342 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
343 Preamble += "struct __NSConstantStringImpl {\n";
344 Preamble += " int *isa;\n";
345 Preamble += " int flags;\n";
346 Preamble += " char *str;\n";
347 Preamble += " long length;\n";
348 Preamble += "};\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000349 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000350 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
351 Preamble += "#endif\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000352 if (LangOpts.Microsoft) {
353 Preamble += "#undef __OBJC_RW_EXTERN\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000354 Preamble += "#define __attribute__(X)\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000355 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000356}
357
358
Chris Lattnerf04da132007-10-24 17:06:59 +0000359//===----------------------------------------------------------------------===//
360// Top Level Driver Code
361//===----------------------------------------------------------------------===//
362
Steve Naroffb29b4272008-04-14 22:03:09 +0000363void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000364 // Two cases: either the decl could be in the main file, or it could be in a
365 // #included file. If the former, rewrite it now. If the later, check to see
366 // if we rewrote the #include/#import.
367 SourceLocation Loc = D->getLocation();
368 Loc = SM->getLogicalLoc(Loc);
369
370 // If this is for a builtin, ignore it.
371 if (Loc.isInvalid()) return;
372
Steve Naroffebf2b562007-10-23 23:50:29 +0000373 // Look for built-in declarations that we need to refer during the rewrite.
374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000375 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000376 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000377 // declared in <Foundation/NSString.h>
378 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
379 ConstantStringClassReference = FVD;
380 return;
381 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000382 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000383 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000384 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000385 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000386 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000387 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000388 } else if (ObjCForwardProtocolDecl *FP =
389 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000390 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000391 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000392 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000393 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000394 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000395}
396
Chris Lattnerf04da132007-10-24 17:06:59 +0000397/// HandleDeclInMainFile - This is called for each top-level decl defined in the
398/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000399void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
401 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000402 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000403
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000405 if (Stmt *Body = MD->getBody()) {
406 //Body->dump();
407 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000408 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000409 CurMethodDecl = 0;
410 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000411 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000412 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000413 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000414 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000415 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000416 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000417 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000418 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000419 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000420 if (VD->getInit())
421 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
422 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000423 // Nothing yet.
424}
425
Steve Naroffb29b4272008-04-14 22:03:09 +0000426RewriteObjC::~RewriteObjC() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000427 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000428
429 // Rewrite tabs if we care.
430 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000431
Steve Naroffa7b402d2008-03-28 22:26:09 +0000432 if (Diags.hasErrorOccurred())
433 return;
434
435 // Create the output file.
436
437 std::ostream *OutFile;
438 if (OutFileName == "-") {
439 OutFile = llvm::cout.stream();
440 } else if (!OutFileName.empty()) {
441 OutFile = new std::ofstream(OutFileName.c_str(),
442 std::ios_base::binary|std::ios_base::out);
443 } else if (InFileName == "-") {
444 OutFile = llvm::cout.stream();
445 } else {
446 llvm::sys::Path Path(InFileName);
447 Path.eraseSuffix();
448 Path.appendSuffix("cpp");
449 OutFile = new std::ofstream(Path.toString().c_str(),
450 std::ios_base::binary|std::ios_base::out);
451 }
452
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000453 RewriteInclude();
454
Steve Naroffba92b2e2008-03-27 22:29:16 +0000455 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
456 Preamble.c_str(), Preamble.size(), false);
457
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000458 // Rewrite Objective-c meta data*
459 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000460 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000461
Chris Lattnerf04da132007-10-24 17:06:59 +0000462 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
463 // we are done.
464 if (const RewriteBuffer *RewriteBuf =
465 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000466 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000467 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000468 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000469 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000470 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000471 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000472 *OutFile << ResultStr;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000473}
474
Chris Lattnerf04da132007-10-24 17:06:59 +0000475//===----------------------------------------------------------------------===//
476// Syntactic (non-AST) Rewriting Code
477//===----------------------------------------------------------------------===//
478
Steve Naroffb29b4272008-04-14 22:03:09 +0000479void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000480 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
481 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
482 const char *MainBufStart = MainBuf.first;
483 const char *MainBufEnd = MainBuf.second;
484 size_t ImportLen = strlen("import");
485 size_t IncludeLen = strlen("include");
486
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000487 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000488 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
489 if (*BufPtr == '#') {
490 if (++BufPtr == MainBufEnd)
491 return;
492 while (*BufPtr == ' ' || *BufPtr == '\t')
493 if (++BufPtr == MainBufEnd)
494 return;
495 if (!strncmp(BufPtr, "import", ImportLen)) {
496 // replace import with include
497 SourceLocation ImportLoc =
498 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000499 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000500 BufPtr += ImportLen;
501 }
502 }
503 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000504}
505
Steve Naroffb29b4272008-04-14 22:03:09 +0000506void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000507 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
508 const char *MainBufStart = MainBuf.first;
509 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000510
Chris Lattnerf04da132007-10-24 17:06:59 +0000511 // Loop over the whole file, looking for tabs.
512 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
513 if (*BufPtr != '\t')
514 continue;
515
516 // Okay, we found a tab. This tab will turn into at least one character,
517 // but it depends on which 'virtual column' it is in. Compute that now.
518 unsigned VCol = 0;
519 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
520 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
521 ++VCol;
522
523 // Okay, now that we know the virtual column, we know how many spaces to
524 // insert. We assume 8-character tab-stops.
525 unsigned Spaces = 8-(VCol & 7);
526
527 // Get the location of the tab.
528 SourceLocation TabLoc =
529 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
530
531 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000532 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000533 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000534}
535
536
Steve Naroffb29b4272008-04-14 22:03:09 +0000537void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000538 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000539 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000540
541 // Get the start location and compute the semi location.
542 SourceLocation startLoc = ClassDecl->getLocation();
543 const char *startBuf = SM->getCharacterData(startLoc);
544 const char *semiPtr = strchr(startBuf, ';');
545
546 // Translate to typedef's that forward reference structs with the same name
547 // as the class. As a convenience, we include the original declaration
548 // as a comment.
549 std::string typedefString;
550 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000551 typedefString.append(startBuf, semiPtr-startBuf+1);
552 typedefString += "\n";
553 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000555 typedefString += "#ifndef _REWRITER_typedef_";
556 typedefString += ForwardDecl->getName();
557 typedefString += "\n";
558 typedefString += "#define _REWRITER_typedef_";
559 typedefString += ForwardDecl->getName();
560 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000561 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000562 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000563 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000564 }
565
566 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000567 ReplaceText(startLoc, semiPtr-startBuf+1,
568 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000569}
570
Steve Naroffb29b4272008-04-14 22:03:09 +0000571void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000572 SourceLocation LocStart = Method->getLocStart();
573 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000574
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000575 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000576 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000577 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000578 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000579 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000580 }
581}
582
Steve Naroffb29b4272008-04-14 22:03:09 +0000583void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000584{
Chris Lattner55d13b42008-03-16 21:23:50 +0000585 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000586 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000587 SourceLocation Loc = Property->getLocation();
588
Chris Lattneraadaf782008-01-31 19:51:04 +0000589 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000590
591 // FIXME: handle properties that are declared across multiple lines.
592 }
593}
594
Steve Naroffb29b4272008-04-14 22:03:09 +0000595void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000596 SourceLocation LocStart = CatDecl->getLocStart();
597
598 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000599 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000600
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000601 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000602 E = CatDecl->instmeth_end(); I != E; ++I)
603 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000604 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000605 E = CatDecl->classmeth_end(); I != E; ++I)
606 RewriteMethodDeclaration(*I);
607
Steve Naroff423cb562007-10-30 13:30:57 +0000608 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000609 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000610}
611
Steve Naroffb29b4272008-04-14 22:03:09 +0000612void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000613 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000614
Steve Naroff752d6ef2007-10-30 16:42:30 +0000615 SourceLocation LocStart = PDecl->getLocStart();
616
617 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000618 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000619
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000620 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000621 E = PDecl->instmeth_end(); I != E; ++I)
622 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000623 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 E = PDecl->classmeth_end(); I != E; ++I)
625 RewriteMethodDeclaration(*I);
626
Steve Naroff752d6ef2007-10-30 16:42:30 +0000627 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000628 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000629 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000630
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000631 // Must comment out @optional/@required
632 const char *startBuf = SM->getCharacterData(LocStart);
633 const char *endBuf = SM->getCharacterData(LocEnd);
634 for (const char *p = startBuf; p < endBuf; p++) {
635 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
636 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000637 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000638 ReplaceText(OptionalLoc, strlen("@optional"),
639 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000640
641 }
642 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
643 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000644 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000645 ReplaceText(OptionalLoc, strlen("@required"),
646 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000647
648 }
649 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000650}
651
Steve Naroffb29b4272008-04-14 22:03:09 +0000652void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000653 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000654 if (LocStart.isInvalid())
655 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000656 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000657 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000658}
659
Steve Naroffb29b4272008-04-14 22:03:09 +0000660void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000661 std::string &ResultStr) {
662 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000664 ResultStr += "id";
665 else
666 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000667 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000668
669 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000670 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000671
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000672 if (OMD->isInstance())
673 NameStr += "_I_";
674 else
675 NameStr += "_C_";
676
677 NameStr += OMD->getClassInterface()->getName();
678 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679
680 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000681 if (ObjCCategoryImplDecl *CID =
682 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000683 NameStr += CID->getName();
684 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685 }
Steve Naroff563b8282008-04-04 22:23:44 +0000686 // Append selector names, replacing ':' with '_'
687 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000688 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000689 else {
690 std::string selString = OMD->getSelector().getName();
691 int len = selString.size();
692 for (int i = 0; i < len; i++)
693 if (selString[i] == ':')
694 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000695 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000696 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000697 // Remember this name for metadata emission
698 MethodInternalNames[OMD] = NameStr;
699 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000700
701 // Rewrite arguments
702 ResultStr += "(";
703
704 // invisible arguments
705 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000707 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000708 if (!LangOpts.Microsoft) {
709 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
710 ResultStr += "struct ";
711 }
712 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000713 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000714 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 }
716 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000717 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000718
719 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000721 ResultStr += " _cmd";
722
723 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000724 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000725 ParmVarDecl *PDecl = OMD->getParamDecl(i);
726 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000727 if (PDecl->getType()->isObjCQualifiedIdType()) {
728 ResultStr += "id ";
729 ResultStr += PDecl->getName();
730 } else {
731 std::string Name = PDecl->getName();
732 PDecl->getType().getAsStringInternal(Name);
733 ResultStr += Name;
734 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000735 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000736 if (OMD->isVariadic())
737 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000738 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000739
740}
Steve Naroffb29b4272008-04-14 22:03:09 +0000741void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000742 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
743 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000744
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000745 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000746 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000747 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000748 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000749
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000750 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000751 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
752 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000753 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 ObjCMethodDecl *OMD = *I;
755 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000756 SourceLocation LocStart = OMD->getLocStart();
757 SourceLocation LocEnd = OMD->getBody()->getLocStart();
758
759 const char *startBuf = SM->getCharacterData(LocStart);
760 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(LocStart, endBuf-startBuf,
762 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000763 }
764
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000765 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000766 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
767 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000768 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769 ObjCMethodDecl *OMD = *I;
770 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000771 SourceLocation LocStart = OMD->getLocStart();
772 SourceLocation LocEnd = OMD->getBody()->getLocStart();
773
774 const char *startBuf = SM->getCharacterData(LocStart);
775 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000776 ReplaceText(LocStart, endBuf-startBuf,
777 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000778 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000779 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000780 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000781 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000782 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000783}
784
Steve Naroffb29b4272008-04-14 22:03:09 +0000785void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000786 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000787 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000788 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000789 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000790 ResultStr += ClassDecl->getName();
791 ResultStr += "\n";
792 ResultStr += "#define _REWRITER_typedef_";
793 ResultStr += ClassDecl->getName();
794 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000795 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000796 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000797 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000798 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000799 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000800 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000802
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000803 RewriteProperties(ClassDecl->getNumPropertyDecl(),
804 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000806 E = ClassDecl->instmeth_end(); I != E; ++I)
807 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000808 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000809 E = ClassDecl->classmeth_end(); I != E; ++I)
810 RewriteMethodDeclaration(*I);
811
Steve Naroff2feac5e2007-10-30 03:43:13 +0000812 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000813 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000814}
815
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000816Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
817 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000818 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000819 if (CurMethodDecl) {
820 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000821 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
822 // lookup which class implements the instance variable.
823 ObjCInterfaceDecl *clsDeclared = 0;
824 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
825 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
826
827 // Synthesize an explicit cast to gain access to the ivar.
828 std::string RecName = clsDeclared->getIdentifier()->getName();
829 RecName += "_IMPL";
830 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
831 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
832 SourceLocation(), II, 0);
833 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
834 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
835 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
836 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000837 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
838 IV->getBase()->getLocEnd(),
839 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000840 if (IV->isFreeIvar() &&
841 CurMethodDecl->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000842 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
843 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000844 ReplaceStmt(IV, ME);
845 delete IV;
846 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000847 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000848
849 ReplaceStmt(IV->getBase(), PE);
850 // Cannot delete IV->getBase(), since PE points to it.
851 // Replace the old base with the cast. This is important when doing
852 // embedded rewrites. For example, [newInv->_container addObject:0].
853 IV->setBase(PE);
854 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000855 }
Steve Naroff84472a82008-04-18 21:55:08 +0000856 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000857 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
858
859 // Explicit ivar refs need to have a cast inserted.
860 // FIXME: consider sharing some of this code with the code above.
861 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000862 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000863 // lookup which class implements the instance variable.
864 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000865 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000866 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
867
868 // Synthesize an explicit cast to gain access to the ivar.
869 std::string RecName = clsDeclared->getIdentifier()->getName();
870 RecName += "_IMPL";
871 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
872 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
873 SourceLocation(), II, 0);
874 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
875 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
876 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
877 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000878 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
879 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000880 ReplaceStmt(IV->getBase(), PE);
881 // Cannot delete IV->getBase(), since PE points to it.
882 // Replace the old base with the cast. This is important when doing
883 // embedded rewrites. For example, [newInv->_container addObject:0].
884 IV->setBase(PE);
885 return IV;
886 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000887 }
Steve Naroff84472a82008-04-18 21:55:08 +0000888 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000889}
890
Chris Lattnerf04da132007-10-24 17:06:59 +0000891//===----------------------------------------------------------------------===//
892// Function Body / Expression rewriting
893//===----------------------------------------------------------------------===//
894
Steve Naroffb29b4272008-04-14 22:03:09 +0000895Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000896 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
897 isa<DoStmt>(S) || isa<ForStmt>(S))
898 Stmts.push_back(S);
899 else if (isa<ObjCForCollectionStmt>(S)) {
900 Stmts.push_back(S);
901 ObjCBcLabelNo.push_back(++BcLabelCount);
902 }
903
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000904 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +0000905
906 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000907 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
908 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000909 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000910 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000911 if (newStmt)
912 *CI = newStmt;
913 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000914
915 // Handle specific things.
916 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
917 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000918
919 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000920 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +0000921
922 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
923 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000924
Steve Naroffbeaf2992007-11-03 11:27:19 +0000925 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
926 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000927
Steve Naroff934f2762007-10-24 22:48:43 +0000928 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
929 // Before we rewrite it, put the original message expression in a comment.
930 SourceLocation startLoc = MessExpr->getLocStart();
931 SourceLocation endLoc = MessExpr->getLocEnd();
932
933 const char *startBuf = SM->getCharacterData(startLoc);
934 const char *endBuf = SM->getCharacterData(endLoc);
935
936 std::string messString;
937 messString += "// ";
938 messString.append(startBuf, endBuf-startBuf+1);
939 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000940
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000941 // FIXME: Missing definition of
942 // InsertText(clang::SourceLocation, char const*, unsigned int).
943 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000944 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000945 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000946 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000947 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000948
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000949 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
950 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000951
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000952 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
953 return RewriteObjCSynchronizedStmt(StmtTry);
954
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000955 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
956 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000957
958 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
959 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000960
961 if (ObjCForCollectionStmt *StmtForCollection =
962 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000963 return RewriteObjCForCollectionStmt(StmtForCollection,
964 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000965 if (BreakStmt *StmtBreakStmt =
966 dyn_cast<BreakStmt>(S))
967 return RewriteBreakStmt(StmtBreakStmt);
968 if (ContinueStmt *StmtContinueStmt =
969 dyn_cast<ContinueStmt>(S))
970 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000971
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000972 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
973 isa<DoStmt>(S) || isa<ForStmt>(S)) {
974 assert(!Stmts.empty() && "Statement stack is empty");
975 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
976 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
977 && "Statement stack mismatch");
978 Stmts.pop_back();
979 }
Steve Naroff874e2322007-11-15 10:28:18 +0000980#if 0
981 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
982 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
983 // Get the new text.
984 std::ostringstream Buf;
985 Replacement->printPretty(Buf);
986 const std::string &Str = Buf.str();
987
988 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000989 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000990 delete S;
991 return Replacement;
992 }
993#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000994 // Return this stmt unmodified.
995 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000996}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000997
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000998/// SynthCountByEnumWithState - To print:
999/// ((unsigned int (*)
1000/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1001/// (void *)objc_msgSend)((id)l_collection,
1002/// sel_registerName(
1003/// "countByEnumeratingWithState:objects:count:"),
1004/// &enumState,
1005/// (id *)items, (unsigned int)16)
1006///
Steve Naroffb29b4272008-04-14 22:03:09 +00001007void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001008 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1009 "id *, unsigned int))(void *)objc_msgSend)";
1010 buf += "\n\t\t";
1011 buf += "((id)l_collection,\n\t\t";
1012 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1013 buf += "\n\t\t";
1014 buf += "&enumState, "
1015 "(id *)items, (unsigned int)16)";
1016}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001017
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001018/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1019/// statement to exit to its outer synthesized loop.
1020///
Steve Naroffb29b4272008-04-14 22:03:09 +00001021Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001022 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1023 return S;
1024 // replace break with goto __break_label
1025 std::string buf;
1026
1027 SourceLocation startLoc = S->getLocStart();
1028 buf = "goto __break_label_";
1029 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001030 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001031
1032 return 0;
1033}
1034
1035/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1036/// statement to continue with its inner synthesized loop.
1037///
Steve Naroffb29b4272008-04-14 22:03:09 +00001038Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001039 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1040 return S;
1041 // replace continue with goto __continue_label
1042 std::string buf;
1043
1044 SourceLocation startLoc = S->getLocStart();
1045 buf = "goto __continue_label_";
1046 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001047 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001048
1049 return 0;
1050}
1051
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001052/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001053/// It rewrites:
1054/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001055
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001056/// Into:
1057/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058/// type elem;
1059/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001060/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001061/// id l_collection = (id)collection;
1062/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1063/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001064/// if (limit) {
1065/// unsigned long startMutations = *enumState.mutationsPtr;
1066/// do {
1067/// unsigned long counter = 0;
1068/// do {
1069/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001070/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001071/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001072/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001073/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001074/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1076/// objects:items count:16]);
1077/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001078/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001079/// }
1080/// else
1081/// elem = nil;
1082/// }
1083///
Steve Naroffb29b4272008-04-14 22:03:09 +00001084Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001085 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001086 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1087 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1088 "ObjCForCollectionStmt Statement stack mismatch");
1089 assert(!ObjCBcLabelNo.empty() &&
1090 "ObjCForCollectionStmt - Label No stack empty");
1091
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001093 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001094 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001095 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001096 std::string buf;
1097 buf = "\n{\n\t";
1098 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1099 // type elem;
1100 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001101 elementTypeAsString = ElementType.getAsString();
1102 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 buf += " ";
1104 elementName = DS->getDecl()->getName();
1105 buf += elementName;
1106 buf += ";\n\t";
1107 }
Chris Lattner06767512008-04-08 05:52:18 +00001108 else {
1109 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001110 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001111 elementTypeAsString = DR->getDecl()->getType().getAsString();
1112 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001113
1114 // struct __objcFastEnumerationState enumState = { 0 };
1115 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1116 // id items[16];
1117 buf += "id items[16];\n\t";
1118 // id l_collection = (id)
1119 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001120 // Find start location of 'collection' the hard way!
1121 const char *startCollectionBuf = startBuf;
1122 startCollectionBuf += 3; // skip 'for'
1123 startCollectionBuf = strchr(startCollectionBuf, '(');
1124 startCollectionBuf++; // skip '('
1125 // find 'in' and skip it.
1126 while (*startCollectionBuf != ' ' ||
1127 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1128 (*(startCollectionBuf+3) != ' ' &&
1129 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1130 startCollectionBuf++;
1131 startCollectionBuf += 3;
1132
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001133 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001134 ReplaceText(startLoc, startCollectionBuf - startBuf,
1135 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001137 SourceLocation rightParenLoc = S->getRParenLoc();
1138 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1139 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001140 buf = ";\n\t";
1141
1142 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1143 // objects:items count:16];
1144 // which is synthesized into:
1145 // unsigned int limit =
1146 // ((unsigned int (*)
1147 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1148 // (void *)objc_msgSend)((id)l_collection,
1149 // sel_registerName(
1150 // "countByEnumeratingWithState:objects:count:"),
1151 // (struct __objcFastEnumerationState *)&state,
1152 // (id *)items, (unsigned int)16);
1153 buf += "unsigned long limit =\n\t\t";
1154 SynthCountByEnumWithState(buf);
1155 buf += ";\n\t";
1156 /// if (limit) {
1157 /// unsigned long startMutations = *enumState.mutationsPtr;
1158 /// do {
1159 /// unsigned long counter = 0;
1160 /// do {
1161 /// if (startMutations != *enumState.mutationsPtr)
1162 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001163 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001164 buf += "if (limit) {\n\t";
1165 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1166 buf += "do {\n\t\t";
1167 buf += "unsigned long counter = 0;\n\t\t";
1168 buf += "do {\n\t\t\t";
1169 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1170 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1171 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001172 buf += " = (";
1173 buf += elementTypeAsString;
1174 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001176 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001177
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001178 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001179 /// } while (counter < limit);
1180 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1181 /// objects:items count:16]);
1182 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001183 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001184 /// }
1185 /// else
1186 /// elem = nil;
1187 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001188 ///
1189 buf = ";\n\t";
1190 buf += "__continue_label_";
1191 buf += utostr(ObjCBcLabelNo.back());
1192 buf += ": ;";
1193 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001194 buf += "} while (counter < limit);\n\t";
1195 buf += "} while (limit = ";
1196 SynthCountByEnumWithState(buf);
1197 buf += ");\n\t";
1198 buf += elementName;
1199 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001200 buf += "__break_label_";
1201 buf += utostr(ObjCBcLabelNo.back());
1202 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001203 buf += "}\n\t";
1204 buf += "else\n\t\t";
1205 buf += elementName;
1206 buf += " = nil;\n";
1207 buf += "}\n";
1208 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001209 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001210 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001211 Stmts.pop_back();
1212 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001213 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001214}
1215
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001216/// RewriteObjCSynchronizedStmt -
1217/// This routine rewrites @synchronized(expr) stmt;
1218/// into:
1219/// objc_sync_enter(expr);
1220/// @try stmt @finally { objc_sync_exit(expr); }
1221///
Steve Naroffb29b4272008-04-14 22:03:09 +00001222Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001223 // Get the start location and compute the semi location.
1224 SourceLocation startLoc = S->getLocStart();
1225 const char *startBuf = SM->getCharacterData(startLoc);
1226
1227 assert((*startBuf == '@') && "bogus @synchronized location");
1228
1229 std::string buf;
1230 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001231 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001232 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1233 const char *endBuf = SM->getCharacterData(endLoc);
1234 endBuf++;
1235 const char *rparenBuf = strchr(endBuf, ')');
1236 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1237 buf = ");\n";
1238 // declare a new scope with two variables, _stack and _rethrow.
1239 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1240 buf += "int buf[18/*32-bit i386*/];\n";
1241 buf += "char *pointers[4];} _stack;\n";
1242 buf += "id volatile _rethrow = 0;\n";
1243 buf += "objc_exception_try_enter(&_stack);\n";
1244 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001245 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001246 startLoc = S->getSynchBody()->getLocEnd();
1247 startBuf = SM->getCharacterData(startLoc);
1248
1249 assert((*startBuf == '}') && "bogus @try block");
1250 SourceLocation lastCurlyLoc = startLoc;
1251 buf = "}\nelse {\n";
1252 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1253 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1254 // FIXME: This must be objc_sync_exit(syncExpr);
1255 buf += " objc_sync_exit();\n";
1256 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1257 buf += "}\n";
1258 buf += "}";
1259
Chris Lattneraadaf782008-01-31 19:51:04 +00001260 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001261 return 0;
1262}
1263
Steve Naroffb29b4272008-04-14 22:03:09 +00001264Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001265 // Get the start location and compute the semi location.
1266 SourceLocation startLoc = S->getLocStart();
1267 const char *startBuf = SM->getCharacterData(startLoc);
1268
1269 assert((*startBuf == '@') && "bogus @try location");
1270
1271 std::string buf;
1272 // declare a new scope with two variables, _stack and _rethrow.
1273 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1274 buf += "int buf[18/*32-bit i386*/];\n";
1275 buf += "char *pointers[4];} _stack;\n";
1276 buf += "id volatile _rethrow = 0;\n";
1277 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001278 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001279
Chris Lattneraadaf782008-01-31 19:51:04 +00001280 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001281
1282 startLoc = S->getTryBody()->getLocEnd();
1283 startBuf = SM->getCharacterData(startLoc);
1284
1285 assert((*startBuf == '}') && "bogus @try block");
1286
1287 SourceLocation lastCurlyLoc = startLoc;
1288
1289 startLoc = startLoc.getFileLocWithOffset(1);
1290 buf = " /* @catch begin */ else {\n";
1291 buf += " id _caught = objc_exception_extract(&_stack);\n";
1292 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001293 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001294 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1295 buf += " else { /* @catch continue */";
1296
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001297 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001298
1299 bool sawIdTypedCatch = false;
1300 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001301 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001302 while (catchList) {
1303 Stmt *catchStmt = catchList->getCatchParamStmt();
1304
1305 if (catchList == S->getCatchStmts())
1306 buf = "if ("; // we are generating code for the first catch clause
1307 else
1308 buf = "else if (";
1309 startLoc = catchList->getLocStart();
1310 startBuf = SM->getCharacterData(startLoc);
1311
1312 assert((*startBuf == '@') && "bogus @catch location");
1313
1314 const char *lParenLoc = strchr(startBuf, '(');
1315
Steve Naroffbe4b3332008-02-01 22:08:12 +00001316 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001317 // Now rewrite the body...
1318 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001319 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1320 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001321 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1322 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001323 assert((*bodyBuf == '{') && "bogus @catch body location");
1324
1325 buf += "1) { id _tmp = _caught;";
1326 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1327 buf.c_str(), buf.size());
1328 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001329 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001331 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001332 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001333 sawIdTypedCatch = true;
1334 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001335 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001336
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001337 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001338 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001339 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001340 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001341 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001342 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001343 }
1344 }
1345 // Now rewrite the body...
1346 lastCatchBody = catchList->getCatchBody();
1347 SourceLocation rParenLoc = catchList->getRParenLoc();
1348 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1349 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1350 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1351 assert((*rParenBuf == ')') && "bogus @catch paren location");
1352 assert((*bodyBuf == '{') && "bogus @catch body location");
1353
1354 buf = " = _caught;";
1355 // Here we replace ") {" with "= _caught;" (which initializes and
1356 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001357 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001358 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001359 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001360 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001361 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001362 catchList = catchList->getNextCatchStmt();
1363 }
1364 // Complete the catch list...
1365 if (lastCatchBody) {
1366 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001367 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1368 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001369 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1370 buf = " } } /* @catch end */\n";
1371
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001372 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001373
1374 // Set lastCurlyLoc
1375 lastCurlyLoc = lastCatchBody->getLocEnd();
1376 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001377 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001378 startLoc = finalStmt->getLocStart();
1379 startBuf = SM->getCharacterData(startLoc);
1380 assert((*startBuf == '@') && "bogus @finally start");
1381
1382 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001383 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001384
1385 Stmt *body = finalStmt->getFinallyBody();
1386 SourceLocation startLoc = body->getLocStart();
1387 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001388 assert(*SM->getCharacterData(startLoc) == '{' &&
1389 "bogus @finally body location");
1390 assert(*SM->getCharacterData(endLoc) == '}' &&
1391 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001392
1393 startLoc = startLoc.getFileLocWithOffset(1);
1394 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001395 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001396 endLoc = endLoc.getFileLocWithOffset(-1);
1397 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001398 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001399
1400 // Set lastCurlyLoc
1401 lastCurlyLoc = body->getLocEnd();
1402 }
1403 // Now emit the final closing curly brace...
1404 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1405 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001406 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001407 return 0;
1408}
1409
Steve Naroffb29b4272008-04-14 22:03:09 +00001410Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001411 return 0;
1412}
1413
Steve Naroffb29b4272008-04-14 22:03:09 +00001414Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001415 return 0;
1416}
1417
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001418// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001419// the throw expression is typically a message expression that's already
1420// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001421Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001422 // Get the start location and compute the semi location.
1423 SourceLocation startLoc = S->getLocStart();
1424 const char *startBuf = SM->getCharacterData(startLoc);
1425
1426 assert((*startBuf == '@') && "bogus @throw location");
1427
1428 std::string buf;
1429 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001430 if (S->getThrowExpr())
1431 buf = "objc_exception_throw(";
1432 else // add an implicit argument
1433 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001434 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001435 const char *semiBuf = strchr(startBuf, ';');
1436 assert((*semiBuf == ';') && "@throw: can't find ';'");
1437 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1438 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001439 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001440 return 0;
1441}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001442
Steve Naroffb29b4272008-04-14 22:03:09 +00001443Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001444 // Create a new string expression.
1445 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001446 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001447 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1448 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001449 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1450 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001451 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001452 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001453
Chris Lattner07506182007-11-30 22:53:43 +00001454 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001455 delete Exp;
1456 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001457}
1458
Steve Naroffb29b4272008-04-14 22:03:09 +00001459Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001460 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1461 // Create a call to sel_registerName("selName").
1462 llvm::SmallVector<Expr*, 8> SelExprs;
1463 QualType argType = Context->getPointerType(Context->CharTy);
1464 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1465 Exp->getSelector().getName().size(),
1466 false, argType, SourceLocation(),
1467 SourceLocation()));
1468 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1469 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001470 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001471 delete Exp;
1472 return SelExp;
1473}
1474
Steve Naroffb29b4272008-04-14 22:03:09 +00001475CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001476 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001477 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001478 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001479
1480 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001481 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001482
1483 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001484 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001485 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1486
1487 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001488
Steve Naroff934f2762007-10-24 22:48:43 +00001489 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1490}
1491
Steve Naroffd5255f52007-11-01 13:24:47 +00001492static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1493 const char *&startRef, const char *&endRef) {
1494 while (startBuf < endBuf) {
1495 if (*startBuf == '<')
1496 startRef = startBuf; // mark the start.
1497 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001498 if (startRef && *startRef == '<') {
1499 endRef = startBuf; // mark the end.
1500 return true;
1501 }
1502 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001503 }
1504 startBuf++;
1505 }
1506 return false;
1507}
1508
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001509static void scanToNextArgument(const char *&argRef) {
1510 int angle = 0;
1511 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1512 if (*argRef == '<')
1513 angle++;
1514 else if (*argRef == '>')
1515 angle--;
1516 argRef++;
1517 }
1518 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1519}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001520
Steve Naroffb29b4272008-04-14 22:03:09 +00001521bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001522
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001523 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001524 return true;
1525
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001526 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001527 return true;
1528
Steve Naroffd5255f52007-11-01 13:24:47 +00001529 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001530 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001531 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001532 return true; // we have "Class <Protocol> *".
1533 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001534 return false;
1535}
1536
Steve Naroffb29b4272008-04-14 22:03:09 +00001537void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001538 SourceLocation Loc;
1539 QualType Type;
1540 const FunctionTypeProto *proto = 0;
1541 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1542 Loc = VD->getLocation();
1543 Type = VD->getType();
1544 }
1545 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1546 Loc = FD->getLocation();
1547 // Check for ObjC 'id' and class types that have been adorned with protocol
1548 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1549 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1550 assert(funcType && "missing function type");
1551 proto = dyn_cast<FunctionTypeProto>(funcType);
1552 if (!proto)
1553 return;
1554 Type = proto->getResultType();
1555 }
1556 else
1557 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001558
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001559 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001560 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001561
1562 const char *endBuf = SM->getCharacterData(Loc);
1563 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001564 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001565 startBuf--; // scan backward (from the decl location) for return type.
1566 const char *startRef = 0, *endRef = 0;
1567 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1568 // Get the locations of the startRef, endRef.
1569 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1570 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1571 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001572 InsertText(LessLoc, "/*", 2);
1573 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001574 }
1575 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001576 if (!proto)
1577 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001578 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001579 const char *startBuf = SM->getCharacterData(Loc);
1580 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001581 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1582 if (needToScanForQualifiers(proto->getArgType(i))) {
1583 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001584
Steve Naroffd5255f52007-11-01 13:24:47 +00001585 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001586 // scan forward (from the decl location) for argument types.
1587 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001588 const char *startRef = 0, *endRef = 0;
1589 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1590 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001591 SourceLocation LessLoc =
1592 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1593 SourceLocation GreaterLoc =
1594 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001595 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001596 InsertText(LessLoc, "/*", 2);
1597 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001598 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001599 startBuf = ++endBuf;
1600 }
1601 else {
1602 while (*startBuf != ')' && *startBuf != ',')
1603 startBuf++; // scan forward (from the decl location) for argument types.
1604 startBuf++;
1605 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001606 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001607}
1608
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001609// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001610void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001611 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1612 llvm::SmallVector<QualType, 16> ArgTys;
1613 ArgTys.push_back(Context->getPointerType(
1614 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001615 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001616 &ArgTys[0], ArgTys.size(),
1617 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001618 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001619 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001620 SelGetUidIdent, getFuncType,
1621 FunctionDecl::Extern, false, 0);
1622}
1623
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001624// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001625void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001626 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1627 llvm::SmallVector<QualType, 16> ArgTys;
1628 ArgTys.push_back(Context->getPointerType(
1629 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001630 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001631 &ArgTys[0], ArgTys.size(),
1632 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001633 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001634 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001635 SelGetProtoIdent, getFuncType,
1636 FunctionDecl::Extern, false, 0);
1637}
1638
Steve Naroffb29b4272008-04-14 22:03:09 +00001639void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001640 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001641 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001642 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001643 return;
1644 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001645 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001646}
1647
Steve Naroffc0a123c2008-03-11 17:37:02 +00001648// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001649void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001650 if (SuperContructorFunctionDecl)
1651 return;
1652 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1653 llvm::SmallVector<QualType, 16> ArgTys;
1654 QualType argT = Context->getObjCIdType();
1655 assert(!argT.isNull() && "Can't find 'id' type");
1656 ArgTys.push_back(argT);
1657 ArgTys.push_back(argT);
1658 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1659 &ArgTys[0], ArgTys.size(),
1660 false);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001661 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001662 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001663 msgSendIdent, msgSendType,
1664 FunctionDecl::Extern, false, 0);
1665}
1666
Steve Naroff09b266e2007-10-30 23:14:51 +00001667// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001668void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001669 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1670 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001672 assert(!argT.isNull() && "Can't find 'id' type");
1673 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001674 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001675 assert(!argT.isNull() && "Can't find 'SEL' type");
1676 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001677 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001678 &ArgTys[0], ArgTys.size(),
1679 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001680 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001681 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001682 msgSendIdent, msgSendType,
1683 FunctionDecl::Extern, false, 0);
1684}
1685
Steve Naroff874e2322007-11-15 10:28:18 +00001686// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001687void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001688 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1689 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001690 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001691 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001692 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001693 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1694 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1695 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001696 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001697 assert(!argT.isNull() && "Can't find 'SEL' type");
1698 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001699 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001700 &ArgTys[0], ArgTys.size(),
1701 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001702 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001703 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001704 msgSendIdent, msgSendType,
1705 FunctionDecl::Extern, false, 0);
1706}
1707
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001708// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001709void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001710 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1711 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001712 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001713 assert(!argT.isNull() && "Can't find 'id' type");
1714 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001715 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001716 assert(!argT.isNull() && "Can't find 'SEL' type");
1717 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001718 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001719 &ArgTys[0], ArgTys.size(),
1720 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001721 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001722 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001723 msgSendIdent, msgSendType,
1724 FunctionDecl::Extern, false, 0);
1725}
1726
1727// SynthMsgSendSuperStretFunctionDecl -
1728// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001729void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001730 IdentifierInfo *msgSendIdent =
1731 &Context->Idents.get("objc_msgSendSuper_stret");
1732 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001733 RecordDecl *RD = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001734 SourceLocation(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001735 &Context->Idents.get("objc_super"), 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001736 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1737 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1738 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001740 assert(!argT.isNull() && "Can't find 'SEL' type");
1741 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001743 &ArgTys[0], ArgTys.size(),
1744 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001745 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001746 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001747 msgSendIdent, msgSendType,
1748 FunctionDecl::Extern, false, 0);
1749}
1750
Steve Naroff1284db82008-05-08 22:02:18 +00001751// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001752void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001753 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1754 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001755 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001756 assert(!argT.isNull() && "Can't find 'id' type");
1757 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001758 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001759 assert(!argT.isNull() && "Can't find 'SEL' type");
1760 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001761 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001762 &ArgTys[0], ArgTys.size(),
1763 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001764 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001765 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001766 msgSendIdent, msgSendType,
1767 FunctionDecl::Extern, false, 0);
1768}
1769
Steve Naroff09b266e2007-10-30 23:14:51 +00001770// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001771void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001772 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1773 llvm::SmallVector<QualType, 16> ArgTys;
1774 ArgTys.push_back(Context->getPointerType(
1775 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001776 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001777 &ArgTys[0], ArgTys.size(),
1778 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001779 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001780 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001781 getClassIdent, getClassType,
1782 FunctionDecl::Extern, false, 0);
1783}
1784
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001785// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001786void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001787 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1788 llvm::SmallVector<QualType, 16> ArgTys;
1789 ArgTys.push_back(Context->getPointerType(
1790 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001791 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001792 &ArgTys[0], ArgTys.size(),
1793 false /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001794 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001795 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001796 getClassIdent, getClassType,
1797 FunctionDecl::Extern, false, 0);
1798}
1799
Steve Naroffb29b4272008-04-14 22:03:09 +00001800Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001801 QualType strType = getConstantStringStructType();
1802
1803 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001804
1805 std::string tmpName = InFileName;
1806 unsigned i;
1807 for (i=0; i < tmpName.length(); i++) {
1808 char c = tmpName.at(i);
1809 // replace any non alphanumeric characters with '_'.
1810 if (!isalpha(c) && (c < '0' || c > '9'))
1811 tmpName[i] = '_';
1812 }
1813 S += tmpName;
1814 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001815 S += utostr(NumObjCStringLiterals++);
1816
Steve Naroffba92b2e2008-03-27 22:29:16 +00001817 Preamble += "static __NSConstantStringImpl " + S;
1818 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1819 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001820 // The pretty printer for StringLiteral handles escape characters properly.
1821 std::ostringstream prettyBuf;
1822 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001823 Preamble += prettyBuf.str();
1824 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001825 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001826 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001827
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001828 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001829 &Context->Idents.get(S.c_str()), strType,
1830 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001831 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1832 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1833 Context->getPointerType(DRE->getType()),
1834 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001835 // cast to NSConstantString *
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001836 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001837 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001838 delete Exp;
1839 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001840}
1841
Steve Naroffb29b4272008-04-14 22:03:09 +00001842ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001843 // check if we are sending a message to 'super'
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001844 if (!CurMethodDecl || !CurMethodDecl->isInstance()) return 0;
1845
1846 CastExpr *CE = dyn_cast<CastExpr>(recExpr);
1847 if (!CE) return 0;
1848
1849 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr());
1850 if (!DRE) return 0;
1851
1852 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl());
1853 if (!PVD) return 0;
1854
1855 if (strcmp(PVD->getName(), "self") != 0)
1856 return 0;
1857
1858 // is this id<P1..> type?
1859 if (CE->getType()->isObjCQualifiedIdType())
1860 return 0;
1861 const PointerType *PT = CE->getType()->getAsPointerType();
1862 if (!PT) return 0;
1863
1864 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
1865 if (!IT) return 0;
1866
1867 if (IT->getDecl() != CurMethodDecl->getClassInterface()->getSuperClass())
1868 return 0;
1869
1870 return IT->getDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001871}
1872
1873// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001874QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001875 if (!SuperStructDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001876 SuperStructDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001877 SourceLocation(),
1878 &Context->Idents.get("objc_super"), 0);
Steve Naroff874e2322007-11-15 10:28:18 +00001879 QualType FieldTypes[2];
1880
1881 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001883 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001885 // Create fields
1886 FieldDecl *FieldDecls[2];
1887
1888 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001889 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001890 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001891
1892 SuperStructDecl->defineBody(FieldDecls, 4);
1893 }
1894 return Context->getTagDeclType(SuperStructDecl);
1895}
1896
Steve Naroffb29b4272008-04-14 22:03:09 +00001897QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001898 if (!ConstantStringDecl) {
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001899 ConstantStringDecl = RecordDecl::Create(*Context, Decl::Struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001900 SourceLocation(),
1901 &Context->Idents.get("__NSConstantStringImpl"), 0);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001902 QualType FieldTypes[4];
1903
1904 // struct objc_object *receiver;
1905 FieldTypes[0] = Context->getObjCIdType();
1906 // int flags;
1907 FieldTypes[1] = Context->IntTy;
1908 // char *str;
1909 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1910 // long length;
1911 FieldTypes[3] = Context->LongTy;
1912 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001913 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001914
1915 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001916 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001917 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001918
1919 ConstantStringDecl->defineBody(FieldDecls, 4);
1920 }
1921 return Context->getTagDeclType(ConstantStringDecl);
1922}
1923
Steve Naroffb29b4272008-04-14 22:03:09 +00001924Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001925 if (!SelGetUidFunctionDecl)
1926 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001927 if (!MsgSendFunctionDecl)
1928 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001929 if (!MsgSendSuperFunctionDecl)
1930 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001931 if (!MsgSendStretFunctionDecl)
1932 SynthMsgSendStretFunctionDecl();
1933 if (!MsgSendSuperStretFunctionDecl)
1934 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001935 if (!MsgSendFpretFunctionDecl)
1936 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001937 if (!GetClassFunctionDecl)
1938 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001939 if (!GetMetaClassFunctionDecl)
1940 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001941
Steve Naroff874e2322007-11-15 10:28:18 +00001942 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001943 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1944 // May need to use objc_msgSend_stret() as well.
1945 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001946 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001947 QualType resultType = mDecl->getResultType();
1948 if (resultType.getCanonicalType()->isStructureType()
1949 || resultType.getCanonicalType()->isUnionType())
1950 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001951 else if (resultType.getCanonicalType()->isRealFloatingType())
1952 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001953 }
Steve Naroff874e2322007-11-15 10:28:18 +00001954
Steve Naroff934f2762007-10-24 22:48:43 +00001955 // Synthesize a call to objc_msgSend().
1956 llvm::SmallVector<Expr*, 8> MsgExprs;
1957 IdentifierInfo *clsName = Exp->getClassName();
1958
1959 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1960 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001961 if (!strcmp(clsName->getName(), "super")) {
1962 MsgSendFlavor = MsgSendSuperFunctionDecl;
1963 if (MsgSendStretFlavor)
1964 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1965 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1966
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001967 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001968 CurMethodDecl->getClassInterface()->getSuperClass();
1969
1970 llvm::SmallVector<Expr*, 4> InitExprs;
1971
1972 // set the receiver to self, the first argument to all methods.
1973 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001974 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001975 SourceLocation()));
1976 llvm::SmallVector<Expr*, 8> ClsExprs;
1977 QualType argType = Context->getPointerType(Context->CharTy);
1978 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1979 SuperDecl->getIdentifier()->getLength(),
1980 false, argType, SourceLocation(),
1981 SourceLocation()));
1982 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1983 &ClsExprs[0],
1984 ClsExprs.size());
1985 // To turn off a warning, type-cast to 'id'
1986 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001988 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1989 // struct objc_super
1990 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001991 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001992
Steve Naroff23f41272008-03-11 18:14:26 +00001993 if (LangOpts.Microsoft) {
1994 SynthSuperContructorFunctionDecl();
1995 // Simulate a contructor call...
1996 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1997 superType, SourceLocation());
1998 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1999 superType, SourceLocation());
2000 } else {
2001 // (struct objc_super) { <exprs from above> }
2002 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2003 &InitExprs[0], InitExprs.size(),
2004 SourceLocation());
2005 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2006 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002007 // struct objc_super *
2008 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2009 Context->getPointerType(SuperRep->getType()),
2010 SourceLocation());
2011 MsgExprs.push_back(Unop);
2012 } else {
2013 llvm::SmallVector<Expr*, 8> ClsExprs;
2014 QualType argType = Context->getPointerType(Context->CharTy);
2015 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2016 clsName->getLength(),
2017 false, argType, SourceLocation(),
2018 SourceLocation()));
2019 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2020 &ClsExprs[0],
2021 ClsExprs.size());
2022 MsgExprs.push_back(Cls);
2023 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002024 } else { // instance message.
2025 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002026
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002028 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002029 if (MsgSendStretFlavor)
2030 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002031 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2032
2033 llvm::SmallVector<Expr*, 4> InitExprs;
2034
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002035 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002037 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002038
2039 llvm::SmallVector<Expr*, 8> ClsExprs;
2040 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002041 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2042 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002043 false, argType, SourceLocation(),
2044 SourceLocation()));
2045 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002046 &ClsExprs[0],
2047 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002048 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002049 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002050 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002051 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00002052 // struct objc_super
2053 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002054 Expr *SuperRep;
2055
2056 if (LangOpts.Microsoft) {
2057 SynthSuperContructorFunctionDecl();
2058 // Simulate a contructor call...
2059 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2060 superType, SourceLocation());
2061 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2062 superType, SourceLocation());
2063 } else {
2064 // (struct objc_super) { <exprs from above> }
2065 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2066 &InitExprs[0], InitExprs.size(),
2067 SourceLocation());
2068 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2069 }
Steve Naroff874e2322007-11-15 10:28:18 +00002070 // struct objc_super *
2071 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2072 Context->getPointerType(SuperRep->getType()),
2073 SourceLocation());
2074 MsgExprs.push_back(Unop);
2075 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002076 // Remove all type-casts because it may contain objc-style types; e.g.
2077 // Foo<Proto> *.
2078 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
2079 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002080 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002081 MsgExprs.push_back(recExpr);
2082 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002083 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002084 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002085 llvm::SmallVector<Expr*, 8> SelExprs;
2086 QualType argType = Context->getPointerType(Context->CharTy);
2087 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2088 Exp->getSelector().getName().size(),
2089 false, argType, SourceLocation(),
2090 SourceLocation()));
2091 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2092 &SelExprs[0], SelExprs.size());
2093 MsgExprs.push_back(SelExp);
2094
2095 // Now push any user supplied arguments.
2096 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002097 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002098 // Make all implicit casts explicit...ICE comes in handy:-)
2099 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2100 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002101 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2102 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002103 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002104 }
2105 // Make id<P...> cast into an 'id' cast.
2106 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002107 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002108 while ((CE = dyn_cast<CastExpr>(userExpr)))
2109 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002111 userExpr, SourceLocation());
2112 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002113 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002114 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002115 // We've transferred the ownership to MsgExprs. Null out the argument in
2116 // the original expression, since we will delete it below.
2117 Exp->setArg(i, 0);
2118 }
Steve Naroffab972d32007-11-04 22:37:50 +00002119 // Generate the funky cast.
2120 CastExpr *cast;
2121 llvm::SmallVector<QualType, 8> ArgTypes;
2122 QualType returnType;
2123
2124 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002125 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2126 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2127 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002128 ArgTypes.push_back(Context->getObjCIdType());
2129 ArgTypes.push_back(Context->getObjCSelType());
2130 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002131 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002132 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002133 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2134 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002135 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002136 ArgTypes.push_back(t);
2137 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002138 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2139 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002140 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002141 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002142 }
2143 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002144 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002145
2146 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002147 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2148 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002149
2150 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2151 // If we don't do this cast, we get the following bizarre warning/note:
2152 // xx.m:13: warning: function called through a non-compatible type
2153 // xx.m:13: note: if this code is reached, the program will abort
2154 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2155 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002156
Steve Naroffab972d32007-11-04 22:37:50 +00002157 // Now do the "normal" pointer to function cast.
2158 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002159 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002160 // If we don't have a method decl, force a variadic cast.
2161 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002162 castType = Context->getPointerType(castType);
2163 cast = new CastExpr(castType, cast, SourceLocation());
2164
2165 // Don't forget the parens to enforce the proper binding.
2166 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2167
2168 const FunctionType *FT = msgSendType->getAsFunctionType();
2169 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2170 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002171 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002172 if (MsgSendStretFlavor) {
2173 // We have the method which returns a struct/union. Must also generate
2174 // call to objc_msgSend_stret and hang both varieties on a conditional
2175 // expression which dictate which one to envoke depending on size of
2176 // method's return type.
2177
2178 // Create a reference to the objc_msgSend_stret() declaration.
2179 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2180 SourceLocation());
2181 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2182 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2183 SourceLocation());
2184 // Now do the "normal" pointer to function cast.
2185 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002186 &ArgTypes[0], ArgTypes.size(),
2187 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002188 castType = Context->getPointerType(castType);
2189 cast = new CastExpr(castType, cast, SourceLocation());
2190
2191 // Don't forget the parens to enforce the proper binding.
2192 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2193
2194 FT = msgSendType->getAsFunctionType();
2195 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2196 FT->getResultType(), SourceLocation());
2197
2198 // Build sizeof(returnType)
2199 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2200 returnType, Context->getSizeType(),
2201 SourceLocation(), SourceLocation());
2202 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2203 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2204 // For X86 it is more complicated and some kind of target specific routine
2205 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002206 unsigned IntSize =
2207 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002208 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2209 Context->IntTy,
2210 SourceLocation());
2211 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2212 BinaryOperator::LE,
2213 Context->IntTy,
2214 SourceLocation());
2215 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2216 ConditionalOperator *CondExpr =
2217 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002218 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002219 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002220 return ReplacingStmt;
2221}
2222
Steve Naroffb29b4272008-04-14 22:03:09 +00002223Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002224 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002225 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002226 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002227
Chris Lattnere64b7772007-10-24 16:57:36 +00002228 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002229 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002230}
2231
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002232/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2233/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002234Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002235 if (!GetProtocolFunctionDecl)
2236 SynthGetProtocolFunctionDecl();
2237 // Create a call to objc_getProtocol("ProtocolName").
2238 llvm::SmallVector<Expr*, 8> ProtoExprs;
2239 QualType argType = Context->getPointerType(Context->CharTy);
2240 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2241 strlen(Exp->getProtocol()->getName()),
2242 false, argType, SourceLocation(),
2243 SourceLocation()));
2244 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2245 &ProtoExprs[0],
2246 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002247 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002248 delete Exp;
2249 return ProtoExp;
2250
2251}
2252
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002253/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002254/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002255void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002256 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002257 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2258 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002259 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002260 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002261 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002262 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002263 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002264 SourceLocation LocStart = CDecl->getLocStart();
2265 SourceLocation LocEnd = CDecl->getLocEnd();
2266
2267 const char *startBuf = SM->getCharacterData(LocStart);
2268 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002269 // If no ivars and no root or if its root, directly or indirectly,
2270 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002271 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2272 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002273 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002274 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002275 return;
2276 }
2277
2278 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002280 Result += "\nstruct ";
2281 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002282 if (LangOpts.Microsoft)
2283 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002284
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002285 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002286 const char *cursor = strchr(startBuf, '{');
2287 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002288 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002289
2290 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002291 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002292 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002293 Result = "\n struct ";
2294 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002295 Result += "_IMPL ";
2296 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002297 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002298
2299 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002300 SourceLocation OnePastCurly =
2301 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2302 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002303 }
2304 cursor++; // past '{'
2305
2306 // Now comment out any visibility specifiers.
2307 while (cursor < endBuf) {
2308 if (*cursor == '@') {
2309 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002310 // Skip whitespace.
2311 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2312 /*scan*/;
2313
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002314 // FIXME: presence of @public, etc. inside comment results in
2315 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002316 if (!strncmp(cursor, "public", strlen("public")) ||
2317 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002318 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002319 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002320 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002321 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002322 // FIXME: If there are cases where '<' is used in ivar declaration part
2323 // of user code, then scan the ivar list and use needToScanForQualifiers
2324 // for type checking.
2325 else if (*cursor == '<') {
2326 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002327 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002328 cursor = strchr(cursor, '>');
2329 cursor++;
2330 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002331 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002332 }
Steve Narofffea763e82007-11-14 19:25:57 +00002333 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002334 }
Steve Narofffea763e82007-11-14 19:25:57 +00002335 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002336 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002337 } else { // we don't have any instance variables - insert super struct.
2338 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2339 Result += " {\n struct ";
2340 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002341 Result += "_IMPL ";
2342 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002343 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002344 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002345 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002346 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002347 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002348 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002349}
2350
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002352/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002353void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002354 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002355 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002356 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002357 const char *ClassName,
2358 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002359 if (MethodBegin == MethodEnd) return;
2360
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002361 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002362 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002363 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002364 SEL _cmd;
2365 char *method_types;
2366 void *_imp;
2367 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002368 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002369 Result += "\nstruct _objc_method {\n";
2370 Result += "\tSEL _cmd;\n";
2371 Result += "\tchar *method_types;\n";
2372 Result += "\tvoid *_imp;\n";
2373 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002374
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002375 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002376 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002377
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002378 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002379
2380 /* struct {
2381 struct _objc_method_list *next_method;
2382 int method_count;
2383 struct _objc_method method_list[];
2384 }
2385 */
2386 Result += "\nstatic struct {\n";
2387 Result += "\tstruct _objc_method_list *next_method;\n";
2388 Result += "\tint method_count;\n";
2389 Result += "\tstruct _objc_method method_list[";
2390 Result += utostr(MethodEnd-MethodBegin);
2391 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002392 Result += prefix;
2393 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2394 Result += "_METHODS_";
2395 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002396 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002397 Result += IsInstanceMethod ? "inst" : "cls";
2398 Result += "_meth\")))= ";
2399 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002400
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002401 Result += "\t,{{(SEL)\"";
2402 Result += (*MethodBegin)->getSelector().getName().c_str();
2403 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002405 Result += "\", \"";
2406 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002407 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002408 Result += MethodInternalNames[*MethodBegin];
2409 Result += "}\n";
2410 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2411 Result += "\t ,{(SEL)\"";
2412 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002413 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002414 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002415 Result += "\", \"";
2416 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002417 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002418 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002419 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002420 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002421 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002422}
2423
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Steve Naroffb29b4272008-04-14 22:03:09 +00002425void RewriteObjC::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002426 int NumProtocols,
2427 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002428 const char *ClassName,
2429 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002430 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002431 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002432 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002434 // Output struct protocol_methods holder of method selector and type.
Chris Lattnerc8581052008-03-16 20:19:15 +00002435 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002436 /* struct protocol_methods {
2437 SEL _cmd;
2438 char *method_types;
2439 }
2440 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002441 Result += "\nstruct protocol_methods {\n";
2442 Result += "\tSEL _cmd;\n";
2443 Result += "\tchar *method_types;\n";
2444 Result += "};\n";
2445
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002446 objc_protocol_methods = true;
2447 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002448 // Do not synthesize the protocol more than once.
2449 if (ObjCSynthesizedProtocols.count(PDecl))
2450 continue;
2451
Chris Lattnerc8581052008-03-16 20:19:15 +00002452 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2453 unsigned NumMethods = PDecl->getNumInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002454 /* struct _objc_protocol_method_list {
2455 int protocol_method_count;
2456 struct protocol_methods protocols[];
2457 }
2458 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002459 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002460 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002461 Result += "\tstruct protocol_methods protocols[";
2462 Result += utostr(NumMethods);
2463 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002464 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002465 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002466 "{\n\t" + utostr(NumMethods) + "\n";
2467
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002468 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002470 E = PDecl->instmeth_end(); I != E; ++I) {
2471 if (I == PDecl->instmeth_begin())
2472 Result += "\t ,{{(SEL)\"";
2473 else
2474 Result += "\t ,{(SEL)\"";
2475 Result += (*I)->getSelector().getName().c_str();
2476 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002478 Result += "\", \"";
2479 Result += MethodTypeString;
2480 Result += "\"}\n";
2481 }
2482 Result += "\t }\n};\n";
2483 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002484
2485 // Output class methods declared in this protocol.
Chris Lattnerc8581052008-03-16 20:19:15 +00002486 int NumMethods = PDecl->getNumClassMethods();
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002487 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002488 /* struct _objc_protocol_method_list {
2489 int protocol_method_count;
2490 struct protocol_methods protocols[];
2491 }
2492 */
2493 Result += "\nstatic struct {\n";
2494 Result += "\tint protocol_method_count;\n";
2495 Result += "\tstruct protocol_methods protocols[";
2496 Result += utostr(NumMethods);
2497 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002498 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002499 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002500 "{\n\t";
2501 Result += utostr(NumMethods);
2502 Result += "\n";
2503
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002504 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002506 E = PDecl->classmeth_end(); I != E; ++I) {
2507 if (I == PDecl->classmeth_begin())
2508 Result += "\t ,{{(SEL)\"";
2509 else
2510 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002511 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002512 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002513 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002514 Result += "\", \"";
2515 Result += MethodTypeString;
2516 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002517 }
2518 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002519 }
Steve Narofffbfe8252008-05-06 18:26:51 +00002520
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002521 // Output:
2522 /* struct _objc_protocol {
2523 // Objective-C 1.0 extensions
2524 struct _objc_protocol_extension *isa;
2525 char *protocol_name;
2526 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002527 struct _objc_protocol_method_list *instance_methods;
2528 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002529 };
2530 */
2531 static bool objc_protocol = false;
2532 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002533 Result += "\nstruct _objc_protocol {\n";
2534 Result += "\tstruct _objc_protocol_extension *isa;\n";
2535 Result += "\tchar *protocol_name;\n";
2536 Result += "\tstruct _objc_protocol **protocol_list;\n";
2537 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2538 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2539 Result += "};\n";
2540
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002541 objc_protocol = true;
2542 }
2543
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2545 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002546 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002547 "{\n\t0, \"";
2548 Result += PDecl->getName();
2549 Result += "\", 0, ";
Chris Lattnerc8581052008-03-16 20:19:15 +00002550 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002551 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002552 Result += PDecl->getName();
2553 Result += ", ";
2554 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002555 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002556 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002557 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002558 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002559 Result += PDecl->getName();
2560 Result += "\n";
2561 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002562 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002563 Result += "0\n";
2564 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002565
2566 // Mark this protocol as having been generated.
2567 if (!ObjCSynthesizedProtocols.insert(PDecl))
2568 assert(false && "protocol already synthesized");
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002569 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002570 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002571 /* struct _objc_protocol_list {
2572 struct _objc_protocol_list *next;
2573 int protocol_count;
2574 struct _objc_protocol *class_protocols[];
2575 }
2576 */
2577 Result += "\nstatic struct {\n";
2578 Result += "\tstruct _objc_protocol_list *next;\n";
2579 Result += "\tint protocol_count;\n";
2580 Result += "\tstruct _objc_protocol *class_protocols[";
2581 Result += utostr(NumProtocols);
2582 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002583 Result += prefix;
2584 Result += "_PROTOCOLS_";
2585 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002586 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002587 "{\n\t0, ";
2588 Result += utostr(NumProtocols);
2589 Result += "\n";
2590
2591 Result += "\t,{&_OBJC_PROTOCOL_";
2592 Result += Protocols[0]->getName();
2593 Result += " \n";
2594
2595 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002596 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Narofffa8ec622008-04-18 22:15:15 +00002597 Result += "\t ,&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002598 Result += PDecl->getName();
2599 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002600 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002601 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002602 }
2603}
2604
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002605/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002606/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002607void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002608 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002609 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002610 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002611 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002612 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2613 CDecl = CDecl->getNextClassCategory())
2614 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2615 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002616
Chris Lattnereb44eee2007-12-23 01:40:15 +00002617 std::string FullCategoryName = ClassDecl->getName();
2618 FullCategoryName += '_';
2619 FullCategoryName += IDecl->getName();
2620
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002621 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002623 true, "CATEGORY_", FullCategoryName.c_str(),
2624 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002625
2626 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002628 false, "CATEGORY_", FullCategoryName.c_str(),
2629 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002630
2631 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002632 // Null CDecl is case of a category implementation with no category interface
2633 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002634 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002635 CDecl->getNumReferencedProtocols(),
2636 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002637 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002638
2639 /* struct _objc_category {
2640 char *category_name;
2641 char *class_name;
2642 struct _objc_method_list *instance_methods;
2643 struct _objc_method_list *class_methods;
2644 struct _objc_protocol_list *protocols;
2645 // Objective-C 1.0 extensions
2646 uint32_t size; // sizeof (struct _objc_category)
2647 struct _objc_property_list *instance_properties; // category's own
2648 // @property decl.
2649 };
2650 */
2651
2652 static bool objc_category = false;
2653 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002654 Result += "\nstruct _objc_category {\n";
2655 Result += "\tchar *category_name;\n";
2656 Result += "\tchar *class_name;\n";
2657 Result += "\tstruct _objc_method_list *instance_methods;\n";
2658 Result += "\tstruct _objc_method_list *class_methods;\n";
2659 Result += "\tstruct _objc_protocol_list *protocols;\n";
2660 Result += "\tunsigned int size;\n";
2661 Result += "\tstruct _objc_property_list *instance_properties;\n";
2662 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002663 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002664 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002665 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2666 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002667 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002668 Result += IDecl->getName();
2669 Result += "\"\n\t, \"";
2670 Result += ClassDecl->getName();
2671 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002672
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002673 if (IDecl->getNumInstanceMethods() > 0) {
2674 Result += "\t, (struct _objc_method_list *)"
2675 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2676 Result += FullCategoryName;
2677 Result += "\n";
2678 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002679 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002680 Result += "\t, 0\n";
2681 if (IDecl->getNumClassMethods() > 0) {
2682 Result += "\t, (struct _objc_method_list *)"
2683 "&_OBJC_CATEGORY_CLASS_METHODS_";
2684 Result += FullCategoryName;
2685 Result += "\n";
2686 }
2687 else
2688 Result += "\t, 0\n";
2689
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002690 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002691 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2692 Result += FullCategoryName;
2693 Result += "\n";
2694 }
2695 else
2696 Result += "\t, 0\n";
2697 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002698}
2699
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002700/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2701/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002702void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002703 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002704 std::string &Result) {
Steve Naroff5df5b762008-05-07 21:23:49 +00002705 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002706 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002707 if (LangOpts.Microsoft)
2708 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002709 Result += ", ";
2710 Result += ivar->getName();
2711 Result += ")";
2712}
2713
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002714//===----------------------------------------------------------------------===//
2715// Meta Data Emission
2716//===----------------------------------------------------------------------===//
2717
Steve Naroffb29b4272008-04-14 22:03:09 +00002718void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002719 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002720 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002721
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002722 // Explictly declared @interface's are already synthesized.
2723 if (CDecl->ImplicitInterfaceDecl()) {
2724 // FIXME: Implementation of a class with no @interface (legacy) doese not
2725 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002726 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002727 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002728
Chris Lattnerbe6df082007-12-12 07:56:42 +00002729 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002730 unsigned NumIvars = !IDecl->ivar_empty()
2731 ? IDecl->ivar_size()
2732 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002733 if (NumIvars > 0) {
2734 static bool objc_ivar = false;
2735 if (!objc_ivar) {
2736 /* struct _objc_ivar {
2737 char *ivar_name;
2738 char *ivar_type;
2739 int ivar_offset;
2740 };
2741 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 Result += "\nstruct _objc_ivar {\n";
2743 Result += "\tchar *ivar_name;\n";
2744 Result += "\tchar *ivar_type;\n";
2745 Result += "\tint ivar_offset;\n";
2746 Result += "};\n";
2747
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002748 objc_ivar = true;
2749 }
2750
Steve Naroff946a6932008-03-11 00:12:29 +00002751 /* struct {
2752 int ivar_count;
2753 struct _objc_ivar ivar_list[nIvars];
2754 };
2755 */
2756 Result += "\nstatic struct {\n";
2757 Result += "\tint ivar_count;\n";
2758 Result += "\tstruct _objc_ivar ivar_list[";
2759 Result += utostr(NumIvars);
2760 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002761 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002762 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 "{\n\t";
2764 Result += utostr(NumIvars);
2765 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002766
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002767 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002768 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002769 IVI = IDecl->ivar_begin();
2770 IVE = IDecl->ivar_end();
2771 } else {
2772 IVI = CDecl->ivar_begin();
2773 IVE = CDecl->ivar_end();
2774 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002776 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002777 Result += "\", \"";
2778 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002779 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2780 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002781 Result += StrEncoding;
2782 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002783 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002784 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002785 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002786 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002787 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002788 Result += "\", \"";
2789 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002790 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2791 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002792 Result += StrEncoding;
2793 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002794 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002795 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002796 }
2797
2798 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002799 }
2800
2801 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002802 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002803 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002804
2805 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002806 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002807 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002809 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002810 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002812 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002813
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002814
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002815 // Declaration of class/meta-class metadata
2816 /* struct _objc_class {
2817 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002818 const char *super_class_name;
2819 char *name;
2820 long version;
2821 long info;
2822 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002823 struct _objc_ivar_list *ivars;
2824 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002825 struct objc_cache *cache;
2826 struct objc_protocol_list *protocols;
2827 const char *ivar_layout;
2828 struct _objc_class_ext *ext;
2829 };
2830 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002831 static bool objc_class = false;
2832 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002833 Result += "\nstruct _objc_class {\n";
2834 Result += "\tstruct _objc_class *isa;\n";
2835 Result += "\tconst char *super_class_name;\n";
2836 Result += "\tchar *name;\n";
2837 Result += "\tlong version;\n";
2838 Result += "\tlong info;\n";
2839 Result += "\tlong instance_size;\n";
2840 Result += "\tstruct _objc_ivar_list *ivars;\n";
2841 Result += "\tstruct _objc_method_list *methods;\n";
2842 Result += "\tstruct objc_cache *cache;\n";
2843 Result += "\tstruct _objc_protocol_list *protocols;\n";
2844 Result += "\tconst char *ivar_layout;\n";
2845 Result += "\tstruct _objc_class_ext *ext;\n";
2846 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002847 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002848 }
2849
2850 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851 ObjCInterfaceDecl *RootClass = 0;
2852 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002853 while (SuperClass) {
2854 RootClass = SuperClass;
2855 SuperClass = SuperClass->getSuperClass();
2856 }
2857 SuperClass = CDecl->getSuperClass();
2858
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002859 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2860 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002861 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002862 "{\n\t(struct _objc_class *)\"";
2863 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2864 Result += "\"";
2865
2866 if (SuperClass) {
2867 Result += ", \"";
2868 Result += SuperClass->getName();
2869 Result += "\", \"";
2870 Result += CDecl->getName();
2871 Result += "\"";
2872 }
2873 else {
2874 Result += ", 0, \"";
2875 Result += CDecl->getName();
2876 Result += "\"";
2877 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002878 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002879 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002881 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002882 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002883 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002884 Result += "\n";
2885 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002886 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002887 Result += ", 0\n";
2888 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002889 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002890 Result += CDecl->getName();
2891 Result += ",0,0\n";
2892 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002893 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002894 Result += "\t,0,0,0,0\n";
2895 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002896
2897 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002898 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2899 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002900 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002901 "{\n\t&_OBJC_METACLASS_";
2902 Result += CDecl->getName();
2903 if (SuperClass) {
2904 Result += ", \"";
2905 Result += SuperClass->getName();
2906 Result += "\", \"";
2907 Result += CDecl->getName();
2908 Result += "\"";
2909 }
2910 else {
2911 Result += ", 0, \"";
2912 Result += CDecl->getName();
2913 Result += "\"";
2914 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002915 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002916 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002917 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002918 Result += ",0";
2919 else {
2920 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002921 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002922 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002923 if (LangOpts.Microsoft)
2924 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002925 Result += ")";
2926 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002927 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002928 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002929 Result += CDecl->getName();
2930 Result += "\n\t";
2931 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002932 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002933 Result += ",0";
2934 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002935 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002936 Result += CDecl->getName();
2937 Result += ", 0\n\t";
2938 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002939 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += ",0,0";
2941 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002942 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002943 Result += CDecl->getName();
2944 Result += ", 0,0\n";
2945 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002946 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002947 Result += ",0,0,0\n";
2948 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002949}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002950
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002951/// RewriteImplementations - This routine rewrites all method implementations
2952/// and emits meta-data.
2953
Steve Naroffb29b4272008-04-14 22:03:09 +00002954void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002955 int ClsDefCount = ClassImplementation.size();
2956 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002957
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002958 if (ClsDefCount == 0 && CatDefCount == 0)
2959 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002960 // Rewrite implemented methods
2961 for (int i = 0; i < ClsDefCount; i++)
2962 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002963
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002964 for (int i = 0; i < CatDefCount; i++)
2965 RewriteImplementationDecl(CategoryImplementation[i]);
2966
Steve Naroff5df5b762008-05-07 21:23:49 +00002967 // This is needed for determining instance variable offsets.
2968 Result += "#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002969 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002970 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002971 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002972
2973 // For each implemented category, write out all its meta data.
2974 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002975 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002976
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002977 // Write objc_symtab metadata
2978 /*
2979 struct _objc_symtab
2980 {
2981 long sel_ref_cnt;
2982 SEL *refs;
2983 short cls_def_cnt;
2984 short cat_def_cnt;
2985 void *defs[cls_def_cnt + cat_def_cnt];
2986 };
2987 */
2988
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002989 Result += "\nstruct _objc_symtab {\n";
2990 Result += "\tlong sel_ref_cnt;\n";
2991 Result += "\tSEL *refs;\n";
2992 Result += "\tshort cls_def_cnt;\n";
2993 Result += "\tshort cat_def_cnt;\n";
2994 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2995 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002996
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002997 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002998 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002999 Result += "\t0, 0, " + utostr(ClsDefCount)
3000 + ", " + utostr(CatDefCount) + "\n";
3001 for (int i = 0; i < ClsDefCount; i++) {
3002 Result += "\t,&_OBJC_CLASS_";
3003 Result += ClassImplementation[i]->getName();
3004 Result += "\n";
3005 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003006
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003007 for (int i = 0; i < CatDefCount; i++) {
3008 Result += "\t,&_OBJC_CATEGORY_";
3009 Result += CategoryImplementation[i]->getClassInterface()->getName();
3010 Result += "_";
3011 Result += CategoryImplementation[i]->getName();
3012 Result += "\n";
3013 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003014
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003015 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003016
3017 // Write objc_module metadata
3018
3019 /*
3020 struct _objc_module {
3021 long version;
3022 long size;
3023 const char *name;
3024 struct _objc_symtab *symtab;
3025 }
3026 */
3027
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003028 Result += "\nstruct _objc_module {\n";
3029 Result += "\tlong version;\n";
3030 Result += "\tlong size;\n";
3031 Result += "\tconst char *name;\n";
3032 Result += "\tstruct _objc_symtab *symtab;\n";
3033 Result += "};\n\n";
3034 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003035 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003036 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3037 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003038 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003039
3040 if (LangOpts.Microsoft) {
3041 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003042 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003043 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3044 Result += "&_OBJC_MODULES;\n";
3045 Result += "#pragma data_seg(pop)\n\n";
3046 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003047}
Chris Lattner311ff022007-10-16 22:36:42 +00003048
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003049